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