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