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