HTMLForm entity labels are now optional and escaped
[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-raw' => $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 $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 $defaultPreferences['forceeditsummary'] = array(
798 'type' => 'toggle',
799 'section' => 'editing/advancedediting',
800 'label-message' => 'tog-forceeditsummary',
801 );
802
803 $defaultPreferences['uselivepreview'] = array(
804 'type' => 'toggle',
805 'section' => 'editing/advancedediting',
806 'label-message' => 'tog-uselivepreview',
807 );
808
809 $defaultPreferences['useeditwarning'] = array(
810 'type' => 'toggle',
811 'section' => 'editing/advancedediting',
812 'label-message' => 'tog-useeditwarning',
813 );
814
815 }
816
817 /**
818 * @param $user User
819 * @param $context IContextSource
820 * @param $defaultPreferences Array
821 */
822 static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
823 global $wgRCMaxAge, $wgRCShowWatchingUsers;
824
825 ## RecentChanges #####################################
826 $defaultPreferences['rcdays'] = array(
827 'type' => 'float',
828 'label-message' => 'recentchangesdays',
829 'section' => 'rc/displayrc',
830 'min' => 1,
831 'max' => ceil( $wgRCMaxAge / ( 3600 * 24 ) ),
832 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
833 ceil( $wgRCMaxAge / ( 3600 * 24 ) ) )->text()
834 );
835 $defaultPreferences['rclimit'] = array(
836 'type' => 'int',
837 'label-message' => 'recentchangescount',
838 'help-message' => 'prefs-help-recentchangescount',
839 'section' => 'rc/displayrc',
840 );
841 $defaultPreferences['usenewrc'] = array(
842 'type' => 'toggle',
843 'label-message' => 'tog-usenewrc',
844 'section' => 'rc/advancedrc',
845 );
846 $defaultPreferences['hideminor'] = array(
847 'type' => 'toggle',
848 'label-message' => 'tog-hideminor',
849 'section' => 'rc/advancedrc',
850 );
851
852 if ( $user->useRCPatrol() ) {
853 $defaultPreferences['hidepatrolled'] = array(
854 'type' => 'toggle',
855 'section' => 'rc/advancedrc',
856 'label-message' => 'tog-hidepatrolled',
857 );
858 $defaultPreferences['newpageshidepatrolled'] = array(
859 'type' => 'toggle',
860 'section' => 'rc/advancedrc',
861 'label-message' => 'tog-newpageshidepatrolled',
862 );
863 }
864
865 if ( $wgRCShowWatchingUsers ) {
866 $defaultPreferences['shownumberswatching'] = array(
867 'type' => 'toggle',
868 'section' => 'rc/advancedrc',
869 'label-message' => 'tog-shownumberswatching',
870 );
871 }
872 }
873
874 /**
875 * @param $user User
876 * @param $context IContextSource
877 * @param $defaultPreferences
878 */
879 static function watchlistPreferences( $user, IContextSource $context, &$defaultPreferences ) {
880 global $wgUseRCPatrol, $wgEnableAPI, $wgRCMaxAge;
881
882 $watchlistdaysMax = ceil( $wgRCMaxAge / ( 3600 * 24 ) );
883
884 ## Watchlist #####################################
885 $defaultPreferences['watchlistdays'] = array(
886 'type' => 'float',
887 'min' => 0,
888 'max' => $watchlistdaysMax,
889 'section' => 'watchlist/displaywatchlist',
890 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
891 $watchlistdaysMax )->text(),
892 'label-message' => 'prefs-watchlist-days',
893 );
894 $defaultPreferences['wllimit'] = array(
895 'type' => 'int',
896 'min' => 0,
897 'max' => 1000,
898 'label-message' => 'prefs-watchlist-edits',
899 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
900 'section' => 'watchlist/displaywatchlist',
901 );
902 $defaultPreferences['extendwatchlist'] = array(
903 'type' => 'toggle',
904 'section' => 'watchlist/advancedwatchlist',
905 'label-message' => 'tog-extendwatchlist',
906 );
907 $defaultPreferences['watchlisthideminor'] = array(
908 'type' => 'toggle',
909 'section' => 'watchlist/advancedwatchlist',
910 'label-message' => 'tog-watchlisthideminor',
911 );
912 $defaultPreferences['watchlisthidebots'] = array(
913 'type' => 'toggle',
914 'section' => 'watchlist/advancedwatchlist',
915 'label-message' => 'tog-watchlisthidebots',
916 );
917 $defaultPreferences['watchlisthideown'] = array(
918 'type' => 'toggle',
919 'section' => 'watchlist/advancedwatchlist',
920 'label-message' => 'tog-watchlisthideown',
921 );
922 $defaultPreferences['watchlisthideanons'] = array(
923 'type' => 'toggle',
924 'section' => 'watchlist/advancedwatchlist',
925 'label-message' => 'tog-watchlisthideanons',
926 );
927 $defaultPreferences['watchlisthideliu'] = array(
928 'type' => 'toggle',
929 'section' => 'watchlist/advancedwatchlist',
930 'label-message' => 'tog-watchlisthideliu',
931 );
932
933 if ( $wgUseRCPatrol ) {
934 $defaultPreferences['watchlisthidepatrolled'] = array(
935 'type' => 'toggle',
936 'section' => 'watchlist/advancedwatchlist',
937 'label-message' => 'tog-watchlisthidepatrolled',
938 );
939 }
940
941 if ( $wgEnableAPI ) {
942 # Some random gibberish as a proposed default
943 // @todo Fixme: this should use CryptRand but we may not want to read urandom on every view
944 $hash = sha1( mt_rand() . microtime( true ) );
945
946 $defaultPreferences['watchlisttoken'] = array(
947 'type' => 'text',
948 'section' => 'watchlist/advancedwatchlist',
949 'label-message' => 'prefs-watchlist-token',
950 'help' => $context->msg( 'prefs-help-watchlist-token', $hash )->escaped()
951 );
952 }
953
954 $watchTypes = array(
955 'edit' => 'watchdefault',
956 'move' => 'watchmoves',
957 'delete' => 'watchdeletion'
958 );
959
960 // Kinda hacky
961 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
962 $watchTypes['read'] = 'watchcreations';
963 }
964
965 foreach ( $watchTypes as $action => $pref ) {
966 if ( $user->isAllowed( $action ) ) {
967 $defaultPreferences[$pref] = array(
968 'type' => 'toggle',
969 'section' => 'watchlist/advancedwatchlist',
970 'label-message' => "tog-$pref",
971 );
972 }
973 }
974 }
975
976 /**
977 * @param $user User
978 * @param $context IContextSource
979 * @param $defaultPreferences Array
980 */
981 static function searchPreferences( $user, IContextSource $context, &$defaultPreferences ) {
982 global $wgContLang, $wgVectorUseSimpleSearch;
983
984 ## Search #####################################
985 $defaultPreferences['searchlimit'] = array(
986 'type' => 'int',
987 'label-message' => 'resultsperpage',
988 'section' => 'searchoptions/displaysearchoptions',
989 'min' => 0,
990 );
991
992 if ( $wgVectorUseSimpleSearch ) {
993 $defaultPreferences['vector-simplesearch'] = array(
994 'type' => 'toggle',
995 'label-message' => 'vector-simplesearch-preference',
996 'section' => 'searchoptions/displaysearchoptions',
997 );
998 }
999
1000 $defaultPreferences['disablesuggest'] = array(
1001 'type' => 'toggle',
1002 'label-message' => 'mwsuggest-disable',
1003 'section' => 'searchoptions/displaysearchoptions',
1004 );
1005
1006 $defaultPreferences['searcheverything'] = array(
1007 'type' => 'toggle',
1008 'label-message' => 'searcheverything-enable',
1009 'section' => 'searchoptions/advancedsearchoptions',
1010 );
1011
1012 $nsOptions = $wgContLang->getFormattedNamespaces();
1013 $nsOptions[0] = $context->msg( 'blanknamespace' )->text();
1014 foreach ( $nsOptions as $ns => $name ) {
1015 if ( $ns < 0 ) {
1016 unset( $nsOptions[$ns] );
1017 }
1018 }
1019
1020 $defaultPreferences['searchnamespaces'] = array(
1021 'type' => 'multiselect',
1022 'label-message' => 'defaultns',
1023 'options' => array_flip( $nsOptions ),
1024 'section' => 'searchoptions/advancedsearchoptions',
1025 'prefix' => 'searchNs',
1026 );
1027 }
1028
1029 /**
1030 * @param $user User
1031 * @param $context IContextSource
1032 * @param $defaultPreferences Array
1033 */
1034 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1035 global $wgContLang;
1036
1037 ## Misc #####################################
1038 $defaultPreferences['diffonly'] = array(
1039 'type' => 'toggle',
1040 'section' => 'misc/diffs',
1041 'label-message' => 'tog-diffonly',
1042 );
1043 $defaultPreferences['norollbackdiff'] = array(
1044 'type' => 'toggle',
1045 'section' => 'misc/diffs',
1046 'label-message' => 'tog-norollbackdiff',
1047 );
1048
1049 // Stuff from Language::getExtraUserToggles()
1050 $toggles = $wgContLang->getExtraUserToggles();
1051
1052 foreach ( $toggles as $toggle ) {
1053 $defaultPreferences[$toggle] = array(
1054 'type' => 'toggle',
1055 'section' => 'personal/i18n',
1056 'label-message' => "tog-$toggle",
1057 );
1058 }
1059 }
1060
1061 /**
1062 * @param $user User The User object
1063 * @param $context IContextSource
1064 * @return Array: text/links to display as key; $skinkey as value
1065 */
1066 static function generateSkinOptions( $user, IContextSource $context ) {
1067 global $wgDefaultSkin, $wgAllowUserCss, $wgAllowUserJs;
1068 $ret = array();
1069
1070 $mptitle = Title::newMainPage();
1071 $previewtext = $context->msg( 'skin-preview' )->text();
1072
1073 # Only show members of Skin::getSkinNames() rather than
1074 # $skinNames (skins is all skin names from Language.php)
1075 $validSkinNames = Skin::getUsableSkins();
1076
1077 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1078 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1079 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1080 $msg = $context->msg( "skinname-{$skinkey}" );
1081 if ( $msg->exists() ) {
1082 $skinname = htmlspecialchars( $msg->text() );
1083 }
1084 }
1085 asort( $validSkinNames );
1086
1087 foreach ( $validSkinNames as $skinkey => $sn ) {
1088 $linkTools = array();
1089
1090 # Mark the default skin
1091 if ( $skinkey == $wgDefaultSkin ) {
1092 $linkTools[] = $context->msg( 'default' )->escaped();
1093 }
1094
1095 # Create preview link
1096 $mplink = htmlspecialchars( $mptitle->getLocalURL( "useskin=$skinkey" ) );
1097 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1098
1099 # Create links to user CSS/JS pages
1100 if ( $wgAllowUserCss ) {
1101 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1102 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1103 }
1104
1105 if ( $wgAllowUserJs ) {
1106 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1107 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1108 }
1109
1110 $display = $sn . ' ' . $context->msg( 'parentheses', $context->getLanguage()->pipeList( $linkTools ) )->text();
1111 $ret[$display] = $skinkey;
1112 }
1113
1114 return $ret;
1115 }
1116
1117 /**
1118 * @param $context IContextSource
1119 * @return array
1120 */
1121 static function getDateOptions( IContextSource $context ) {
1122 $lang = $context->getLanguage();
1123 $dateopts = $lang->getDatePreferences();
1124
1125 $ret = array();
1126
1127 if ( $dateopts ) {
1128 if ( !in_array( 'default', $dateopts ) ) {
1129 $dateopts[] = 'default'; // Make sure default is always valid
1130 // Bug 19237
1131 }
1132
1133 // KLUGE: site default might not be valid for user language
1134 global $wgDefaultUserOptions;
1135 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1136 $wgDefaultUserOptions['date'] = 'default';
1137 }
1138
1139 $epoch = wfTimestampNow();
1140 foreach ( $dateopts as $key ) {
1141 if ( $key == 'default' ) {
1142 $formatted = $context->msg( 'datedefault' )->escaped();
1143 } else {
1144 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1145 }
1146 $ret[$formatted] = $key;
1147 }
1148 }
1149 return $ret;
1150 }
1151
1152 /**
1153 * @param $context IContextSource
1154 * @return array
1155 */
1156 static function getImageSizes( IContextSource $context ) {
1157 global $wgImageLimits;
1158
1159 $ret = array();
1160 $pixels = $context->msg( 'unit-pixel' )->text();
1161
1162 foreach ( $wgImageLimits as $index => $limits ) {
1163 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1164 $ret[$display] = $index;
1165 }
1166
1167 return $ret;
1168 }
1169
1170 /**
1171 * @param $context IContextSource
1172 * @return array
1173 */
1174 static function getThumbSizes( IContextSource $context ) {
1175 global $wgThumbLimits;
1176
1177 $ret = array();
1178 $pixels = $context->msg( 'unit-pixel' )->text();
1179
1180 foreach ( $wgThumbLimits as $index => $size ) {
1181 $display = $size . $pixels;
1182 $ret[$display] = $index;
1183 }
1184
1185 return $ret;
1186 }
1187
1188 /**
1189 * @param $signature string
1190 * @param $alldata array
1191 * @param $form HTMLForm
1192 * @return bool|string
1193 */
1194 static function validateSignature( $signature, $alldata, $form ) {
1195 global $wgParser, $wgMaxSigChars;
1196 if ( mb_strlen( $signature ) > $wgMaxSigChars ) {
1197 return Xml::element( 'span', array( 'class' => 'error' ),
1198 $form->msg( 'badsiglength' )->numParams( $wgMaxSigChars )->text() );
1199 } elseif ( isset( $alldata['fancysig'] ) &&
1200 $alldata['fancysig'] &&
1201 false === $wgParser->validateSig( $signature ) ) {
1202 return Xml::element( 'span', array( 'class' => 'error' ), $form->msg( 'badsig' )->text() );
1203 } else {
1204 return true;
1205 }
1206 }
1207
1208 /**
1209 * @param $signature string
1210 * @param $alldata array
1211 * @param $form HTMLForm
1212 * @return string
1213 */
1214 static function cleanSignature( $signature, $alldata, $form ) {
1215 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1216 global $wgParser;
1217 $signature = $wgParser->cleanSig( $signature );
1218 } else {
1219 // When no fancy sig used, make sure ~{3,5} get removed.
1220 $signature = Parser::cleanSigInSig( $signature );
1221 }
1222
1223 return $signature;
1224 }
1225
1226 /**
1227 * @param $user User
1228 * @param $context IContextSource
1229 * @param $formClass string
1230 * @param array $remove array of items to remove
1231 * @return HtmlForm
1232 */
1233 static function getFormObject( $user, IContextSource $context, $formClass = 'PreferencesForm', array $remove = array() ) {
1234 $formDescriptor = Preferences::getPreferences( $user, $context );
1235 if ( count( $remove ) ) {
1236 $removeKeys = array_flip( $remove );
1237 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1238 }
1239
1240 // Remove type=api preferences. They are not intended for rendering in the form.
1241 foreach ( $formDescriptor as $name => $info ) {
1242 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1243 unset( $formDescriptor[$name] );
1244 }
1245 }
1246
1247 /**
1248 * @var $htmlForm PreferencesForm
1249 */
1250 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1251
1252 $htmlForm->setModifiedUser( $user );
1253 $htmlForm->setId( 'mw-prefs-form' );
1254 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1255 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1256 $htmlForm->setSubmitTooltip( 'preferences-save' );
1257 $htmlForm->setSubmitID( 'prefsubmit' );
1258 $htmlForm->setSubmitCallback( array( 'Preferences', 'tryFormSubmit' ) );
1259
1260 return $htmlForm;
1261 }
1262
1263 /**
1264 * @param $context IContextSource
1265 * @return array
1266 */
1267 static function getTimezoneOptions( IContextSource $context ) {
1268 $opt = array();
1269
1270 global $wgLocalTZoffset, $wgLocaltimezone;
1271 // Check that $wgLocalTZoffset is the same as $wgLocaltimezone
1272 if ( $wgLocalTZoffset == date( 'Z' ) / 60 ) {
1273 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $wgLocaltimezone )->text();
1274 } else {
1275 $tzstring = sprintf( '%+03d:%02d', floor( $wgLocalTZoffset / 60 ), abs( $wgLocalTZoffset ) % 60 );
1276 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1277 }
1278 $opt[$server_tz_msg] = "System|$wgLocalTZoffset";
1279 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1280 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1281
1282 if ( function_exists( 'timezone_identifiers_list' ) ) {
1283 # Read timezone list
1284 $tzs = timezone_identifiers_list();
1285 sort( $tzs );
1286
1287 $tzRegions = array();
1288 $tzRegions['Africa'] = $context->msg( 'timezoneregion-africa' )->text();
1289 $tzRegions['America'] = $context->msg( 'timezoneregion-america' )->text();
1290 $tzRegions['Antarctica'] = $context->msg( 'timezoneregion-antarctica' )->text();
1291 $tzRegions['Arctic'] = $context->msg( 'timezoneregion-arctic' )->text();
1292 $tzRegions['Asia'] = $context->msg( 'timezoneregion-asia' )->text();
1293 $tzRegions['Atlantic'] = $context->msg( 'timezoneregion-atlantic' )->text();
1294 $tzRegions['Australia'] = $context->msg( 'timezoneregion-australia' )->text();
1295 $tzRegions['Europe'] = $context->msg( 'timezoneregion-europe' )->text();
1296 $tzRegions['Indian'] = $context->msg( 'timezoneregion-indian' )->text();
1297 $tzRegions['Pacific'] = $context->msg( 'timezoneregion-pacific' )->text();
1298 asort( $tzRegions );
1299
1300 $prefill = array_fill_keys( array_values( $tzRegions ), array() );
1301 $opt = array_merge( $opt, $prefill );
1302
1303 $now = date_create( 'now' );
1304
1305 foreach ( $tzs as $tz ) {
1306 $z = explode( '/', $tz, 2 );
1307
1308 # timezone_identifiers_list() returns a number of
1309 # backwards-compatibility entries. This filters them out of the
1310 # list presented to the user.
1311 if ( count( $z ) != 2 || !array_key_exists( $z[0], $tzRegions ) ) {
1312 continue;
1313 }
1314
1315 # Localize region
1316 $z[0] = $tzRegions[$z[0]];
1317
1318 $minDiff = floor( timezone_offset_get( timezone_open( $tz ), $now ) / 60 );
1319
1320 $display = str_replace( '_', ' ', $z[0] . '/' . $z[1] );
1321 $value = "ZoneInfo|$minDiff|$tz";
1322
1323 $opt[$z[0]][$display] = $value;
1324 }
1325 }
1326 return $opt;
1327 }
1328
1329 /**
1330 * @param $value
1331 * @param $alldata
1332 * @return int
1333 */
1334 static function filterIntval( $value, $alldata ) {
1335 return intval( $value );
1336 }
1337
1338 /**
1339 * @param $tz
1340 * @param $alldata
1341 * @return string
1342 */
1343 static function filterTimezoneInput( $tz, $alldata ) {
1344 $data = explode( '|', $tz, 3 );
1345 switch ( $data[0] ) {
1346 case 'ZoneInfo':
1347 case 'System':
1348 return $tz;
1349 default:
1350 $data = explode( ':', $tz, 2 );
1351 if ( count( $data ) == 2 ) {
1352 $data[0] = intval( $data[0] );
1353 $data[1] = intval( $data[1] );
1354 $minDiff = abs( $data[0] ) * 60 + $data[1];
1355 if ( $data[0] < 0 ) {
1356 $minDiff = - $minDiff;
1357 }
1358 } else {
1359 $minDiff = intval( $data[0] ) * 60;
1360 }
1361
1362 # Max is +14:00 and min is -12:00, see:
1363 # http://en.wikipedia.org/wiki/Timezone
1364 $minDiff = min( $minDiff, 840 ); # 14:00
1365 $minDiff = max( $minDiff, - 720 ); # -12:00
1366 return 'Offset|' . $minDiff;
1367 }
1368 }
1369
1370 /**
1371 * Handle the form submission if everything validated properly
1372 *
1373 * @param $formData
1374 * @param $form PreferencesForm
1375 * @param $entryPoint string
1376 * @return bool|Status|string
1377 */
1378 static function tryFormSubmit( $formData, $form, $entryPoint = 'internal' ) {
1379 global $wgHiddenPrefs, $wgAuth;
1380
1381 $user = $form->getModifiedUser();
1382 $result = true;
1383
1384 // Filter input
1385 foreach ( array_keys( $formData ) as $name ) {
1386 if ( isset( self::$saveFilters[$name] ) ) {
1387 $formData[$name] =
1388 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1389 }
1390 }
1391
1392 // Stuff that shouldn't be saved as a preference.
1393 $saveBlacklist = array(
1394 'realname',
1395 'emailaddress',
1396 );
1397
1398 // Fortunately, the realname field is MUCH simpler
1399 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
1400 $realName = $formData['realname'];
1401 $user->setRealName( $realName );
1402 }
1403
1404 foreach ( $saveBlacklist as $b ) {
1405 unset( $formData[$b] );
1406 }
1407
1408 # If users have saved a value for a preference which has subsequently been disabled
1409 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1410 # is subsequently re-enabled
1411 # TODO: maintenance script to actually delete these
1412 foreach ( $wgHiddenPrefs as $pref ) {
1413 # If the user has not set a non-default value here, the default will be returned
1414 # and subsequently discarded
1415 $formData[$pref] = $user->getOption( $pref, null, true );
1416 }
1417
1418 // Keep old preferences from interfering due to back-compat code, etc.
1419 $user->resetOptions( 'unused', $form->getContext() );
1420
1421 foreach ( $formData as $key => $value ) {
1422 $user->setOption( $key, $value );
1423 }
1424
1425 $user->saveSettings();
1426
1427 $wgAuth->updateExternalDB( $user );
1428
1429 return $result;
1430 }
1431
1432 /**
1433 * @param $formData
1434 * @param $form PreferencesForm
1435 * @return Status
1436 */
1437 public static function tryUISubmit( $formData, $form ) {
1438 $res = self::tryFormSubmit( $formData, $form, 'ui' );
1439
1440 if ( $res ) {
1441 $urlOptions = array( 'success' => 1 );
1442
1443 if ( $res === 'eauth' ) {
1444 $urlOptions['eauth'] = 1;
1445 }
1446
1447 $urlOptions += $form->getExtraSuccessRedirectParameters();
1448
1449 $url = $form->getTitle()->getFullURL( $urlOptions );
1450
1451 $form->getContext()->getOutput()->redirect( $url );
1452 }
1453
1454 return Status::newGood();
1455 }
1456
1457 /**
1458 * Try to set a user's email address.
1459 * This does *not* try to validate the address.
1460 * Caller is responsible for checking $wgAuth.
1461 *
1462 * @deprecated in 1.20; use User::setEmailWithConfirmation() instead.
1463 * @param $user User
1464 * @param string $newaddr New email address
1465 * @return Array (true on success or Status on failure, info string)
1466 */
1467 public static function trySetUserEmail( User $user, $newaddr ) {
1468 wfDeprecated( __METHOD__, '1.20' );
1469
1470 $result = $user->setEmailWithConfirmation( $newaddr );
1471 if ( $result->isGood() ) {
1472 return array( true, $result->value );
1473 } else {
1474 return array( $result, 'mailerror' );
1475 }
1476 }
1477
1478 /**
1479 * @deprecated in 1.19; will be removed in 1.20.
1480 * @param $user User
1481 * @return array
1482 */
1483 public static function loadOldSearchNs( $user ) {
1484 wfDeprecated( __METHOD__, '1.19' );
1485
1486 $searchableNamespaces = SearchEngine::searchableNamespaces();
1487 // Back compat with old format
1488 $arr = array();
1489
1490 foreach ( $searchableNamespaces as $ns => $name ) {
1491 if ( $user->getOption( 'searchNs' . $ns ) ) {
1492 $arr[] = $ns;
1493 }
1494 }
1495
1496 return $arr;
1497 }
1498 }
1499
1500 /** Some tweaks to allow js prefs to work */
1501 class PreferencesForm extends HTMLForm {
1502 // Override default value from HTMLForm
1503 protected $mSubSectionBeforeFields = false;
1504
1505 private $modifiedUser;
1506
1507 /**
1508 * @param $user User
1509 */
1510 public function setModifiedUser( $user ) {
1511 $this->modifiedUser = $user;
1512 }
1513
1514 /**
1515 * @return User
1516 */
1517 public function getModifiedUser() {
1518 if ( $this->modifiedUser === null ) {
1519 return $this->getUser();
1520 } else {
1521 return $this->modifiedUser;
1522 }
1523 }
1524
1525 /**
1526 * Get extra parameters for the query string when redirecting after
1527 * successful save.
1528 *
1529 * @return array()
1530 */
1531 public function getExtraSuccessRedirectParameters() {
1532 return array();
1533 }
1534
1535 /**
1536 * @param $html string
1537 * @return String
1538 */
1539 function wrapForm( $html ) {
1540 $html = Xml::tags( 'div', array( 'id' => 'preferences' ), $html );
1541
1542 return parent::wrapForm( $html );
1543 }
1544
1545 /**
1546 * @return String
1547 */
1548 function getButtons() {
1549 $html = parent::getButtons();
1550
1551 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1552
1553 $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped() );
1554
1555 $html = Xml::tags( 'div', array( 'class' => 'mw-prefs-buttons' ), $html );
1556
1557 return $html;
1558 }
1559
1560 /**
1561 * @param $data array
1562 * @return array
1563 */
1564 function filterDataForSubmit( $data ) {
1565 // Support for separating multi-option preferences into multiple preferences
1566 // Due to lack of array support.
1567 foreach ( $this->mFlatFields as $fieldname => $field ) {
1568 $info = $field->mParams;
1569
1570 if ( $field instanceof HTMLMultiSelectField ) {
1571 $options = HTMLFormField::flattenOptions( $info['options'] );
1572 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1573
1574 foreach ( $options as $opt ) {
1575 $data["$prefix$opt"] = in_array( $opt, $data[$fieldname] );
1576 }
1577
1578 unset( $data[$fieldname] );
1579
1580 } elseif ( $field instanceof HTMLCheckMatrix ) {
1581 $columns = HTMLFormField::flattenOptions( $info['columns'] );
1582 $rows = HTMLFormField::flattenOptions( $info['rows'] );
1583 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1584 foreach ( $columns as $column ) {
1585 foreach ( $rows as $row ) {
1586 // Make sure option hasn't been removed
1587 if ( !isset( $info['remove-options'] )
1588 || !in_array( "$column-$row", $info['remove-options'] ) )
1589 {
1590 $data["$prefix-$column-$row"] = in_array( "$column-$row", $data[$fieldname] );
1591 }
1592 }
1593 }
1594
1595 unset( $data[$fieldname] );
1596 }
1597 }
1598
1599 return $data;
1600 }
1601
1602 /**
1603 * Get the whole body of the form.
1604 * @return string
1605 */
1606 function getBody() {
1607 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1608 }
1609
1610 /**
1611 * Get the "<legend>" for a given section key. Normally this is the
1612 * prefs-$key message but we'll allow extensions to override it.
1613 * @param $key string
1614 * @return string
1615 */
1616 function getLegend( $key ) {
1617 $legend = parent::getLegend( $key );
1618 wfRunHooks( 'PreferencesGetLegend', array( $this, $key, &$legend ) );
1619 return $legend;
1620 }
1621 }