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