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