Add ChronologyProtector to ExternalLBs
[lhc/web/wiklou.git] / includes / Preferences.php
1 <?php
2 /**
3 * Form to edit user preferences.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * We're now using the HTMLForm object with some customisation to generate the
25 * Preferences form. This object handles generic submission, CSRF protection,
26 * layout and other logic in a reusable manner. We subclass it as a PreferencesForm
27 * to make some minor customisations.
28 *
29 * In order to generate the form, the HTMLForm object needs an array structure
30 * detailing the form fields available, and that's what this class is for. Each
31 * element of the array is a basic property-list, including the type of field,
32 * the label it is to be given in the form, callbacks for validation and
33 * 'filtering', and other pertinent information. Note that the 'default' field
34 * is named for generic forms, and does not represent the preference's default
35 * (which is stored in $wgDefaultUserOptions), but the default for the form
36 * field, which should be whatever the user has set for that preference. There
37 * is no need to override it unless you have some special storage logic (for
38 * instance, those not presently stored as options, but which are best set from
39 * the user preferences view).
40 *
41 * Field types are implemented as subclasses of the generic HTMLFormField
42 * object, and typically implement at least getInputHTML, which generates the
43 * HTML for the input field to be placed in the table.
44 *
45 * Once fields have been retrieved and validated, submission logic is handed
46 * over to the tryUISubmit static method of this class.
47 */
48 class Preferences {
49 static $defaultPreferences = null;
50 static $saveFilters = array(
51 'timecorrection' => array( 'Preferences', 'filterTimezoneInput' ),
52 'cols' => array( 'Preferences', 'filterIntval' ),
53 'rows' => array( 'Preferences', 'filterIntval' ),
54 'rclimit' => array( 'Preferences', 'filterIntval' ),
55 'wllimit' => array( 'Preferences', 'filterIntval' ),
56 'searchlimit' => array( 'Preferences', 'filterIntval' ),
57 );
58
59 /**
60 * @throws MWException
61 * @param $user User
62 * @param $context IContextSource
63 * @return array|null
64 */
65 static function getPreferences( $user, IContextSource $context ) {
66 if ( self::$defaultPreferences ) {
67 return self::$defaultPreferences;
68 }
69
70 $defaultPreferences = array();
71
72 self::profilePreferences( $user, $context, $defaultPreferences );
73 self::skinPreferences( $user, $context, $defaultPreferences );
74 self::filesPreferences( $user, $context, $defaultPreferences );
75 self::datetimePreferences( $user, $context, $defaultPreferences );
76 self::renderingPreferences( $user, $context, $defaultPreferences );
77 self::editingPreferences( $user, $context, $defaultPreferences );
78 self::rcPreferences( $user, $context, $defaultPreferences );
79 self::watchlistPreferences( $user, $context, $defaultPreferences );
80 self::searchPreferences( $user, $context, $defaultPreferences );
81 self::miscPreferences( $user, $context, $defaultPreferences );
82
83 wfRunHooks( 'GetPreferences', array( $user, &$defaultPreferences ) );
84
85 ## Remove preferences that wikis don't want to use
86 global $wgHiddenPrefs;
87 foreach ( $wgHiddenPrefs as $pref ) {
88 if ( isset( $defaultPreferences[$pref] ) ) {
89 unset( $defaultPreferences[$pref] );
90 }
91 }
92
93 ## Prod in defaults from the user
94 foreach ( $defaultPreferences as $name => &$info ) {
95 $prefFromUser = self::getOptionFromUser( $name, $info, $user );
96 $field = HTMLForm::loadInputFromParameters( $name, $info ); // For validation
97 $defaultOptions = User::getDefaultOptions();
98 $globalDefault = isset( $defaultOptions[$name] )
99 ? $defaultOptions[$name]
100 : null;
101
102 // If it validates, set it as the default
103 if ( isset( $info['default'] ) ) {
104 // Already set, no problem
105 continue;
106 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
107 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
108 $info['default'] = $prefFromUser;
109 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
110 $info['default'] = $globalDefault;
111 } else {
112 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
113 }
114 }
115
116 self::$defaultPreferences = $defaultPreferences;
117
118 return $defaultPreferences;
119 }
120
121 /**
122 * Pull option from a user account. Handles stuff like array-type preferences.
123 *
124 * @param $name
125 * @param $info
126 * @param $user User
127 * @return array|String
128 */
129 static function getOptionFromUser( $name, $info, $user ) {
130 $val = $user->getOption( $name );
131
132 // Handling for multiselect preferences
133 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
134 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
135 $options = HTMLFormField::flattenOptions( $info['options'] );
136 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
137 $val = array();
138
139 foreach ( $options as $value ) {
140 if ( $user->getOption( "$prefix$value" ) ) {
141 $val[] = $value;
142 }
143 }
144 }
145
146 // Handling for checkmatrix preferences
147 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
148 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
149 $columns = HTMLFormField::flattenOptions( $info['columns'] );
150 $rows = HTMLFormField::flattenOptions( $info['rows'] );
151 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
152 $val = array();
153
154 foreach ( $columns as $column ) {
155 foreach ( $rows as $row ) {
156 if ( $user->getOption( "$prefix-$column-$row" ) ) {
157 $val[] = "$column-$row";
158 }
159 }
160 }
161 }
162
163 return $val;
164 }
165
166 /**
167 * @param $user User
168 * @param $context IContextSource
169 * @param $defaultPreferences
170 * @return void
171 */
172 static function profilePreferences( $user, IContextSource $context, &$defaultPreferences ) {
173 global $wgAuth, $wgContLang, $wgParser, $wgCookieExpiration, $wgLanguageCode,
174 $wgDisableTitleConversion, $wgDisableLangConversion, $wgMaxSigChars,
175 $wgEnableEmail, $wgEmailConfirmToEdit, $wgEnableUserEmail, $wgEmailAuthentication,
176 $wgEnotifWatchlist, $wgEnotifUserTalk, $wgEnotifRevealEditorAddress;
177
178 // retrieving user name for GENDER and misc.
179 $userName = $user->getName();
180
181 ## User info #####################################
182 // Information panel
183 $defaultPreferences['username'] = array(
184 'type' => 'info',
185 'label-message' => array( 'username', $userName ),
186 'default' => $userName,
187 'section' => 'personal/info',
188 );
189
190 $defaultPreferences['userid'] = array(
191 'type' => 'info',
192 'label-message' => array( 'uid', $userName ),
193 'default' => $user->getId(),
194 'section' => 'personal/info',
195 );
196
197 # Get groups to which the user belongs
198 $userEffectiveGroups = $user->getEffectiveGroups();
199 $userGroups = $userMembers = array();
200 foreach ( $userEffectiveGroups as $ueg ) {
201 if ( $ueg == '*' ) {
202 // Skip the default * group, seems useless here
203 continue;
204 }
205 $groupName = User::getGroupName( $ueg );
206 $userGroups[] = User::makeGroupLinkHTML( $ueg, $groupName );
207
208 $memberName = User::getGroupMember( $ueg, $userName );
209 $userMembers[] = User::makeGroupLinkHTML( $ueg, $memberName );
210 }
211 asort( $userGroups );
212 asort( $userMembers );
213
214 $lang = $context->getLanguage();
215
216 $defaultPreferences['usergroups'] = array(
217 'type' => 'info',
218 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
219 count( $userGroups ) )->params( $userName )->parse(),
220 'default' => $context->msg( 'prefs-memberingroups-type',
221 $lang->commaList( $userGroups ),
222 $lang->commaList( $userMembers )
223 )->plain(),
224 'raw' => true,
225 'section' => 'personal/info',
226 );
227
228 $defaultPreferences['editcount'] = array(
229 'type' => 'info',
230 'label-message' => 'prefs-edits',
231 'default' => $lang->formatNum( $user->getEditCount() ),
232 'section' => 'personal/info',
233 );
234
235 if ( $user->getRegistration() ) {
236 $displayUser = $context->getUser();
237 $userRegistration = $user->getRegistration();
238 $defaultPreferences['registrationdate'] = array(
239 'type' => 'info',
240 'label-message' => 'prefs-registration',
241 'default' => $context->msg(
242 'prefs-registration-date-time',
243 $lang->userTimeAndDate( $userRegistration, $displayUser ),
244 $lang->userDate( $userRegistration, $displayUser ),
245 $lang->userTime( $userRegistration, $displayUser )
246 )->parse(),
247 'section' => 'personal/info',
248 );
249 }
250
251 // Actually changeable stuff
252 $defaultPreferences['realname'] = array(
253 'type' => $wgAuth->allowPropChange( 'realname' ) ? 'text' : 'info',
254 'default' => $user->getRealName(),
255 'section' => 'personal/info',
256 'label-message' => 'yourrealname',
257 'help-message' => 'prefs-help-realname',
258 );
259
260 $defaultPreferences['gender'] = array(
261 'type' => 'select',
262 'section' => 'personal/info',
263 'options' => array(
264 $context->msg( 'gender-male' )->text() => 'male',
265 $context->msg( 'gender-female' )->text() => 'female',
266 $context->msg( 'gender-unknown' )->text() => 'unknown',
267 ),
268 'label-message' => 'yourgender',
269 'help-message' => 'prefs-help-gender',
270 );
271
272 if ( $wgAuth->allowPasswordChange() ) {
273 $link = Linker::link( SpecialPage::getTitleFor( 'ChangePassword' ),
274 $context->msg( 'prefs-resetpass' )->escaped(), array(),
275 array( 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ) );
276
277 $defaultPreferences['password'] = array(
278 'type' => 'info',
279 'raw' => true,
280 'default' => $link,
281 'label-message' => 'yourpassword',
282 'section' => 'personal/info',
283 );
284 }
285 if ( $wgCookieExpiration > 0 ) {
286 $defaultPreferences['rememberpassword'] = array(
287 'type' => 'toggle',
288 'label' => $context->msg( 'tog-rememberpassword' )->numParams(
289 ceil( $wgCookieExpiration / ( 3600 * 24 ) ) )->text(),
290 'section' => 'personal/info',
291 );
292 }
293
294 // Language
295 $languages = Language::fetchLanguageNames( null, 'mw' );
296 if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
297 $languages[$wgLanguageCode] = $wgLanguageCode;
298 }
299 ksort( $languages );
300
301 $options = array();
302 foreach ( $languages as $code => $name ) {
303 $display = wfBCP47( $code ) . ' - ' . $name;
304 $options[$display] = $code;
305 }
306 $defaultPreferences['language'] = array(
307 'type' => 'select',
308 'section' => 'personal/i18n',
309 'options' => $options,
310 'label-message' => 'yourlanguage',
311 );
312
313 /* see if there are multiple language variants to choose from*/
314 $variantArray = array();
315 if ( !$wgDisableLangConversion ) {
316 $variants = $wgContLang->getVariants();
317
318 foreach ( $variants as $v ) {
319 $v = str_replace( '_', '-', strtolower( $v ) );
320 $variantArray[$v] = $wgContLang->getVariantname( $v, false );
321 }
322
323 $options = array();
324 foreach ( $variantArray as $code => $name ) {
325 $display = wfBCP47( $code ) . ' - ' . $name;
326 $options[$display] = $code;
327 }
328
329 if ( count( $variantArray ) > 1 ) {
330 $defaultPreferences['variant'] = array(
331 'label-message' => 'yourvariant',
332 'type' => 'select',
333 'options' => $options,
334 'section' => 'personal/i18n',
335 'help-message' => 'prefs-help-variant',
336 );
337 }
338 }
339
340 if ( count( $variantArray ) > 1 && !$wgDisableLangConversion && !$wgDisableTitleConversion ) {
341 $defaultPreferences['noconvertlink'] =
342 array(
343 'type' => 'toggle',
344 'section' => 'personal/i18n',
345 'label-message' => 'tog-noconvertlink',
346 );
347 }
348
349 // show a preview of the old signature first
350 $oldsigWikiText = $wgParser->preSaveTransform( "~~~", $context->getTitle(), $user, ParserOptions::newFromContext( $context ) );
351 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
352 $defaultPreferences['oldsig'] = array(
353 'type' => 'info',
354 'raw' => true,
355 'label-message' => 'tog-oldsig',
356 'default' => $oldsigHTML,
357 'section' => 'personal/signature',
358 );
359 $defaultPreferences['nickname'] = array(
360 'type' => $wgAuth->allowPropChange( 'nickname' ) ? 'text' : 'info',
361 'maxlength' => $wgMaxSigChars,
362 'label-message' => 'yournick',
363 'validation-callback' => array( 'Preferences', 'validateSignature' ),
364 'section' => 'personal/signature',
365 'filter-callback' => array( 'Preferences', 'cleanSignature' ),
366 );
367 $defaultPreferences['fancysig'] = array(
368 'type' => 'toggle',
369 'label-message' => 'tog-fancysig',
370 'help-message' => 'prefs-help-signature', // show general help about signature at the bottom of the section
371 'section' => 'personal/signature'
372 );
373
374 ## Email stuff
375
376 if ( $wgEnableEmail ) {
377 $helpMessages[] = $wgEmailConfirmToEdit
378 ? 'prefs-help-email-required'
379 : 'prefs-help-email';
380
381 if( $wgEnableUserEmail ) {
382 // additional messages when users can send email to each other
383 $helpMessages[] = 'prefs-help-email-others';
384 }
385
386 $link = Linker::link(
387 SpecialPage::getTitleFor( 'ChangeEmail' ),
388 $context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->escaped(),
389 array(),
390 array( 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ) );
391
392 $emailAddress = $user->getEmail() ? htmlspecialchars( $user->getEmail() ) : '';
393 if ( $wgAuth->allowPropChange( 'emailaddress' ) ) {
394 $emailAddress .= $emailAddress == '' ? $link : (
395 $context->msg( 'word-separator' )->plain()
396 . $context->msg( 'parentheses' )->rawParams( $link )->plain()
397 );
398 }
399
400 $defaultPreferences['emailaddress'] = array(
401 'type' => 'info',
402 'raw' => true,
403 'default' => $emailAddress,
404 'label-message' => 'youremail',
405 'section' => 'personal/email',
406 'help-messages' => $helpMessages,
407 # 'cssclass' chosen below
408 );
409
410 $disableEmailPrefs = false;
411
412 $emailauthenticationclass = 'mw-email-not-authenticated';
413 if ( $wgEmailAuthentication ) {
414 if ( $user->getEmail() ) {
415 if ( $user->getEmailAuthenticationTimestamp() ) {
416 // date and time are separate parameters to facilitate localisation.
417 // $time is kept for backward compat reasons.
418 // 'emailauthenticated' is also used in SpecialConfirmemail.php
419 $displayUser = $context->getUser();
420 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
421 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
422 $d = $lang->userDate( $emailTimestamp, $displayUser );
423 $t = $lang->userTime( $emailTimestamp, $displayUser );
424 $emailauthenticated = $context->msg( 'emailauthenticated',
425 $time, $d, $t )->parse() . '<br />';
426 $disableEmailPrefs = false;
427 $emailauthenticationclass = 'mw-email-authenticated';
428 } else {
429 $disableEmailPrefs = true;
430 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
431 Linker::linkKnown(
432 SpecialPage::getTitleFor( 'Confirmemail' ),
433 $context->msg( 'emailconfirmlink' )->escaped()
434 ) . '<br />';
435 $emailauthenticationclass="mw-email-not-authenticated";
436 }
437 } else {
438 $disableEmailPrefs = true;
439 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
440 $emailauthenticationclass = 'mw-email-none';
441 }
442
443 $defaultPreferences['emailauthentication'] = array(
444 'type' => 'info',
445 'raw' => true,
446 'section' => 'personal/email',
447 'label-message' => 'prefs-emailconfirm-label',
448 'default' => $emailauthenticated,
449 # Apply the same CSS class used on the input to the message:
450 'cssclass' => $emailauthenticationclass,
451 );
452 }
453 $defaultPreferences['emailaddress']['cssclass'] = $emailauthenticationclass;
454
455 if ( $wgEnableUserEmail && $user->isAllowed( 'sendemail' ) ) {
456 $defaultPreferences['disablemail'] = array(
457 'type' => 'toggle',
458 'invert' => true,
459 'section' => 'personal/email',
460 'label-message' => 'allowemail',
461 'disabled' => $disableEmailPrefs,
462 );
463 $defaultPreferences['ccmeonemails'] = array(
464 'type' => 'toggle',
465 'section' => 'personal/email',
466 'label-message' => 'tog-ccmeonemails',
467 'disabled' => $disableEmailPrefs,
468 );
469 }
470
471 if ( $wgEnotifWatchlist ) {
472 $defaultPreferences['enotifwatchlistpages'] = array(
473 'type' => 'toggle',
474 'section' => 'personal/email',
475 'label-message' => 'tog-enotifwatchlistpages',
476 'disabled' => $disableEmailPrefs,
477 );
478 }
479 if ( $wgEnotifUserTalk ) {
480 $defaultPreferences['enotifusertalkpages'] = array(
481 'type' => 'toggle',
482 'section' => 'personal/email',
483 'label-message' => 'tog-enotifusertalkpages',
484 'disabled' => $disableEmailPrefs,
485 );
486 }
487 if ( $wgEnotifUserTalk || $wgEnotifWatchlist ) {
488 $defaultPreferences['enotifminoredits'] = array(
489 'type' => 'toggle',
490 'section' => 'personal/email',
491 'label-message' => 'tog-enotifminoredits',
492 'disabled' => $disableEmailPrefs,
493 );
494
495 if ( $wgEnotifRevealEditorAddress ) {
496 $defaultPreferences['enotifrevealaddr'] = array(
497 'type' => 'toggle',
498 'section' => 'personal/email',
499 'label-message' => 'tog-enotifrevealaddr',
500 'disabled' => $disableEmailPrefs,
501 );
502 }
503 }
504 }
505 }
506
507 /**
508 * @param $user User
509 * @param $context IContextSource
510 * @param $defaultPreferences
511 * @return void
512 */
513 static function skinPreferences( $user, IContextSource $context, &$defaultPreferences ) {
514 ## Skin #####################################
515 global $wgAllowUserCss, $wgAllowUserJs;
516
517 $defaultPreferences['skin'] = array(
518 'type' => 'radio',
519 'options' => self::generateSkinOptions( $user, $context ),
520 'label' => '&#160;',
521 'section' => 'rendering/skin',
522 );
523
524 # Create links to user CSS/JS pages for all skins
525 # This code is basically copied from generateSkinOptions(). It'd
526 # be nice to somehow merge this back in there to avoid redundancy.
527 if ( $wgAllowUserCss || $wgAllowUserJs ) {
528 $linkTools = array();
529 $userName = $user->getName();
530
531 if ( $wgAllowUserCss ) {
532 $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
533 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
534 }
535
536 if ( $wgAllowUserJs ) {
537 $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
538 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
539 }
540
541 $defaultPreferences['commoncssjs'] = array(
542 'type' => 'info',
543 'raw' => true,
544 'default' => $context->getLanguage()->pipeList( $linkTools ),
545 'label-message' => 'prefs-common-css-js',
546 'section' => 'rendering/skin',
547 );
548 }
549 }
550
551 /**
552 * @param $user User
553 * @param $context IContextSource
554 * @param $defaultPreferences Array
555 */
556 static function filesPreferences( $user, IContextSource $context, &$defaultPreferences ) {
557 ## Files #####################################
558 $defaultPreferences['imagesize'] = array(
559 'type' => 'select',
560 'options' => self::getImageSizes( $context ),
561 'label-message' => 'imagemaxsize',
562 'section' => 'rendering/files',
563 );
564 $defaultPreferences['thumbsize'] = array(
565 'type' => 'select',
566 'options' => self::getThumbSizes( $context ),
567 'label-message' => 'thumbsize',
568 'section' => 'rendering/files',
569 );
570 }
571
572 /**
573 * @param $user User
574 * @param $context IContextSource
575 * @param $defaultPreferences
576 * @return void
577 */
578 static function datetimePreferences( $user, IContextSource $context, &$defaultPreferences ) {
579 ## Date and time #####################################
580 $dateOptions = self::getDateOptions( $context );
581 if ( $dateOptions ) {
582 $defaultPreferences['date'] = array(
583 'type' => 'radio',
584 'options' => $dateOptions,
585 'label' => '&#160;',
586 'section' => 'datetime/dateformat',
587 );
588 }
589
590 // Info
591 $now = wfTimestampNow();
592 $lang = $context->getLanguage();
593 $nowlocal = Xml::element( 'span', array( 'id' => 'wpLocalTime' ),
594 $lang->time( $now, true ) );
595 $nowserver = $lang->time( $now, false ) .
596 Html::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 + (int)substr( $now, 10, 2 ) );
597
598 $defaultPreferences['nowserver'] = array(
599 'type' => 'info',
600 'raw' => 1,
601 'label-message' => 'servertime',
602 'default' => $nowserver,
603 'section' => 'datetime/timeoffset',
604 );
605
606 $defaultPreferences['nowlocal'] = array(
607 'type' => 'info',
608 'raw' => 1,
609 'label-message' => 'localtime',
610 'default' => $nowlocal,
611 'section' => 'datetime/timeoffset',
612 );
613
614 // Grab existing pref.
615 $tzOffset = $user->getOption( 'timecorrection' );
616 $tz = explode( '|', $tzOffset, 3 );
617
618 $tzOptions = self::getTimezoneOptions( $context );
619
620 $tzSetting = $tzOffset;
621 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
622 $minDiff = $tz[1];
623 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) % 60 );
624 } elseif ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
625 !in_array( $tzOffset, HTMLFormField::flattenOptions( $tzOptions ) ) )
626 {
627 # Timezone offset can vary with DST
628 $userTZ = timezone_open( $tz[2] );
629 if ( $userTZ !== false ) {
630 $minDiff = floor( timezone_offset_get( $userTZ, date_create( 'now' ) ) / 60 );
631 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
632 }
633 }
634
635 $defaultPreferences['timecorrection'] = array(
636 'class' => 'HTMLSelectOrOtherField',
637 'label-message' => 'timezonelegend',
638 'options' => $tzOptions,
639 'default' => $tzSetting,
640 'size' => 20,
641 'section' => 'datetime/timeoffset',
642 );
643 }
644
645 /**
646 * @param $user User
647 * @param $context IContextSource
648 * @param $defaultPreferences Array
649 */
650 static function renderingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
651 ## Page Rendering ##############################
652 global $wgAllowUserCssPrefs;
653 if ( $wgAllowUserCssPrefs ) {
654 $defaultPreferences['underline'] = array(
655 'type' => 'select',
656 'options' => array(
657 $context->msg( 'underline-never' )->text() => 0,
658 $context->msg( 'underline-always' )->text() => 1,
659 $context->msg( 'underline-default' )->text() => 2,
660 ),
661 'label-message' => 'tog-underline',
662 'section' => 'rendering/advancedrendering',
663 );
664 }
665
666 $stubThresholdValues = array( 50, 100, 500, 1000, 2000, 5000, 10000 );
667 $stubThresholdOptions = array( $context->msg( 'stub-threshold-disabled' )->text() => 0 );
668 foreach ( $stubThresholdValues as $value ) {
669 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
670 }
671
672 $defaultPreferences['stubthreshold'] = array(
673 'type' => 'selectorother',
674 'section' => 'rendering/advancedrendering',
675 'options' => $stubThresholdOptions,
676 'size' => 20,
677 'label' => $context->msg( 'stub-threshold' )->text(), // Raw HTML message. Yay?
678 );
679
680 if ( $wgAllowUserCssPrefs ) {
681 $defaultPreferences['showtoc'] = array(
682 'type' => 'toggle',
683 'section' => 'rendering/advancedrendering',
684 'label-message' => 'tog-showtoc',
685 );
686 }
687 $defaultPreferences['nocache'] = array(
688 'type' => 'toggle',
689 'label-message' => 'tog-nocache',
690 'section' => 'rendering/advancedrendering',
691 );
692 $defaultPreferences['showhiddencats'] = array(
693 'type' => 'toggle',
694 'section' => 'rendering/advancedrendering',
695 'label-message' => 'tog-showhiddencats'
696 );
697 $defaultPreferences['showjumplinks'] = array(
698 'type' => 'toggle',
699 'section' => 'rendering/advancedrendering',
700 'label-message' => 'tog-showjumplinks',
701 );
702
703 if ( $wgAllowUserCssPrefs ) {
704 $defaultPreferences['justify'] = array(
705 'type' => 'toggle',
706 'section' => 'rendering/advancedrendering',
707 'label-message' => 'tog-justify',
708 );
709 }
710
711 $defaultPreferences['numberheadings'] = array(
712 'type' => 'toggle',
713 'section' => 'rendering/advancedrendering',
714 'label-message' => 'tog-numberheadings',
715 );
716 }
717
718 /**
719 * @param $user User
720 * @param $context IContextSource
721 * @param $defaultPreferences Array
722 */
723 static function editingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
724 global $wgUseExternalEditor, $wgAllowUserCssPrefs;
725
726 ## Editing #####################################
727 $defaultPreferences['cols'] = array(
728 'type' => 'int',
729 'label-message' => 'columns',
730 'section' => 'editing/textboxsize',
731 'min' => 4,
732 'max' => 1000,
733 );
734 $defaultPreferences['rows'] = array(
735 'type' => 'int',
736 'label-message' => 'rows',
737 'section' => 'editing/textboxsize',
738 'min' => 4,
739 'max' => 1000,
740 );
741
742 if ( $wgAllowUserCssPrefs ) {
743 $defaultPreferences['editfont'] = array(
744 'type' => 'select',
745 'section' => 'editing/advancedediting',
746 'label-message' => 'editfont-style',
747 'options' => array(
748 $context->msg( 'editfont-default' )->text() => 'default',
749 $context->msg( 'editfont-monospace' )->text() => 'monospace',
750 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
751 $context->msg( 'editfont-serif' )->text() => 'serif',
752 )
753 );
754 }
755 $defaultPreferences['previewontop'] = array(
756 'type' => 'toggle',
757 'section' => 'editing/advancedediting',
758 'label-message' => 'tog-previewontop',
759 );
760 $defaultPreferences['previewonfirst'] = array(
761 'type' => 'toggle',
762 'section' => 'editing/advancedediting',
763 'label-message' => 'tog-previewonfirst',
764 );
765
766 if ( $wgAllowUserCssPrefs ) {
767 $defaultPreferences['editsection'] = array(
768 'type' => 'toggle',
769 'section' => 'editing/advancedediting',
770 'label-message' => 'tog-editsection',
771 );
772 }
773 $defaultPreferences['editsectiononrightclick'] = array(
774 'type' => 'toggle',
775 'section' => 'editing/advancedediting',
776 'label-message' => 'tog-editsectiononrightclick',
777 );
778 $defaultPreferences['editondblclick'] = array(
779 'type' => 'toggle',
780 'section' => 'editing/advancedediting',
781 'label-message' => 'tog-editondblclick',
782 );
783 $defaultPreferences['showtoolbar'] = array(
784 'type' => 'toggle',
785 'section' => 'editing/advancedediting',
786 'label-message' => 'tog-showtoolbar',
787 );
788
789 if ( $user->isAllowed( 'minoredit' ) ) {
790 $defaultPreferences['minordefault'] = array(
791 'type' => 'toggle',
792 'section' => 'editing/advancedediting',
793 'label-message' => 'tog-minordefault',
794 );
795 }
796
797 if ( $wgUseExternalEditor ) {
798 $defaultPreferences['externaleditor'] = array(
799 'type' => 'toggle',
800 'section' => 'editing/advancedediting',
801 'label-message' => 'tog-externaleditor',
802 );
803 $defaultPreferences['externaldiff'] = array(
804 'type' => 'toggle',
805 'section' => 'editing/advancedediting',
806 'label-message' => 'tog-externaldiff',
807 );
808 }
809
810 $defaultPreferences['forceeditsummary'] = array(
811 'type' => 'toggle',
812 'section' => 'editing/advancedediting',
813 'label-message' => 'tog-forceeditsummary',
814 );
815
816 $defaultPreferences['uselivepreview'] = array(
817 'type' => 'toggle',
818 'section' => 'editing/advancedediting',
819 'label-message' => 'tog-uselivepreview',
820 );
821
822 $defaultPreferences['useeditwarning'] = array(
823 'type' => 'toggle',
824 'section' => 'editing/advancedediting',
825 'label-message' => 'tog-useeditwarning',
826 );
827
828 }
829
830 /**
831 * @param $user User
832 * @param $context IContextSource
833 * @param $defaultPreferences Array
834 */
835 static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
836 global $wgRCMaxAge, $wgRCShowWatchingUsers;
837
838 ## RecentChanges #####################################
839 $defaultPreferences['rcdays'] = array(
840 'type' => 'float',
841 'label-message' => 'recentchangesdays',
842 'section' => 'rc/displayrc',
843 'min' => 1,
844 'max' => ceil( $wgRCMaxAge / ( 3600 * 24 ) ),
845 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
846 ceil( $wgRCMaxAge / ( 3600 * 24 ) ) )->text()
847 );
848 $defaultPreferences['rclimit'] = array(
849 'type' => 'int',
850 'label-message' => 'recentchangescount',
851 'help-message' => 'prefs-help-recentchangescount',
852 'section' => 'rc/displayrc',
853 );
854 $defaultPreferences['usenewrc'] = array(
855 'type' => 'toggle',
856 'label-message' => 'tog-usenewrc',
857 'section' => 'rc/advancedrc',
858 );
859 $defaultPreferences['hideminor'] = array(
860 'type' => 'toggle',
861 'label-message' => 'tog-hideminor',
862 'section' => 'rc/advancedrc',
863 );
864
865 if ( $user->useRCPatrol() ) {
866 $defaultPreferences['hidepatrolled'] = array(
867 'type' => 'toggle',
868 'section' => 'rc/advancedrc',
869 'label-message' => 'tog-hidepatrolled',
870 );
871 $defaultPreferences['newpageshidepatrolled'] = array(
872 'type' => 'toggle',
873 'section' => 'rc/advancedrc',
874 'label-message' => 'tog-newpageshidepatrolled',
875 );
876 }
877
878 if ( $wgRCShowWatchingUsers ) {
879 $defaultPreferences['shownumberswatching'] = array(
880 'type' => 'toggle',
881 'section' => 'rc/advancedrc',
882 'label-message' => 'tog-shownumberswatching',
883 );
884 }
885 }
886
887 /**
888 * @param $user User
889 * @param $context IContextSource
890 * @param $defaultPreferences
891 */
892 static function watchlistPreferences( $user, IContextSource $context, &$defaultPreferences ) {
893 global $wgUseRCPatrol, $wgEnableAPI, $wgRCMaxAge;
894
895 $watchlistdaysMax = ceil( $wgRCMaxAge / ( 3600 * 24 ) );
896
897 ## Watchlist #####################################
898 $defaultPreferences['watchlistdays'] = array(
899 'type' => 'float',
900 'min' => 0,
901 'max' => $watchlistdaysMax,
902 'section' => 'watchlist/displaywatchlist',
903 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
904 $watchlistdaysMax )->text(),
905 'label-message' => 'prefs-watchlist-days',
906 );
907 $defaultPreferences['wllimit'] = array(
908 'type' => 'int',
909 'min' => 0,
910 'max' => 1000,
911 'label-message' => 'prefs-watchlist-edits',
912 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
913 'section' => 'watchlist/displaywatchlist',
914 );
915 $defaultPreferences['extendwatchlist'] = array(
916 'type' => 'toggle',
917 'section' => 'watchlist/advancedwatchlist',
918 'label-message' => 'tog-extendwatchlist',
919 );
920 $defaultPreferences['watchlisthideminor'] = array(
921 'type' => 'toggle',
922 'section' => 'watchlist/advancedwatchlist',
923 'label-message' => 'tog-watchlisthideminor',
924 );
925 $defaultPreferences['watchlisthidebots'] = array(
926 'type' => 'toggle',
927 'section' => 'watchlist/advancedwatchlist',
928 'label-message' => 'tog-watchlisthidebots',
929 );
930 $defaultPreferences['watchlisthideown'] = array(
931 'type' => 'toggle',
932 'section' => 'watchlist/advancedwatchlist',
933 'label-message' => 'tog-watchlisthideown',
934 );
935 $defaultPreferences['watchlisthideanons'] = array(
936 'type' => 'toggle',
937 'section' => 'watchlist/advancedwatchlist',
938 'label-message' => 'tog-watchlisthideanons',
939 );
940 $defaultPreferences['watchlisthideliu'] = array(
941 'type' => 'toggle',
942 'section' => 'watchlist/advancedwatchlist',
943 'label-message' => 'tog-watchlisthideliu',
944 );
945
946 if ( $wgUseRCPatrol ) {
947 $defaultPreferences['watchlisthidepatrolled'] = array(
948 'type' => 'toggle',
949 'section' => 'watchlist/advancedwatchlist',
950 'label-message' => 'tog-watchlisthidepatrolled',
951 );
952 }
953
954 if ( $wgEnableAPI ) {
955 # Some random gibberish as a proposed default
956 // @todo Fixme: this should use CryptRand but we may not want to read urandom on every view
957 $hash = sha1( mt_rand() . microtime( true ) );
958
959 $defaultPreferences['watchlisttoken'] = array(
960 'type' => 'text',
961 'section' => 'watchlist/advancedwatchlist',
962 'label-message' => 'prefs-watchlist-token',
963 'help' => $context->msg( 'prefs-help-watchlist-token', $hash )->escaped()
964 );
965 }
966
967 $watchTypes = array(
968 'edit' => 'watchdefault',
969 'move' => 'watchmoves',
970 'delete' => 'watchdeletion'
971 );
972
973 // Kinda hacky
974 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
975 $watchTypes['read'] = 'watchcreations';
976 }
977
978 foreach ( $watchTypes as $action => $pref ) {
979 if ( $user->isAllowed( $action ) ) {
980 $defaultPreferences[$pref] = array(
981 'type' => 'toggle',
982 'section' => 'watchlist/advancedwatchlist',
983 'label-message' => "tog-$pref",
984 );
985 }
986 }
987 }
988
989 /**
990 * @param $user User
991 * @param $context IContextSource
992 * @param $defaultPreferences Array
993 */
994 static function searchPreferences( $user, IContextSource $context, &$defaultPreferences ) {
995 global $wgContLang, $wgVectorUseSimpleSearch;
996
997 ## Search #####################################
998 $defaultPreferences['searchlimit'] = array(
999 'type' => 'int',
1000 'label-message' => 'resultsperpage',
1001 'section' => 'searchoptions/displaysearchoptions',
1002 'min' => 0,
1003 );
1004
1005 if ( $wgVectorUseSimpleSearch ) {
1006 $defaultPreferences['vector-simplesearch'] = array(
1007 'type' => 'toggle',
1008 'label-message' => 'vector-simplesearch-preference',
1009 'section' => 'searchoptions/displaysearchoptions',
1010 );
1011 }
1012
1013 $defaultPreferences['disablesuggest'] = array(
1014 'type' => 'toggle',
1015 'label-message' => 'mwsuggest-disable',
1016 'section' => 'searchoptions/displaysearchoptions',
1017 );
1018
1019 $defaultPreferences['searcheverything'] = array(
1020 'type' => 'toggle',
1021 'label-message' => 'searcheverything-enable',
1022 'section' => 'searchoptions/advancedsearchoptions',
1023 );
1024
1025 $nsOptions = $wgContLang->getFormattedNamespaces();
1026 $nsOptions[0] = $context->msg( 'blanknamespace' )->text();
1027 foreach ( $nsOptions as $ns => $name ) {
1028 if ( $ns < 0 )
1029 unset( $nsOptions[$ns] );
1030 }
1031
1032 $defaultPreferences['searchnamespaces'] = array(
1033 'type' => 'multiselect',
1034 'label-message' => 'defaultns',
1035 'options' => array_flip( $nsOptions ),
1036 'section' => 'searchoptions/advancedsearchoptions',
1037 'prefix' => 'searchNs',
1038 );
1039 }
1040
1041 /**
1042 * @param $user User
1043 * @param $context IContextSource
1044 * @param $defaultPreferences Array
1045 */
1046 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1047 global $wgContLang;
1048
1049 ## Misc #####################################
1050 $defaultPreferences['diffonly'] = array(
1051 'type' => 'toggle',
1052 'section' => 'misc/diffs',
1053 'label-message' => 'tog-diffonly',
1054 );
1055 $defaultPreferences['norollbackdiff'] = array(
1056 'type' => 'toggle',
1057 'section' => 'misc/diffs',
1058 'label-message' => 'tog-norollbackdiff',
1059 );
1060
1061 // Stuff from Language::getExtraUserToggles()
1062 $toggles = $wgContLang->getExtraUserToggles();
1063
1064 foreach ( $toggles as $toggle ) {
1065 $defaultPreferences[$toggle] = array(
1066 'type' => 'toggle',
1067 'section' => 'personal/i18n',
1068 'label-message' => "tog-$toggle",
1069 );
1070 }
1071 }
1072
1073 /**
1074 * @param $user User The User object
1075 * @param $context IContextSource
1076 * @return Array: text/links to display as key; $skinkey as value
1077 */
1078 static function generateSkinOptions( $user, IContextSource $context ) {
1079 global $wgDefaultSkin, $wgAllowUserCss, $wgAllowUserJs;
1080 $ret = array();
1081
1082 $mptitle = Title::newMainPage();
1083 $previewtext = $context->msg( 'skin-preview' )->text();
1084
1085 # Only show members of Skin::getSkinNames() rather than
1086 # $skinNames (skins is all skin names from Language.php)
1087 $validSkinNames = Skin::getUsableSkins();
1088
1089 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1090 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1091 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1092 $msg = $context->msg( "skinname-{$skinkey}" );
1093 if ( $msg->exists() ) {
1094 $skinname = htmlspecialchars( $msg->text() );
1095 }
1096 }
1097 asort( $validSkinNames );
1098
1099 foreach ( $validSkinNames as $skinkey => $sn ) {
1100 $linkTools = array();
1101
1102 # Mark the default skin
1103 if ( $skinkey == $wgDefaultSkin ) {
1104 $linkTools[] = $context->msg( 'default' )->escaped();
1105 }
1106
1107 # Create preview link
1108 $mplink = htmlspecialchars( $mptitle->getLocalURL( "useskin=$skinkey" ) );
1109 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1110
1111 # Create links to user CSS/JS pages
1112 if ( $wgAllowUserCss ) {
1113 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1114 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1115 }
1116
1117 if ( $wgAllowUserJs ) {
1118 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1119 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1120 }
1121
1122 $display = $sn . ' ' . $context->msg( 'parentheses', $context->getLanguage()->pipeList( $linkTools ) )->text();
1123 $ret[$display] = $skinkey;
1124 }
1125
1126 return $ret;
1127 }
1128
1129 /**
1130 * @param $context IContextSource
1131 * @return array
1132 */
1133 static function getDateOptions( IContextSource $context ) {
1134 $lang = $context->getLanguage();
1135 $dateopts = $lang->getDatePreferences();
1136
1137 $ret = array();
1138
1139 if ( $dateopts ) {
1140 if ( !in_array( 'default', $dateopts ) ) {
1141 $dateopts[] = 'default'; // Make sure default is always valid
1142 // Bug 19237
1143 }
1144
1145 // KLUGE: site default might not be valid for user language
1146 global $wgDefaultUserOptions;
1147 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1148 $wgDefaultUserOptions['date'] = 'default';
1149 }
1150
1151 $epoch = wfTimestampNow();
1152 foreach ( $dateopts as $key ) {
1153 if ( $key == 'default' ) {
1154 $formatted = $context->msg( 'datedefault' )->escaped();
1155 } else {
1156 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1157 }
1158 $ret[$formatted] = $key;
1159 }
1160 }
1161 return $ret;
1162 }
1163
1164 /**
1165 * @param $context IContextSource
1166 * @return array
1167 */
1168 static function getImageSizes( IContextSource $context ) {
1169 global $wgImageLimits;
1170
1171 $ret = array();
1172 $pixels = $context->msg( 'unit-pixel' )->text();
1173
1174 foreach ( $wgImageLimits as $index => $limits ) {
1175 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1176 $ret[$display] = $index;
1177 }
1178
1179 return $ret;
1180 }
1181
1182 /**
1183 * @param $context IContextSource
1184 * @return array
1185 */
1186 static function getThumbSizes( IContextSource $context ) {
1187 global $wgThumbLimits;
1188
1189 $ret = array();
1190 $pixels = $context->msg( 'unit-pixel' )->text();
1191
1192 foreach ( $wgThumbLimits as $index => $size ) {
1193 $display = $size . $pixels;
1194 $ret[$display] = $index;
1195 }
1196
1197 return $ret;
1198 }
1199
1200 /**
1201 * @param $signature string
1202 * @param $alldata array
1203 * @param $form HTMLForm
1204 * @return bool|string
1205 */
1206 static function validateSignature( $signature, $alldata, $form ) {
1207 global $wgParser, $wgMaxSigChars;
1208 if ( mb_strlen( $signature ) > $wgMaxSigChars ) {
1209 return Xml::element( 'span', array( 'class' => 'error' ),
1210 $form->msg( 'badsiglength' )->numParams( $wgMaxSigChars )->text() );
1211 } elseif ( isset( $alldata['fancysig'] ) &&
1212 $alldata['fancysig'] &&
1213 false === $wgParser->validateSig( $signature ) ) {
1214 return Xml::element( 'span', array( 'class' => 'error' ), $form->msg( 'badsig' )->text() );
1215 } else {
1216 return true;
1217 }
1218 }
1219
1220 /**
1221 * @param $signature string
1222 * @param $alldata array
1223 * @param $form HTMLForm
1224 * @return string
1225 */
1226 static function cleanSignature( $signature, $alldata, $form ) {
1227 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1228 global $wgParser;
1229 $signature = $wgParser->cleanSig( $signature );
1230 } else {
1231 // When no fancy sig used, make sure ~{3,5} get removed.
1232 $signature = Parser::cleanSigInSig( $signature );
1233 }
1234
1235 return $signature;
1236 }
1237
1238 /**
1239 * @param $user User
1240 * @param $context IContextSource
1241 * @param $formClass string
1242 * @param array $remove array of items to remove
1243 * @return HtmlForm
1244 */
1245 static function getFormObject( $user, IContextSource $context, $formClass = 'PreferencesForm', array $remove = array() ) {
1246 $formDescriptor = Preferences::getPreferences( $user, $context );
1247 if ( count( $remove ) ) {
1248 $removeKeys = array_flip( $remove );
1249 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1250 }
1251
1252 // Remove type=api preferences. They are not intended for rendering in the form.
1253 foreach ( $formDescriptor as $name => $info ) {
1254 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1255 unset( $formDescriptor[$name] );
1256 }
1257 }
1258
1259 /**
1260 * @var $htmlForm PreferencesForm
1261 */
1262 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1263
1264 $htmlForm->setModifiedUser( $user );
1265 $htmlForm->setId( 'mw-prefs-form' );
1266 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1267 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1268 $htmlForm->setSubmitTooltip( 'preferences-save' );
1269 $htmlForm->setSubmitID( 'prefsubmit' );
1270 $htmlForm->setSubmitCallback( array( 'Preferences', 'tryFormSubmit' ) );
1271
1272 return $htmlForm;
1273 }
1274
1275 /**
1276 * @return array
1277 */
1278 static function getTimezoneOptions( IContextSource $context ) {
1279 $opt = array();
1280
1281 global $wgLocalTZoffset, $wgLocaltimezone;
1282 // Check that $wgLocalTZoffset is the same as $wgLocaltimezone
1283 if ( $wgLocalTZoffset == date( 'Z' ) / 60 ) {
1284 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $wgLocaltimezone )->text();
1285 } else {
1286 $tzstring = sprintf( '%+03d:%02d', floor( $wgLocalTZoffset / 60 ), abs( $wgLocalTZoffset ) % 60 );
1287 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1288 }
1289 $opt[$server_tz_msg] = "System|$wgLocalTZoffset";
1290 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1291 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1292
1293 if ( function_exists( 'timezone_identifiers_list' ) ) {
1294 # Read timezone list
1295 $tzs = timezone_identifiers_list();
1296 sort( $tzs );
1297
1298 $tzRegions = array();
1299 $tzRegions['Africa'] = $context->msg( 'timezoneregion-africa' )->text();
1300 $tzRegions['America'] = $context->msg( 'timezoneregion-america' )->text();
1301 $tzRegions['Antarctica'] = $context->msg( 'timezoneregion-antarctica' )->text();
1302 $tzRegions['Arctic'] = $context->msg( 'timezoneregion-arctic' )->text();
1303 $tzRegions['Asia'] = $context->msg( 'timezoneregion-asia' )->text();
1304 $tzRegions['Atlantic'] = $context->msg( 'timezoneregion-atlantic' )->text();
1305 $tzRegions['Australia'] = $context->msg( 'timezoneregion-australia' )->text();
1306 $tzRegions['Europe'] = $context->msg( 'timezoneregion-europe' )->text();
1307 $tzRegions['Indian'] = $context->msg( 'timezoneregion-indian' )->text();
1308 $tzRegions['Pacific'] = $context->msg( 'timezoneregion-pacific' )->text();
1309 asort( $tzRegions );
1310
1311 $prefill = array_fill_keys( array_values( $tzRegions ), array() );
1312 $opt = array_merge( $opt, $prefill );
1313
1314 $now = date_create( 'now' );
1315
1316 foreach ( $tzs as $tz ) {
1317 $z = explode( '/', $tz, 2 );
1318
1319 # timezone_identifiers_list() returns a number of
1320 # backwards-compatibility entries. This filters them out of the
1321 # list presented to the user.
1322 if ( count( $z ) != 2 || !array_key_exists( $z[0], $tzRegions ) ) {
1323 continue;
1324 }
1325
1326 # Localize region
1327 $z[0] = $tzRegions[$z[0]];
1328
1329 $minDiff = floor( timezone_offset_get( timezone_open( $tz ), $now ) / 60 );
1330
1331 $display = str_replace( '_', ' ', $z[0] . '/' . $z[1] );
1332 $value = "ZoneInfo|$minDiff|$tz";
1333
1334 $opt[$z[0]][$display] = $value;
1335 }
1336 }
1337 return $opt;
1338 }
1339
1340 /**
1341 * @param $value
1342 * @param $alldata
1343 * @return int
1344 */
1345 static function filterIntval( $value, $alldata ) {
1346 return intval( $value );
1347 }
1348
1349 /**
1350 * @param $tz
1351 * @param $alldata
1352 * @return string
1353 */
1354 static function filterTimezoneInput( $tz, $alldata ) {
1355 $data = explode( '|', $tz, 3 );
1356 switch ( $data[0] ) {
1357 case 'ZoneInfo':
1358 case 'System':
1359 return $tz;
1360 default:
1361 $data = explode( ':', $tz, 2 );
1362 if ( count( $data ) == 2 ) {
1363 $data[0] = intval( $data[0] );
1364 $data[1] = intval( $data[1] );
1365 $minDiff = abs( $data[0] ) * 60 + $data[1];
1366 if ( $data[0] < 0 ) $minDiff = - $minDiff;
1367 } else {
1368 $minDiff = intval( $data[0] ) * 60;
1369 }
1370
1371 # Max is +14:00 and min is -12:00, see:
1372 # http://en.wikipedia.org/wiki/Timezone
1373 $minDiff = min( $minDiff, 840 ); # 14:00
1374 $minDiff = max( $minDiff, - 720 ); # -12:00
1375 return 'Offset|' . $minDiff;
1376 }
1377 }
1378
1379 /**
1380 * @param $formData
1381 * @param $form PreferencesForm
1382 * @param $entryPoint string
1383 * @return bool|Status|string
1384 */
1385 static function tryFormSubmit( $formData, $form, $entryPoint = 'internal' ) {
1386 global $wgHiddenPrefs, $wgAuth;
1387
1388 $user = $form->getModifiedUser();
1389 $result = true;
1390
1391 // Filter input
1392 foreach ( array_keys( $formData ) as $name ) {
1393 if ( isset( self::$saveFilters[$name] ) ) {
1394 $formData[$name] =
1395 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1396 }
1397 }
1398
1399 // Stuff that shouldn't be saved as a preference.
1400 $saveBlacklist = array(
1401 'realname',
1402 'emailaddress',
1403 );
1404
1405 // Fortunately, the realname field is MUCH simpler
1406 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
1407 $realName = $formData['realname'];
1408 $user->setRealName( $realName );
1409 }
1410
1411 foreach ( $saveBlacklist as $b ) {
1412 unset( $formData[$b] );
1413 }
1414
1415 # If users have saved a value for a preference which has subsequently been disabled
1416 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1417 # is subsequently re-enabled
1418 # TODO: maintenance script to actually delete these
1419 foreach( $wgHiddenPrefs as $pref ) {
1420 # If the user has not set a non-default value here, the default will be returned
1421 # and subsequently discarded
1422 $formData[$pref] = $user->getOption( $pref, null, true );
1423 }
1424
1425 // Keep old preferences from interfering due to back-compat code, etc.
1426 $user->resetOptions( 'unused', $form->getContext() );
1427
1428 foreach ( $formData as $key => $value ) {
1429 $user->setOption( $key, $value );
1430 }
1431
1432 $user->saveSettings();
1433
1434 $wgAuth->updateExternalDB( $user );
1435
1436 return $result;
1437 }
1438
1439 /**
1440 * @param $formData
1441 * @param $form PreferencesForm
1442 * @return Status
1443 */
1444 public static function tryUISubmit( $formData, $form ) {
1445 $res = self::tryFormSubmit( $formData, $form, 'ui' );
1446
1447 if ( $res ) {
1448 $urlOptions = array( 'success' => 1 );
1449
1450 if ( $res === 'eauth' ) {
1451 $urlOptions['eauth'] = 1;
1452 }
1453
1454 $urlOptions += $form->getExtraSuccessRedirectParameters();
1455
1456 $url = $form->getTitle()->getFullURL( $urlOptions );
1457
1458 $form->getContext()->getOutput()->redirect( $url );
1459 }
1460
1461 return Status::newGood();
1462 }
1463
1464 /**
1465 * Try to set a user's email address.
1466 * This does *not* try to validate the address.
1467 * Caller is responsible for checking $wgAuth.
1468 *
1469 * @deprecated in 1.20; use User::setEmailWithConfirmation() instead.
1470 * @param $user User
1471 * @param string $newaddr New email address
1472 * @return Array (true on success or Status on failure, info string)
1473 */
1474 public static function trySetUserEmail( User $user, $newaddr ) {
1475 wfDeprecated( __METHOD__, '1.20' );
1476
1477 $result = $user->setEmailWithConfirmation( $newaddr );
1478 if ( $result->isGood() ) {
1479 return array( true, $result->value );
1480 } else {
1481 return array( $result, 'mailerror' );
1482 }
1483 }
1484
1485 /**
1486 * @deprecated in 1.19; will be removed in 1.20.
1487 * @param $user User
1488 * @return array
1489 */
1490 public static function loadOldSearchNs( $user ) {
1491 wfDeprecated( __METHOD__, '1.19' );
1492
1493 $searchableNamespaces = SearchEngine::searchableNamespaces();
1494 // Back compat with old format
1495 $arr = array();
1496
1497 foreach ( $searchableNamespaces as $ns => $name ) {
1498 if ( $user->getOption( 'searchNs' . $ns ) ) {
1499 $arr[] = $ns;
1500 }
1501 }
1502
1503 return $arr;
1504 }
1505 }
1506
1507 /** Some tweaks to allow js prefs to work */
1508 class PreferencesForm extends HTMLForm {
1509 // Override default value from HTMLForm
1510 protected $mSubSectionBeforeFields = false;
1511
1512 private $modifiedUser;
1513
1514 /**
1515 * @param $user User
1516 */
1517 public function setModifiedUser( $user ) {
1518 $this->modifiedUser = $user;
1519 }
1520
1521 /**
1522 * @return User
1523 */
1524 public function getModifiedUser() {
1525 if ( $this->modifiedUser === null ) {
1526 return $this->getUser();
1527 } else {
1528 return $this->modifiedUser;
1529 }
1530 }
1531
1532 /**
1533 * Get extra parameters for the query string when redirecting after
1534 * successful save.
1535 *
1536 * @return array()
1537 */
1538 public function getExtraSuccessRedirectParameters() {
1539 return array();
1540 }
1541
1542 /**
1543 * @param $html string
1544 * @return String
1545 */
1546 function wrapForm( $html ) {
1547 $html = Xml::tags( 'div', array( 'id' => 'preferences' ), $html );
1548
1549 return parent::wrapForm( $html );
1550 }
1551
1552 /**
1553 * @return String
1554 */
1555 function getButtons() {
1556 $html = parent::getButtons();
1557
1558 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1559
1560 $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped() );
1561
1562 $html = Xml::tags( 'div', array( 'class' => 'mw-prefs-buttons' ), $html );
1563
1564 return $html;
1565 }
1566
1567 /**
1568 * @param $data array
1569 * @return array
1570 */
1571 function filterDataForSubmit( $data ) {
1572 // Support for separating multi-option preferences into multiple preferences
1573 // Due to lack of array support.
1574 foreach ( $this->mFlatFields as $fieldname => $field ) {
1575 $info = $field->mParams;
1576
1577 if ( $field instanceof HTMLMultiSelectField ) {
1578 $options = HTMLFormField::flattenOptions( $info['options'] );
1579 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1580
1581 foreach ( $options as $opt ) {
1582 $data["$prefix$opt"] = in_array( $opt, $data[$fieldname] );
1583 }
1584
1585 unset( $data[$fieldname] );
1586
1587 } elseif ( $field instanceof HTMLCheckMatrix ) {
1588 $columns = HTMLFormField::flattenOptions( $info['columns'] );
1589 $rows = HTMLFormField::flattenOptions( $info['rows'] );
1590 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1591 foreach ( $columns as $column ) {
1592 foreach ( $rows as $row ) {
1593 // Make sure option hasn't been removed
1594 if ( !isset( $info['remove-options'] )
1595 || !in_array( "$column-$row", $info['remove-options'] ) )
1596 {
1597 $data["$prefix-$column-$row"] = in_array( "$column-$row", $data[$fieldname] );
1598 }
1599 }
1600 }
1601
1602 unset( $data[$fieldname] );
1603 }
1604 }
1605
1606 return $data;
1607 }
1608
1609 /**
1610 * Get the whole body of the form.
1611 * @return string
1612 */
1613 function getBody() {
1614 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1615 }
1616
1617 /**
1618 * Get the "<legend>" for a given section key. Normally this is the
1619 * prefs-$key message but we'll allow extensions to override it.
1620 * @param $key string
1621 * @return string
1622 */
1623 function getLegend( $key ) {
1624 $legend = parent::getLegend( $key );
1625 wfRunHooks( 'PreferencesGetLegend', array( $this, $key, &$legend ) );
1626 return $legend;
1627 }
1628 }