Merge "Add scripts to generate update builds of OOjs and OOjs UI"
[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;
1034
1035 $defaultPreferences['searcheverything'] = array(
1036 'type' => 'toggle',
1037 'label-message' => 'searcheverything-enable',
1038 'section' => 'searchoptions/advancedsearchoptions',
1039 );
1040
1041 $nsOptions = $wgContLang->getFormattedNamespaces();
1042 $nsOptions[0] = $context->msg( 'blanknamespace' )->text();
1043 foreach ( $nsOptions as $ns => $name ) {
1044 if ( $ns < 0 ) {
1045 unset( $nsOptions[$ns] );
1046 }
1047 }
1048
1049 $defaultPreferences['searchnamespaces'] = array(
1050 'type' => 'multiselect',
1051 'label-message' => 'defaultns',
1052 'options' => array_flip( $nsOptions ),
1053 'section' => 'searchoptions/advancedsearchoptions',
1054 'prefix' => 'searchNs',
1055 );
1056 }
1057
1058 /**
1059 * Dummy, kept for backwards-compatibility.
1060 */
1061 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1062 }
1063
1064 /**
1065 * @param $user User The User object
1066 * @param $context IContextSource
1067 * @return Array: text/links to display as key; $skinkey as value
1068 */
1069 static function generateSkinOptions( $user, IContextSource $context ) {
1070 global $wgDefaultSkin, $wgAllowUserCss, $wgAllowUserJs;
1071 $ret = array();
1072
1073 $mptitle = Title::newMainPage();
1074 $previewtext = $context->msg( 'skin-preview' )->text();
1075
1076 # Only show members of Skin::getSkinNames() rather than
1077 # $skinNames (skins is all skin names from Language.php)
1078 $validSkinNames = Skin::getUsableSkins();
1079
1080 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1081 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1082 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1083 $msg = $context->msg( "skinname-{$skinkey}" );
1084 if ( $msg->exists() ) {
1085 $skinname = htmlspecialchars( $msg->text() );
1086 }
1087 }
1088 asort( $validSkinNames );
1089
1090 foreach ( $validSkinNames as $skinkey => $sn ) {
1091 $linkTools = array();
1092
1093 # Mark the default skin
1094 if ( $skinkey == $wgDefaultSkin ) {
1095 $linkTools[] = $context->msg( 'default' )->escaped();
1096 }
1097
1098 # Create preview link
1099 $mplink = htmlspecialchars( $mptitle->getLocalURL( array( 'useskin' => $skinkey ) ) );
1100 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1101
1102 # Create links to user CSS/JS pages
1103 if ( $wgAllowUserCss ) {
1104 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1105 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1106 }
1107
1108 if ( $wgAllowUserJs ) {
1109 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1110 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1111 }
1112
1113 $display = $sn . ' ' . $context->msg(
1114 'parentheses',
1115 $context->getLanguage()->pipeList( $linkTools )
1116 )->text();
1117 $ret[$display] = $skinkey;
1118 }
1119
1120 return $ret;
1121 }
1122
1123 /**
1124 * @param $context IContextSource
1125 * @return array
1126 */
1127 static function getDateOptions( IContextSource $context ) {
1128 $lang = $context->getLanguage();
1129 $dateopts = $lang->getDatePreferences();
1130
1131 $ret = array();
1132
1133 if ( $dateopts ) {
1134 if ( !in_array( 'default', $dateopts ) ) {
1135 $dateopts[] = 'default'; // Make sure default is always valid
1136 // Bug 19237
1137 }
1138
1139 // KLUGE: site default might not be valid for user language
1140 global $wgDefaultUserOptions;
1141 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1142 $wgDefaultUserOptions['date'] = 'default';
1143 }
1144
1145 $epoch = wfTimestampNow();
1146 foreach ( $dateopts as $key ) {
1147 if ( $key == 'default' ) {
1148 $formatted = $context->msg( 'datedefault' )->escaped();
1149 } else {
1150 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1151 }
1152 $ret[$formatted] = $key;
1153 }
1154 }
1155 return $ret;
1156 }
1157
1158 /**
1159 * @param $context IContextSource
1160 * @return array
1161 */
1162 static function getImageSizes( IContextSource $context ) {
1163 global $wgImageLimits;
1164
1165 $ret = array();
1166 $pixels = $context->msg( 'unit-pixel' )->text();
1167
1168 foreach ( $wgImageLimits as $index => $limits ) {
1169 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1170 $ret[$display] = $index;
1171 }
1172
1173 return $ret;
1174 }
1175
1176 /**
1177 * @param $context IContextSource
1178 * @return array
1179 */
1180 static function getThumbSizes( IContextSource $context ) {
1181 global $wgThumbLimits;
1182
1183 $ret = array();
1184 $pixels = $context->msg( 'unit-pixel' )->text();
1185
1186 foreach ( $wgThumbLimits as $index => $size ) {
1187 $display = $size . $pixels;
1188 $ret[$display] = $index;
1189 }
1190
1191 return $ret;
1192 }
1193
1194 /**
1195 * @param $signature string
1196 * @param $alldata array
1197 * @param $form HTMLForm
1198 * @return bool|string
1199 */
1200 static function validateSignature( $signature, $alldata, $form ) {
1201 global $wgParser, $wgMaxSigChars;
1202 if ( mb_strlen( $signature ) > $wgMaxSigChars ) {
1203 return Xml::element( 'span', array( 'class' => 'error' ),
1204 $form->msg( 'badsiglength' )->numParams( $wgMaxSigChars )->text() );
1205 } elseif ( isset( $alldata['fancysig'] ) &&
1206 $alldata['fancysig'] &&
1207 $wgParser->validateSig( $signature ) === false
1208 ) {
1209 return Xml::element(
1210 'span',
1211 array( 'class' => 'error' ),
1212 $form->msg( 'badsig' )->text()
1213 );
1214 } else {
1215 return true;
1216 }
1217 }
1218
1219 /**
1220 * @param $signature string
1221 * @param $alldata array
1222 * @param $form HTMLForm
1223 * @return string
1224 */
1225 static function cleanSignature( $signature, $alldata, $form ) {
1226 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1227 global $wgParser;
1228 $signature = $wgParser->cleanSig( $signature );
1229 } else {
1230 // When no fancy sig used, make sure ~{3,5} get removed.
1231 $signature = Parser::cleanSigInSig( $signature );
1232 }
1233
1234 return $signature;
1235 }
1236
1237 /**
1238 * @param $user User
1239 * @param $context IContextSource
1240 * @param $formClass string
1241 * @param array $remove array of items to remove
1242 * @return HtmlForm
1243 */
1244 static function getFormObject(
1245 $user,
1246 IContextSource $context,
1247 $formClass = 'PreferencesForm',
1248 array $remove = array()
1249 ) {
1250 $formDescriptor = Preferences::getPreferences( $user, $context );
1251 if ( count( $remove ) ) {
1252 $removeKeys = array_flip( $remove );
1253 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1254 }
1255
1256 // Remove type=api preferences. They are not intended for rendering in the form.
1257 foreach ( $formDescriptor as $name => $info ) {
1258 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1259 unset( $formDescriptor[$name] );
1260 }
1261 }
1262
1263 /**
1264 * @var $htmlForm PreferencesForm
1265 */
1266 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1267
1268 $htmlForm->setModifiedUser( $user );
1269 $htmlForm->setId( 'mw-prefs-form' );
1270 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1271 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1272 $htmlForm->setSubmitTooltip( 'preferences-save' );
1273 $htmlForm->setSubmitID( 'prefsubmit' );
1274 $htmlForm->setSubmitCallback( array( 'Preferences', 'tryFormSubmit' ) );
1275
1276 return $htmlForm;
1277 }
1278
1279 /**
1280 * @param $context IContextSource
1281 * @return array
1282 */
1283 static function getTimezoneOptions( IContextSource $context ) {
1284 $opt = array();
1285
1286 global $wgLocalTZoffset;
1287 $timestamp = MWTimestamp::getLocalInstance();
1288 // Check that $wgLocalTZoffset is the same as the local time zone offset
1289 if ( $wgLocalTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1290 $server_tz_msg = $context->msg(
1291 'timezoneuseserverdefault',
1292 $timestamp->getTimezone()->getName()
1293 )->text();
1294 } else {
1295 $tzstring = sprintf(
1296 '%+03d:%02d',
1297 floor( $wgLocalTZoffset / 60 ),
1298 abs( $wgLocalTZoffset ) % 60
1299 );
1300 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1301 }
1302 $opt[$server_tz_msg] = "System|$wgLocalTZoffset";
1303 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1304 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1305
1306 if ( function_exists( 'timezone_identifiers_list' ) ) {
1307 # Read timezone list
1308 $tzs = timezone_identifiers_list();
1309 sort( $tzs );
1310
1311 $tzRegions = array();
1312 $tzRegions['Africa'] = $context->msg( 'timezoneregion-africa' )->text();
1313 $tzRegions['America'] = $context->msg( 'timezoneregion-america' )->text();
1314 $tzRegions['Antarctica'] = $context->msg( 'timezoneregion-antarctica' )->text();
1315 $tzRegions['Arctic'] = $context->msg( 'timezoneregion-arctic' )->text();
1316 $tzRegions['Asia'] = $context->msg( 'timezoneregion-asia' )->text();
1317 $tzRegions['Atlantic'] = $context->msg( 'timezoneregion-atlantic' )->text();
1318 $tzRegions['Australia'] = $context->msg( 'timezoneregion-australia' )->text();
1319 $tzRegions['Europe'] = $context->msg( 'timezoneregion-europe' )->text();
1320 $tzRegions['Indian'] = $context->msg( 'timezoneregion-indian' )->text();
1321 $tzRegions['Pacific'] = $context->msg( 'timezoneregion-pacific' )->text();
1322 asort( $tzRegions );
1323
1324 $prefill = array_fill_keys( array_values( $tzRegions ), array() );
1325 $opt = array_merge( $opt, $prefill );
1326
1327 $now = date_create( 'now' );
1328
1329 foreach ( $tzs as $tz ) {
1330 $z = explode( '/', $tz, 2 );
1331
1332 # timezone_identifiers_list() returns a number of
1333 # backwards-compatibility entries. This filters them out of the
1334 # list presented to the user.
1335 if ( count( $z ) != 2 || !array_key_exists( $z[0], $tzRegions ) ) {
1336 continue;
1337 }
1338
1339 # Localize region
1340 $z[0] = $tzRegions[$z[0]];
1341
1342 $minDiff = floor( timezone_offset_get( timezone_open( $tz ), $now ) / 60 );
1343
1344 $display = str_replace( '_', ' ', $z[0] . '/' . $z[1] );
1345 $value = "ZoneInfo|$minDiff|$tz";
1346
1347 $opt[$z[0]][$display] = $value;
1348 }
1349 }
1350 return $opt;
1351 }
1352
1353 /**
1354 * @param $value
1355 * @param $alldata
1356 * @return int
1357 */
1358 static function filterIntval( $value, $alldata ) {
1359 return intval( $value );
1360 }
1361
1362 /**
1363 * @param $tz
1364 * @param $alldata
1365 * @return string
1366 */
1367 static function filterTimezoneInput( $tz, $alldata ) {
1368 $data = explode( '|', $tz, 3 );
1369 switch ( $data[0] ) {
1370 case 'ZoneInfo':
1371 case 'System':
1372 return $tz;
1373 default:
1374 $data = explode( ':', $tz, 2 );
1375 if ( count( $data ) == 2 ) {
1376 $data[0] = intval( $data[0] );
1377 $data[1] = intval( $data[1] );
1378 $minDiff = abs( $data[0] ) * 60 + $data[1];
1379 if ( $data[0] < 0 ) {
1380 $minDiff = - $minDiff;
1381 }
1382 } else {
1383 $minDiff = intval( $data[0] ) * 60;
1384 }
1385
1386 # Max is +14:00 and min is -12:00, see:
1387 # http://en.wikipedia.org/wiki/Timezone
1388 $minDiff = min( $minDiff, 840 ); # 14:00
1389 $minDiff = max( $minDiff, - 720 ); # -12:00
1390 return 'Offset|' . $minDiff;
1391 }
1392 }
1393
1394 /**
1395 * Handle the form submission if everything validated properly
1396 *
1397 * @param $formData
1398 * @param $form PreferencesForm
1399 * @return bool|Status|string
1400 */
1401 static function tryFormSubmit( $formData, $form ) {
1402 global $wgHiddenPrefs, $wgAuth;
1403
1404 $user = $form->getModifiedUser();
1405 $result = true;
1406
1407 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1408 return Status::newFatal( 'mypreferencesprotected' );
1409 }
1410
1411 // Filter input
1412 foreach ( array_keys( $formData ) as $name ) {
1413 if ( isset( self::$saveFilters[$name] ) ) {
1414 $formData[$name] =
1415 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1416 }
1417 }
1418
1419 // Fortunately, the realname field is MUCH simpler
1420 // (not really "private", but still shouldn't be edited without permission)
1421 if ( !in_array( 'realname', $wgHiddenPrefs ) && $user->isAllowed( 'editmyprivateinfo' ) ) {
1422 $realName = $formData['realname'];
1423 $user->setRealName( $realName );
1424 }
1425
1426 if ( $user->isAllowed( 'editmyoptions' ) ) {
1427 foreach ( self::$saveBlacklist as $b ) {
1428 unset( $formData[$b] );
1429 }
1430
1431 # If users have saved a value for a preference which has subsequently been disabled
1432 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1433 # is subsequently re-enabled
1434 foreach ( $wgHiddenPrefs as $pref ) {
1435 # If the user has not set a non-default value here, the default will be returned
1436 # and subsequently discarded
1437 $formData[$pref] = $user->getOption( $pref, null, true );
1438 }
1439
1440 // Keep old preferences from interfering due to back-compat code, etc.
1441 $user->resetOptions( 'unused', $form->getContext() );
1442
1443 foreach ( $formData as $key => $value ) {
1444 $user->setOption( $key, $value );
1445 }
1446
1447 wfRunHooks( 'PreferencesFormPreSave', array( $formData, $form, $user, &$result ) );
1448 $user->saveSettings();
1449 }
1450
1451 $wgAuth->updateExternalDB( $user );
1452
1453 return $result;
1454 }
1455
1456 /**
1457 * @param $formData
1458 * @param $form PreferencesForm
1459 * @return Status
1460 */
1461 public static function tryUISubmit( $formData, $form ) {
1462 $res = self::tryFormSubmit( $formData, $form );
1463
1464 if ( $res ) {
1465 $urlOptions = array( 'success' => 1 );
1466
1467 if ( $res === 'eauth' ) {
1468 $urlOptions['eauth'] = 1;
1469 }
1470
1471 $urlOptions += $form->getExtraSuccessRedirectParameters();
1472
1473 $url = $form->getTitle()->getFullURL( $urlOptions );
1474
1475 $form->getContext()->getOutput()->redirect( $url );
1476 }
1477
1478 return Status::newGood();
1479 }
1480
1481 /**
1482 * Try to set a user's email address.
1483 * This does *not* try to validate the address.
1484 * Caller is responsible for checking $wgAuth and 'editmyprivateinfo'
1485 * right.
1486 *
1487 * @deprecated in 1.20; use User::setEmailWithConfirmation() instead.
1488 * @param $user User
1489 * @param string $newaddr New email address
1490 * @return Array (true on success or Status on failure, info string)
1491 */
1492 public static function trySetUserEmail( User $user, $newaddr ) {
1493 wfDeprecated( __METHOD__, '1.20' );
1494
1495 $result = $user->setEmailWithConfirmation( $newaddr );
1496 if ( $result->isGood() ) {
1497 return array( true, $result->value );
1498 } else {
1499 return array( $result, 'mailerror' );
1500 }
1501 }
1502
1503 /**
1504 * @deprecated in 1.19
1505 * @param $user User
1506 * @return array
1507 */
1508 public static function loadOldSearchNs( $user ) {
1509 wfDeprecated( __METHOD__, '1.19' );
1510
1511 $searchableNamespaces = SearchEngine::searchableNamespaces();
1512 // Back compat with old format
1513 $arr = array();
1514
1515 foreach ( $searchableNamespaces as $ns => $name ) {
1516 if ( $user->getOption( 'searchNs' . $ns ) ) {
1517 $arr[] = $ns;
1518 }
1519 }
1520
1521 return $arr;
1522 }
1523 }
1524
1525 /** Some tweaks to allow js prefs to work */
1526 class PreferencesForm extends HTMLForm {
1527 // Override default value from HTMLForm
1528 protected $mSubSectionBeforeFields = false;
1529
1530 private $modifiedUser;
1531
1532 /**
1533 * @param $user User
1534 */
1535 public function setModifiedUser( $user ) {
1536 $this->modifiedUser = $user;
1537 }
1538
1539 /**
1540 * @return User
1541 */
1542 public function getModifiedUser() {
1543 if ( $this->modifiedUser === null ) {
1544 return $this->getUser();
1545 } else {
1546 return $this->modifiedUser;
1547 }
1548 }
1549
1550 /**
1551 * Get extra parameters for the query string when redirecting after
1552 * successful save.
1553 *
1554 * @return array()
1555 */
1556 public function getExtraSuccessRedirectParameters() {
1557 return array();
1558 }
1559
1560 /**
1561 * @param $html string
1562 * @return String
1563 */
1564 function wrapForm( $html ) {
1565 $html = Xml::tags( 'div', array( 'id' => 'preferences' ), $html );
1566
1567 return parent::wrapForm( $html );
1568 }
1569
1570 /**
1571 * @return String
1572 */
1573 function getButtons() {
1574 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1575 return '';
1576 }
1577
1578 $html = parent::getButtons();
1579
1580 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1581 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1582
1583 $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped() );
1584
1585 $html = Xml::tags( 'div', array( 'class' => 'mw-prefs-buttons' ), $html );
1586 }
1587
1588 return $html;
1589 }
1590
1591 /**
1592 * Separate multi-option preferences into multiple preferences, since we
1593 * have to store them separately
1594 * @param $data array
1595 * @return array
1596 */
1597 function filterDataForSubmit( $data ) {
1598 foreach ( $this->mFlatFields as $fieldname => $field ) {
1599 if ( $field instanceof HTMLNestedFilterable ) {
1600 $info = $field->mParams;
1601 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1602 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1603 $data["$prefix$key"] = $value;
1604 }
1605 unset( $data[$fieldname] );
1606 }
1607 }
1608
1609 return $data;
1610 }
1611
1612 /**
1613 * Get the whole body of the form.
1614 * @return string
1615 */
1616 function getBody() {
1617 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1618 }
1619
1620 /**
1621 * Get the "<legend>" for a given section key. Normally this is the
1622 * prefs-$key message but we'll allow extensions to override it.
1623 * @param $key string
1624 * @return string
1625 */
1626 function getLegend( $key ) {
1627 $legend = parent::getLegend( $key );
1628 wfRunHooks( 'PreferencesGetLegend', array( $this, $key, &$legend ) );
1629 return $legend;
1630 }
1631 }