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