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