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