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