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