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