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