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