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