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