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