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