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