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