MediaWiki  1.23.0
Preferences.php
Go to the documentation of this file.
1 <?php
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 
68  static function getSaveBlacklist() {
69  return self::$saveBlacklist;
70  }
71 
78  static function getPreferences( $user, IContextSource $context ) {
79  if ( self::$defaultPreferences ) {
81  }
82 
84 
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;
120  $globalDefault = isset( $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 
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 
195  global $wgAuth, $wgContLang, $wgParser, $wgCookieExpiration, $wgLanguageCode,
196  $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  // Only show prefershttps if secure login is turned on
305  if ( $wgSecureLogin && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
306  $defaultPreferences['prefershttps'] = array(
307  'type' => 'toggle',
308  'label-message' => 'tog-prefershttps',
309  'help-message' => 'prefs-help-prefershttps',
310  'section' => 'personal/info'
311  );
312  }
313 
314  // Language
316  if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
317  $languages[$wgLanguageCode] = $wgLanguageCode;
318  }
319  ksort( $languages );
320 
321  $options = array();
322  foreach ( $languages as $code => $name ) {
323  $display = wfBCP47( $code ) . ' - ' . $name;
324  $options[$display] = $code;
325  }
326  $defaultPreferences['language'] = array(
327  'type' => 'select',
328  'section' => 'personal/i18n',
329  'options' => $options,
330  'label-message' => 'yourlanguage',
331  );
332 
333  $defaultPreferences['gender'] = array(
334  'type' => 'radio',
335  'section' => 'personal/i18n',
336  'options' => array(
337  $context->msg( 'parentheses',
338  $context->msg( 'gender-unknown' )->text()
339  )->text() => 'unknown',
340  $context->msg( 'gender-female' )->text() => 'female',
341  $context->msg( 'gender-male' )->text() => 'male',
342  ),
343  'label-message' => 'yourgender',
344  'help-message' => 'prefs-help-gender',
345  );
346 
347  // see if there are multiple language variants to choose from
348  if ( !$wgDisableLangConversion ) {
349  foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
350  if ( $langCode == $wgContLang->getCode() ) {
351  $variants = $wgContLang->getVariants();
352 
353  if ( count( $variants ) <= 1 ) {
354  continue;
355  }
356 
357  $variantArray = array();
358  foreach ( $variants as $v ) {
359  $v = str_replace( '_', '-', strtolower( $v ) );
360  $variantArray[$v] = $lang->getVariantname( $v, false );
361  }
362 
363  $options = array();
364  foreach ( $variantArray as $code => $name ) {
365  $display = wfBCP47( $code ) . ' - ' . $name;
366  $options[$display] = $code;
367  }
368 
369  $defaultPreferences['variant'] = array(
370  'label-message' => 'yourvariant',
371  'type' => 'select',
372  'options' => $options,
373  'section' => 'personal/i18n',
374  'help-message' => 'prefs-help-variant',
375  );
376  } else {
377  $defaultPreferences["variant-$langCode"] = array(
378  'type' => 'api',
379  );
380  }
381  }
382  }
383 
384  // Stuff from Language::getExtraUserToggles()
385  // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
386  $toggles = $wgContLang->getExtraUserToggles();
387 
388  foreach ( $toggles as $toggle ) {
389  $defaultPreferences[$toggle] = array(
390  'type' => 'toggle',
391  'section' => 'personal/i18n',
392  'label-message' => "tog-$toggle",
393  );
394  }
395 
396  // show a preview of the old signature first
397  $oldsigWikiText = $wgParser->preSaveTransform(
398  '~~~',
399  $context->getTitle(),
400  $user,
402  );
403  $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
404  $defaultPreferences['oldsig'] = array(
405  'type' => 'info',
406  'raw' => true,
407  'label-message' => 'tog-oldsig',
408  'default' => $oldsigHTML,
409  'section' => 'personal/signature',
410  );
411  $defaultPreferences['nickname'] = array(
412  'type' => $wgAuth->allowPropChange( 'nickname' ) ? 'text' : 'info',
413  'maxlength' => $wgMaxSigChars,
414  'label-message' => 'yournick',
415  'validation-callback' => array( 'Preferences', 'validateSignature' ),
416  'section' => 'personal/signature',
417  'filter-callback' => array( 'Preferences', 'cleanSignature' ),
418  );
419  $defaultPreferences['fancysig'] = array(
420  'type' => 'toggle',
421  'label-message' => 'tog-fancysig',
422  // show general help about signature at the bottom of the section
423  'help-message' => 'prefs-help-signature',
424  'section' => 'personal/signature'
425  );
426 
427  ## Email stuff
428 
429  if ( $wgEnableEmail ) {
430  if ( $canViewPrivateInfo ) {
431  $helpMessages[] = $wgEmailConfirmToEdit
432  ? 'prefs-help-email-required'
433  : 'prefs-help-email';
434 
435  if ( $wgEnableUserEmail ) {
436  // additional messages when users can send email to each other
437  $helpMessages[] = 'prefs-help-email-others';
438  }
439 
440  $emailAddress = $user->getEmail() ? htmlspecialchars( $user->getEmail() ) : '';
441  if ( $canEditPrivateInfo && $wgAuth->allowPropChange( 'emailaddress' ) ) {
443  SpecialPage::getTitleFor( 'ChangeEmail' ),
444  $context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->escaped(),
445  array(),
446  array( 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ) );
447 
448  $emailAddress .= $emailAddress == '' ? $link : (
449  $context->msg( 'word-separator' )->plain()
450  . $context->msg( 'parentheses' )->rawParams( $link )->plain()
451  );
452  }
453 
454  $defaultPreferences['emailaddress'] = array(
455  'type' => 'info',
456  'raw' => true,
457  'default' => $emailAddress,
458  'label-message' => 'youremail',
459  'section' => 'personal/email',
460  'help-messages' => $helpMessages,
461  # 'cssclass' chosen below
462  );
463  }
464 
465  $disableEmailPrefs = false;
466 
467  if ( $wgEmailAuthentication ) {
468  $emailauthenticationclass = 'mw-email-not-authenticated';
469  if ( $user->getEmail() ) {
470  if ( $user->getEmailAuthenticationTimestamp() ) {
471  // date and time are separate parameters to facilitate localisation.
472  // $time is kept for backward compat reasons.
473  // 'emailauthenticated' is also used in SpecialConfirmemail.php
474  $displayUser = $context->getUser();
475  $emailTimestamp = $user->getEmailAuthenticationTimestamp();
476  $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
477  $d = $lang->userDate( $emailTimestamp, $displayUser );
478  $t = $lang->userTime( $emailTimestamp, $displayUser );
479  $emailauthenticated = $context->msg( 'emailauthenticated',
480  $time, $d, $t )->parse() . '<br />';
481  $disableEmailPrefs = false;
482  $emailauthenticationclass = 'mw-email-authenticated';
483  } else {
484  $disableEmailPrefs = true;
485  $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
487  SpecialPage::getTitleFor( 'Confirmemail' ),
488  $context->msg( 'emailconfirmlink' )->escaped()
489  ) . '<br />';
490  $emailauthenticationclass = "mw-email-not-authenticated";
491  }
492  } else {
493  $disableEmailPrefs = true;
494  $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
495  $emailauthenticationclass = 'mw-email-none';
496  }
497 
498  if ( $canViewPrivateInfo ) {
499  $defaultPreferences['emailauthentication'] = array(
500  'type' => 'info',
501  'raw' => true,
502  'section' => 'personal/email',
503  'label-message' => 'prefs-emailconfirm-label',
504  'default' => $emailauthenticated,
505  # Apply the same CSS class used on the input to the message:
506  'cssclass' => $emailauthenticationclass,
507  );
508  $defaultPreferences['emailaddress']['cssclass'] = $emailauthenticationclass;
509  }
510  }
511 
512  if ( $wgEnableUserEmail && $user->isAllowed( 'sendemail' ) ) {
513  $defaultPreferences['disablemail'] = array(
514  'type' => 'toggle',
515  'invert' => true,
516  'section' => 'personal/email',
517  'label-message' => 'allowemail',
518  'disabled' => $disableEmailPrefs,
519  );
520  $defaultPreferences['ccmeonemails'] = array(
521  'type' => 'toggle',
522  'section' => 'personal/email',
523  'label-message' => 'tog-ccmeonemails',
524  'disabled' => $disableEmailPrefs,
525  );
526  }
527 
528  if ( $wgEnotifWatchlist ) {
529  $defaultPreferences['enotifwatchlistpages'] = array(
530  'type' => 'toggle',
531  'section' => 'personal/email',
532  'label-message' => 'tog-enotifwatchlistpages',
533  'disabled' => $disableEmailPrefs,
534  );
535  }
536  if ( $wgEnotifUserTalk ) {
537  $defaultPreferences['enotifusertalkpages'] = array(
538  'type' => 'toggle',
539  'section' => 'personal/email',
540  'label-message' => 'tog-enotifusertalkpages',
541  'disabled' => $disableEmailPrefs,
542  );
543  }
544  if ( $wgEnotifUserTalk || $wgEnotifWatchlist ) {
545  $defaultPreferences['enotifminoredits'] = array(
546  'type' => 'toggle',
547  'section' => 'personal/email',
548  'label-message' => 'tog-enotifminoredits',
549  'disabled' => $disableEmailPrefs,
550  );
551 
552  if ( $wgEnotifRevealEditorAddress ) {
553  $defaultPreferences['enotifrevealaddr'] = array(
554  'type' => 'toggle',
555  'section' => 'personal/email',
556  'label-message' => 'tog-enotifrevealaddr',
557  'disabled' => $disableEmailPrefs,
558  );
559  }
560  }
561  }
562  }
563 
570  static function skinPreferences( $user, IContextSource $context, &$defaultPreferences ) {
571  ## Skin #####################################
572  global $wgAllowUserCss, $wgAllowUserJs;
573 
574  $defaultPreferences['skin'] = array(
575  'type' => 'radio',
576  'options' => self::generateSkinOptions( $user, $context ),
577  'label' => '&#160;',
578  'section' => 'rendering/skin',
579  );
580 
581  # Create links to user CSS/JS pages for all skins
582  # This code is basically copied from generateSkinOptions(). It'd
583  # be nice to somehow merge this back in there to avoid redundancy.
584  if ( $wgAllowUserCss || $wgAllowUserJs ) {
585  $linkTools = array();
586  $userName = $user->getName();
587 
588  if ( $wgAllowUserCss ) {
589  $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
590  $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
591  }
592 
593  if ( $wgAllowUserJs ) {
594  $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
595  $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
596  }
597 
598  $defaultPreferences['commoncssjs'] = array(
599  'type' => 'info',
600  'raw' => true,
601  'default' => $context->getLanguage()->pipeList( $linkTools ),
602  'label-message' => 'prefs-common-css-js',
603  'section' => 'rendering/skin',
604  );
605  }
606  }
607 
613  static function filesPreferences( $user, IContextSource $context, &$defaultPreferences ) {
614  ## Files #####################################
615  $defaultPreferences['imagesize'] = array(
616  'type' => 'select',
617  'options' => self::getImageSizes( $context ),
618  'label-message' => 'imagemaxsize',
619  'section' => 'rendering/files',
620  );
621  $defaultPreferences['thumbsize'] = array(
622  'type' => 'select',
623  'options' => self::getThumbSizes( $context ),
624  'label-message' => 'thumbsize',
625  'section' => 'rendering/files',
626  );
627  }
628 
636  ## Date and time #####################################
637  $dateOptions = self::getDateOptions( $context );
638  if ( $dateOptions ) {
639  $defaultPreferences['date'] = array(
640  'type' => 'radio',
641  'options' => $dateOptions,
642  'label' => '&#160;',
643  'section' => 'rendering/dateformat',
644  );
645  }
646 
647  // Info
648  $now = wfTimestampNow();
649  $lang = $context->getLanguage();
650  $nowlocal = Xml::element( 'span', array( 'id' => 'wpLocalTime' ),
651  $lang->time( $now, true ) );
652  $nowserver = $lang->time( $now, false ) .
653  Html::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 + (int)substr( $now, 10, 2 ) );
654 
655  $defaultPreferences['nowserver'] = array(
656  'type' => 'info',
657  'raw' => 1,
658  'label-message' => 'servertime',
659  'default' => $nowserver,
660  'section' => 'rendering/timeoffset',
661  );
662 
663  $defaultPreferences['nowlocal'] = array(
664  'type' => 'info',
665  'raw' => 1,
666  'label-message' => 'localtime',
667  'default' => $nowlocal,
668  'section' => 'rendering/timeoffset',
669  );
670 
671  // Grab existing pref.
672  $tzOffset = $user->getOption( 'timecorrection' );
673  $tz = explode( '|', $tzOffset, 3 );
674 
675  $tzOptions = self::getTimezoneOptions( $context );
676 
677  $tzSetting = $tzOffset;
678  if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
679  $minDiff = $tz[1];
680  $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) % 60 );
681  } elseif ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
682  !in_array( $tzOffset, HTMLFormField::flattenOptions( $tzOptions ) )
683  ) {
684  # Timezone offset can vary with DST
685  $userTZ = timezone_open( $tz[2] );
686  if ( $userTZ !== false ) {
687  $minDiff = floor( timezone_offset_get( $userTZ, date_create( 'now' ) ) / 60 );
688  $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
689  }
690  }
691 
692  $defaultPreferences['timecorrection'] = array(
693  'class' => 'HTMLSelectOrOtherField',
694  'label-message' => 'timezonelegend',
695  'options' => $tzOptions,
696  'default' => $tzSetting,
697  'size' => 20,
698  'section' => 'rendering/timeoffset',
699  );
700  }
701 
708  ## Diffs ####################################
709  $defaultPreferences['diffonly'] = array(
710  'type' => 'toggle',
711  'section' => 'rendering/diffs',
712  'label-message' => 'tog-diffonly',
713  );
714  $defaultPreferences['norollbackdiff'] = array(
715  'type' => 'toggle',
716  'section' => 'rendering/diffs',
717  'label-message' => 'tog-norollbackdiff',
718  );
719 
720  ## Page Rendering ##############################
721  global $wgAllowUserCssPrefs;
722  if ( $wgAllowUserCssPrefs ) {
723  $defaultPreferences['underline'] = array(
724  'type' => 'select',
725  'options' => array(
726  $context->msg( 'underline-never' )->text() => 0,
727  $context->msg( 'underline-always' )->text() => 1,
728  $context->msg( 'underline-default' )->text() => 2,
729  ),
730  'label-message' => 'tog-underline',
731  'section' => 'rendering/advancedrendering',
732  );
733  }
734 
735  $stubThresholdValues = array( 50, 100, 500, 1000, 2000, 5000, 10000 );
736  $stubThresholdOptions = array( $context->msg( 'stub-threshold-disabled' )->text() => 0 );
737  foreach ( $stubThresholdValues as $value ) {
738  $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
739  }
740 
741  $defaultPreferences['stubthreshold'] = array(
742  'type' => 'select',
743  'section' => 'rendering/advancedrendering',
744  'options' => $stubThresholdOptions,
745  'size' => 20,
746  'label-raw' => $context->msg( 'stub-threshold' )->text(), // Raw HTML message. Yay?
747  );
748 
749  $defaultPreferences['showhiddencats'] = array(
750  'type' => 'toggle',
751  'section' => 'rendering/advancedrendering',
752  'label-message' => 'tog-showhiddencats'
753  );
754 
755  $defaultPreferences['numberheadings'] = array(
756  'type' => 'toggle',
757  'section' => 'rendering/advancedrendering',
758  'label-message' => 'tog-numberheadings',
759  );
760  }
761 
768  global $wgAllowUserCssPrefs;
769 
770  ## Editing #####################################
771  $defaultPreferences['editsectiononrightclick'] = array(
772  'type' => 'toggle',
773  'section' => 'editing/advancedediting',
774  'label-message' => 'tog-editsectiononrightclick',
775  );
776  $defaultPreferences['editondblclick'] = array(
777  'type' => 'toggle',
778  'section' => 'editing/advancedediting',
779  'label-message' => 'tog-editondblclick',
780  );
781 
782  if ( $wgAllowUserCssPrefs ) {
783  $defaultPreferences['editfont'] = array(
784  'type' => 'select',
785  'section' => 'editing/editor',
786  'label-message' => 'editfont-style',
787  'options' => array(
788  $context->msg( 'editfont-default' )->text() => 'default',
789  $context->msg( 'editfont-monospace' )->text() => 'monospace',
790  $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
791  $context->msg( 'editfont-serif' )->text() => 'serif',
792  )
793  );
794  }
795  $defaultPreferences['cols'] = array(
796  'type' => 'int',
797  'label-message' => 'columns',
798  'section' => 'editing/editor',
799  'min' => 4,
800  'max' => 1000,
801  );
802  $defaultPreferences['rows'] = array(
803  'type' => 'int',
804  'label-message' => 'rows',
805  'section' => 'editing/editor',
806  'min' => 4,
807  'max' => 1000,
808  );
809  if ( $user->isAllowed( 'minoredit' ) ) {
810  $defaultPreferences['minordefault'] = array(
811  'type' => 'toggle',
812  'section' => 'editing/editor',
813  'label-message' => 'tog-minordefault',
814  );
815  }
816  $defaultPreferences['forceeditsummary'] = array(
817  'type' => 'toggle',
818  'section' => 'editing/editor',
819  'label-message' => 'tog-forceeditsummary',
820  );
821  $defaultPreferences['useeditwarning'] = array(
822  'type' => 'toggle',
823  'section' => 'editing/editor',
824  'label-message' => 'tog-useeditwarning',
825  );
826  $defaultPreferences['showtoolbar'] = array(
827  'type' => 'toggle',
828  'section' => 'editing/editor',
829  'label-message' => 'tog-showtoolbar',
830  );
831 
832  $defaultPreferences['previewonfirst'] = array(
833  'type' => 'toggle',
834  'section' => 'editing/preview',
835  'label-message' => 'tog-previewonfirst',
836  );
837  $defaultPreferences['previewontop'] = array(
838  'type' => 'toggle',
839  'section' => 'editing/preview',
840  'label-message' => 'tog-previewontop',
841  );
842  $defaultPreferences['uselivepreview'] = array(
843  'type' => 'toggle',
844  'section' => 'editing/preview',
845  'label-message' => 'tog-uselivepreview',
846  );
847 
848  }
849 
855  static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
856  global $wgRCMaxAge, $wgRCShowWatchingUsers;
857 
858  ## RecentChanges #####################################
859  $defaultPreferences['rcdays'] = array(
860  'type' => 'float',
861  'label-message' => 'recentchangesdays',
862  'section' => 'rc/displayrc',
863  'min' => 1,
864  'max' => ceil( $wgRCMaxAge / ( 3600 * 24 ) ),
865  'help' => $context->msg( 'recentchangesdays-max' )->numParams(
866  ceil( $wgRCMaxAge / ( 3600 * 24 ) ) )->text()
867  );
868  $defaultPreferences['rclimit'] = array(
869  'type' => 'int',
870  'label-message' => 'recentchangescount',
871  'help-message' => 'prefs-help-recentchangescount',
872  'section' => 'rc/displayrc',
873  );
874  $defaultPreferences['usenewrc'] = array(
875  'type' => 'toggle',
876  'label-message' => 'tog-usenewrc',
877  'section' => 'rc/advancedrc',
878  );
879  $defaultPreferences['hideminor'] = array(
880  'type' => 'toggle',
881  'label-message' => 'tog-hideminor',
882  'section' => 'rc/advancedrc',
883  );
884 
885  if ( $user->useRCPatrol() ) {
886  $defaultPreferences['hidepatrolled'] = array(
887  'type' => 'toggle',
888  'section' => 'rc/advancedrc',
889  'label-message' => 'tog-hidepatrolled',
890  );
891  $defaultPreferences['newpageshidepatrolled'] = array(
892  'type' => 'toggle',
893  'section' => 'rc/advancedrc',
894  'label-message' => 'tog-newpageshidepatrolled',
895  );
896  }
897 
898  if ( $wgRCShowWatchingUsers ) {
899  $defaultPreferences['shownumberswatching'] = array(
900  'type' => 'toggle',
901  'section' => 'rc/advancedrc',
902  'label-message' => 'tog-shownumberswatching',
903  );
904  }
905  }
906 
913  global $wgUseRCPatrol, $wgEnableAPI, $wgRCMaxAge;
914 
915  $watchlistdaysMax = ceil( $wgRCMaxAge / ( 3600 * 24 ) );
916 
917  ## Watchlist #####################################
918  $defaultPreferences['watchlistdays'] = array(
919  'type' => 'float',
920  'min' => 0,
921  'max' => $watchlistdaysMax,
922  'section' => 'watchlist/displaywatchlist',
923  'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
924  $watchlistdaysMax )->text(),
925  'label-message' => 'prefs-watchlist-days',
926  );
927  $defaultPreferences['wllimit'] = array(
928  'type' => 'int',
929  'min' => 0,
930  'max' => 1000,
931  'label-message' => 'prefs-watchlist-edits',
932  'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
933  'section' => 'watchlist/displaywatchlist',
934  );
935  $defaultPreferences['extendwatchlist'] = array(
936  'type' => 'toggle',
937  'section' => 'watchlist/advancedwatchlist',
938  'label-message' => 'tog-extendwatchlist',
939  );
940  $defaultPreferences['watchlisthideminor'] = array(
941  'type' => 'toggle',
942  'section' => 'watchlist/advancedwatchlist',
943  'label-message' => 'tog-watchlisthideminor',
944  );
945  $defaultPreferences['watchlisthidebots'] = array(
946  'type' => 'toggle',
947  'section' => 'watchlist/advancedwatchlist',
948  'label-message' => 'tog-watchlisthidebots',
949  );
950  $defaultPreferences['watchlisthideown'] = array(
951  'type' => 'toggle',
952  'section' => 'watchlist/advancedwatchlist',
953  'label-message' => 'tog-watchlisthideown',
954  );
955  $defaultPreferences['watchlisthideanons'] = array(
956  'type' => 'toggle',
957  'section' => 'watchlist/advancedwatchlist',
958  'label-message' => 'tog-watchlisthideanons',
959  );
960  $defaultPreferences['watchlisthideliu'] = array(
961  'type' => 'toggle',
962  'section' => 'watchlist/advancedwatchlist',
963  'label-message' => 'tog-watchlisthideliu',
964  );
965 
966  if ( $wgUseRCPatrol ) {
967  $defaultPreferences['watchlisthidepatrolled'] = array(
968  'type' => 'toggle',
969  'section' => 'watchlist/advancedwatchlist',
970  'label-message' => 'tog-watchlisthidepatrolled',
971  );
972  }
973 
974  $watchTypes = array(
975  'edit' => 'watchdefault',
976  'move' => 'watchmoves',
977  'delete' => 'watchdeletion'
978  );
979 
980  // Kinda hacky
981  if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
982  $watchTypes['read'] = 'watchcreations';
983  }
984 
985  foreach ( $watchTypes as $action => $pref ) {
986  if ( $user->isAllowed( $action ) ) {
987  // Messages:
988  // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations
989  $defaultPreferences[$pref] = array(
990  'type' => 'toggle',
991  'section' => 'watchlist/advancedwatchlist',
992  'label-message' => "tog-$pref",
993  );
994  }
995  }
996 
997  if ( $wgEnableAPI ) {
998  $defaultPreferences['watchlisttoken'] = array(
999  'type' => 'api',
1000  );
1001  $defaultPreferences['watchlisttoken-info'] = array(
1002  'type' => 'info',
1003  'section' => 'watchlist/tokenwatchlist',
1004  'label-message' => 'prefs-watchlist-token',
1005  'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1006  'help-message' => 'prefs-help-watchlist-token2',
1007  );
1008  }
1009  }
1010 
1018 
1019  $defaultPreferences['searcheverything'] = array(
1020  'type' => 'toggle',
1021  'label-message' => 'searcheverything-enable',
1022  'section' => 'searchoptions/advancedsearchoptions',
1023  );
1024 
1025  $nsOptions = $wgContLang->getFormattedNamespaces();
1026  $nsOptions[0] = $context->msg( 'blanknamespace' )->text();
1027  foreach ( $nsOptions as $ns => $name ) {
1028  if ( $ns < 0 ) {
1029  unset( $nsOptions[$ns] );
1030  }
1031  }
1032 
1033  $defaultPreferences['searchnamespaces'] = array(
1034  'type' => 'multiselect',
1035  'label-message' => 'defaultns',
1036  'options' => array_flip( $nsOptions ),
1037  'section' => 'searchoptions/advancedsearchoptions',
1038  'prefix' => 'searchNs',
1039  );
1040  }
1041 
1045  static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1046  }
1047 
1053  static function generateSkinOptions( $user, IContextSource $context ) {
1054  global $wgDefaultSkin, $wgAllowUserCss, $wgAllowUserJs;
1055  $ret = array();
1056 
1057  $mptitle = Title::newMainPage();
1058  $previewtext = $context->msg( 'skin-preview' )->text();
1059 
1060  # Only show skins that aren't disabled in $wgSkipSkins
1061  $validSkinNames = Skin::getAllowedSkins();
1062 
1063  # Sort by UI skin name. First though need to update validSkinNames as sometimes
1064  # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1065  foreach ( $validSkinNames as $skinkey => &$skinname ) {
1066  $msg = $context->msg( "skinname-{$skinkey}" );
1067  if ( $msg->exists() ) {
1068  $skinname = htmlspecialchars( $msg->text() );
1069  }
1070  }
1071  asort( $validSkinNames );
1072 
1073  foreach ( $validSkinNames as $skinkey => $sn ) {
1074  $linkTools = array();
1075 
1076  # Mark the default skin
1077  if ( $skinkey == $wgDefaultSkin ) {
1078  $linkTools[] = $context->msg( 'default' )->escaped();
1079  }
1080 
1081  # Create preview link
1082  $mplink = htmlspecialchars( $mptitle->getLocalURL( array( 'useskin' => $skinkey ) ) );
1083  $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1084 
1085  # Create links to user CSS/JS pages
1086  if ( $wgAllowUserCss ) {
1087  $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1088  $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1089  }
1090 
1091  if ( $wgAllowUserJs ) {
1092  $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1093  $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1094  }
1095 
1096  $display = $sn . ' ' . $context->msg(
1097  'parentheses',
1098  $context->getLanguage()->pipeList( $linkTools )
1099  )->text();
1100  $ret[$display] = $skinkey;
1101  }
1102 
1103  return $ret;
1104  }
1105 
1110  static function getDateOptions( IContextSource $context ) {
1111  $lang = $context->getLanguage();
1112  $dateopts = $lang->getDatePreferences();
1113 
1114  $ret = array();
1115 
1116  if ( $dateopts ) {
1117  if ( !in_array( 'default', $dateopts ) ) {
1118  $dateopts[] = 'default'; // Make sure default is always valid
1119  // Bug 19237
1120  }
1121 
1122  // KLUGE: site default might not be valid for user language
1123  global $wgDefaultUserOptions;
1124  if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1125  $wgDefaultUserOptions['date'] = 'default';
1126  }
1127 
1128  $epoch = wfTimestampNow();
1129  foreach ( $dateopts as $key ) {
1130  if ( $key == 'default' ) {
1131  $formatted = $context->msg( 'datedefault' )->escaped();
1132  } else {
1133  $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1134  }
1135  $ret[$formatted] = $key;
1136  }
1137  }
1138  return $ret;
1139  }
1140 
1145  static function getImageSizes( IContextSource $context ) {
1146  global $wgImageLimits;
1147 
1148  $ret = array();
1149  $pixels = $context->msg( 'unit-pixel' )->text();
1150 
1151  foreach ( $wgImageLimits as $index => $limits ) {
1152  $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1153  $ret[$display] = $index;
1154  }
1155 
1156  return $ret;
1157  }
1158 
1163  static function getThumbSizes( IContextSource $context ) {
1164  global $wgThumbLimits;
1165 
1166  $ret = array();
1167  $pixels = $context->msg( 'unit-pixel' )->text();
1168 
1169  foreach ( $wgThumbLimits as $index => $size ) {
1170  $display = $size . $pixels;
1171  $ret[$display] = $index;
1172  }
1173 
1174  return $ret;
1175  }
1176 
1183  static function validateSignature( $signature, $alldata, $form ) {
1184  global $wgParser, $wgMaxSigChars;
1185  if ( mb_strlen( $signature ) > $wgMaxSigChars ) {
1186  return Xml::element( 'span', array( 'class' => 'error' ),
1187  $form->msg( 'badsiglength' )->numParams( $wgMaxSigChars )->text() );
1188  } elseif ( isset( $alldata['fancysig'] ) &&
1189  $alldata['fancysig'] &&
1190  $wgParser->validateSig( $signature ) === false
1191  ) {
1192  return Xml::element(
1193  'span',
1194  array( 'class' => 'error' ),
1195  $form->msg( 'badsig' )->text()
1196  );
1197  } else {
1198  return true;
1199  }
1200  }
1201 
1208  static function cleanSignature( $signature, $alldata, $form ) {
1209  if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1210  global $wgParser;
1211  $signature = $wgParser->cleanSig( $signature );
1212  } else {
1213  // When no fancy sig used, make sure ~{3,5} get removed.
1214  $signature = Parser::cleanSigInSig( $signature );
1215  }
1216 
1217  return $signature;
1218  }
1219 
1227  static function getFormObject(
1228  $user,
1229  IContextSource $context,
1230  $formClass = 'PreferencesForm',
1231  array $remove = array()
1232  ) {
1233  $formDescriptor = Preferences::getPreferences( $user, $context );
1234  if ( count( $remove ) ) {
1235  $removeKeys = array_flip( $remove );
1236  $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1237  }
1238 
1239  // Remove type=api preferences. They are not intended for rendering in the form.
1240  foreach ( $formDescriptor as $name => $info ) {
1241  if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1242  unset( $formDescriptor[$name] );
1243  }
1244  }
1245 
1249  $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1250 
1251  $htmlForm->setModifiedUser( $user );
1252  $htmlForm->setId( 'mw-prefs-form' );
1253  $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1254  # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1255  $htmlForm->setSubmitTooltip( 'preferences-save' );
1256  $htmlForm->setSubmitID( 'prefsubmit' );
1257  $htmlForm->setSubmitCallback( array( 'Preferences', 'tryFormSubmit' ) );
1258 
1259  return $htmlForm;
1260  }
1261 
1266  static function getTimezoneOptions( IContextSource $context ) {
1267  $opt = array();
1268 
1269  global $wgLocalTZoffset;
1271  // Check that $wgLocalTZoffset is the same as the local time zone offset
1272  if ( $wgLocalTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1273  $server_tz_msg = $context->msg(
1274  'timezoneuseserverdefault',
1275  $timestamp->getTimezone()->getName()
1276  )->text();
1277  } else {
1278  $tzstring = sprintf(
1279  '%+03d:%02d',
1280  floor( $wgLocalTZoffset / 60 ),
1281  abs( $wgLocalTZoffset ) % 60
1282  );
1283  $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1284  }
1285  $opt[$server_tz_msg] = "System|$wgLocalTZoffset";
1286  $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1287  $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1288 
1289  if ( function_exists( 'timezone_identifiers_list' ) ) {
1290  # Read timezone list
1291  $tzs = timezone_identifiers_list();
1292  sort( $tzs );
1293 
1294  $tzRegions = array();
1295  $tzRegions['Africa'] = $context->msg( 'timezoneregion-africa' )->text();
1296  $tzRegions['America'] = $context->msg( 'timezoneregion-america' )->text();
1297  $tzRegions['Antarctica'] = $context->msg( 'timezoneregion-antarctica' )->text();
1298  $tzRegions['Arctic'] = $context->msg( 'timezoneregion-arctic' )->text();
1299  $tzRegions['Asia'] = $context->msg( 'timezoneregion-asia' )->text();
1300  $tzRegions['Atlantic'] = $context->msg( 'timezoneregion-atlantic' )->text();
1301  $tzRegions['Australia'] = $context->msg( 'timezoneregion-australia' )->text();
1302  $tzRegions['Europe'] = $context->msg( 'timezoneregion-europe' )->text();
1303  $tzRegions['Indian'] = $context->msg( 'timezoneregion-indian' )->text();
1304  $tzRegions['Pacific'] = $context->msg( 'timezoneregion-pacific' )->text();
1305  asort( $tzRegions );
1306 
1307  $prefill = array_fill_keys( array_values( $tzRegions ), array() );
1308  $opt = array_merge( $opt, $prefill );
1309 
1310  $now = date_create( 'now' );
1311 
1312  foreach ( $tzs as $tz ) {
1313  $z = explode( '/', $tz, 2 );
1314 
1315  # timezone_identifiers_list() returns a number of
1316  # backwards-compatibility entries. This filters them out of the
1317  # list presented to the user.
1318  if ( count( $z ) != 2 || !array_key_exists( $z[0], $tzRegions ) ) {
1319  continue;
1320  }
1321 
1322  # Localize region
1323  $z[0] = $tzRegions[$z[0]];
1324 
1325  $minDiff = floor( timezone_offset_get( timezone_open( $tz ), $now ) / 60 );
1326 
1327  $display = str_replace( '_', ' ', $z[0] . '/' . $z[1] );
1328  $value = "ZoneInfo|$minDiff|$tz";
1329 
1330  $opt[$z[0]][$display] = $value;
1331  }
1332  }
1333  return $opt;
1334  }
1335 
1341  static function filterIntval( $value, $alldata ) {
1342  return intval( $value );
1343  }
1344 
1350  static function filterTimezoneInput( $tz, $alldata ) {
1351  $data = explode( '|', $tz, 3 );
1352  switch ( $data[0] ) {
1353  case 'ZoneInfo':
1354  case 'System':
1355  return $tz;
1356  default:
1357  $data = explode( ':', $tz, 2 );
1358  if ( count( $data ) == 2 ) {
1359  $data[0] = intval( $data[0] );
1360  $data[1] = intval( $data[1] );
1361  $minDiff = abs( $data[0] ) * 60 + $data[1];
1362  if ( $data[0] < 0 ) {
1363  $minDiff = - $minDiff;
1364  }
1365  } else {
1366  $minDiff = intval( $data[0] ) * 60;
1367  }
1368 
1369  # Max is +14:00 and min is -12:00, see:
1370  # http://en.wikipedia.org/wiki/Timezone
1371  $minDiff = min( $minDiff, 840 ); # 14:00
1372  $minDiff = max( $minDiff, - 720 ); # -12:00
1373  return 'Offset|' . $minDiff;
1374  }
1375  }
1376 
1384  static function tryFormSubmit( $formData, $form ) {
1385  global $wgHiddenPrefs, $wgAuth;
1386 
1387  $user = $form->getModifiedUser();
1388  $result = true;
1389 
1390  if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1391  return Status::newFatal( 'mypreferencesprotected' );
1392  }
1393 
1394  // Filter input
1395  foreach ( array_keys( $formData ) as $name ) {
1396  if ( isset( self::$saveFilters[$name] ) ) {
1397  $formData[$name] =
1398  call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1399  }
1400  }
1401 
1402  // Fortunately, the realname field is MUCH simpler
1403  // (not really "private", but still shouldn't be edited without permission)
1404  if ( !in_array( 'realname', $wgHiddenPrefs ) && $user->isAllowed( 'editmyprivateinfo' ) && array_key_exists( 'realname', $formData ) ) {
1405  $realName = $formData['realname'];
1406  $user->setRealName( $realName );
1407  }
1408 
1409  if ( $user->isAllowed( 'editmyoptions' ) ) {
1410  foreach ( self::$saveBlacklist as $b ) {
1411  unset( $formData[$b] );
1412  }
1413 
1414  # If users have saved a value for a preference which has subsequently been disabled
1415  # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1416  # is subsequently re-enabled
1417  foreach ( $wgHiddenPrefs as $pref ) {
1418  # If the user has not set a non-default value here, the default will be returned
1419  # and subsequently discarded
1420  $formData[$pref] = $user->getOption( $pref, null, true );
1421  }
1422 
1423  // Keep old preferences from interfering due to back-compat code, etc.
1424  $user->resetOptions( 'unused', $form->getContext() );
1425 
1426  foreach ( $formData as $key => $value ) {
1427  $user->setOption( $key, $value );
1428  }
1429 
1430  wfRunHooks( 'PreferencesFormPreSave', array( $formData, $form, $user, &$result ) );
1431  $user->saveSettings();
1432  }
1433 
1434  $wgAuth->updateExternalDB( $user );
1435 
1436  return $result;
1437  }
1438 
1444  public static function tryUISubmit( $formData, $form ) {
1445  $res = self::tryFormSubmit( $formData, $form );
1446 
1447  if ( $res ) {
1448  $urlOptions = array( 'success' => 1 );
1449 
1450  if ( $res === 'eauth' ) {
1451  $urlOptions['eauth'] = 1;
1452  }
1453 
1454  $urlOptions += $form->getExtraSuccessRedirectParameters();
1455 
1456  $url = $form->getTitle()->getFullURL( $urlOptions );
1457 
1458  $form->getContext()->getOutput()->redirect( $url );
1459  }
1460 
1461  return Status::newGood();
1462  }
1463 
1475  public static function trySetUserEmail( User $user, $newaddr ) {
1476  wfDeprecated( __METHOD__, '1.20' );
1477 
1478  $result = $user->setEmailWithConfirmation( $newaddr );
1479  if ( $result->isGood() ) {
1480  return array( true, $result->value );
1481  } else {
1482  return array( $result, 'mailerror' );
1483  }
1484  }
1485 
1491  public static function loadOldSearchNs( $user ) {
1492  wfDeprecated( __METHOD__, '1.19' );
1493 
1494  $searchableNamespaces = SearchEngine::searchableNamespaces();
1495  // Back compat with old format
1496  $arr = array();
1497 
1498  foreach ( $searchableNamespaces as $ns => $name ) {
1499  if ( $user->getOption( 'searchNs' . $ns ) ) {
1500  $arr[] = $ns;
1501  }
1502  }
1503 
1504  return $arr;
1505  }
1506 }
1507 
1509 class PreferencesForm extends HTMLForm {
1510  // Override default value from HTMLForm
1511  protected $mSubSectionBeforeFields = false;
1512 
1513  private $modifiedUser;
1514 
1518  public function setModifiedUser( $user ) {
1519  $this->modifiedUser = $user;
1520  }
1521 
1525  public function getModifiedUser() {
1526  if ( $this->modifiedUser === null ) {
1527  return $this->getUser();
1528  } else {
1529  return $this->modifiedUser;
1530  }
1531  }
1532 
1540  return array();
1541  }
1542 
1547  function wrapForm( $html ) {
1548  $html = Xml::tags( 'div', array( 'id' => 'preferences' ), $html );
1549 
1550  return parent::wrapForm( $html );
1551  }
1552 
1556  function getButtons() {
1557  if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1558  return '';
1559  }
1560 
1561  $html = parent::getButtons();
1562 
1563  if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1564  $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1565 
1566  $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped() );
1567 
1568  $html = Xml::tags( 'div', array( 'class' => 'mw-prefs-buttons' ), $html );
1569  }
1570 
1571  return $html;
1572  }
1573 
1580  function filterDataForSubmit( $data ) {
1581  foreach ( $this->mFlatFields as $fieldname => $field ) {
1582  if ( $field instanceof HTMLNestedFilterable ) {
1583  $info = $field->mParams;
1584  $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1585  foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1586  $data["$prefix$key"] = $value;
1587  }
1588  unset( $data[$fieldname] );
1589  }
1590  }
1591 
1592  return $data;
1593  }
1594 
1599  function getBody() {
1600  return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1601  }
1602 
1609  function getLegend( $key ) {
1610  $legend = parent::getLegend( $key );
1611  wfRunHooks( 'PreferencesGetLegend', array( $this, $key, &$legend ) );
1612  return $legend;
1613  }
1614 }
Preferences\getPreferences
static getPreferences( $user, IContextSource $context)
Definition: Preferences.php:78
Preferences\getThumbSizes
static getThumbSizes(IContextSource $context)
Definition: Preferences.php:1163
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. $title:Title object for the current page $request:WebRequest $ignoreRedirect:boolean to skip redirect check $target:Title/string of redirect target $article:Article object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) $article:article(object) being checked 'IsTrustedProxy':Override the result of wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of User::isValidEmailAddr(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetMagic':DEPRECATED, use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetSpecialPageAliases':DEPRECATED, use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1528
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1358
Preferences\filterTimezoneInput
static filterTimezoneInput( $tz, $alldata)
Definition: Preferences.php:1350
wfBCP47
wfBCP47( $code)
Get the normalised IETF language tag See unit test for examples.
Definition: GlobalFunctions.php:3920
wfCanIPUseHTTPS
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
Definition: GlobalFunctions.php:4129
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
Preferences\rcPreferences
static rcPreferences( $user, IContextSource $context, &$defaultPreferences)
Definition: Preferences.php:855
$html
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1530
ContextSource\msg
msg()
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:175
Preferences\trySetUserEmail
static trySetUserEmail(User $user, $newaddr)
Try to set a user's email address.
Definition: Preferences.php:1475
Xml\tags
static tags( $element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:131
Preferences\editingPreferences
static editingPreferences( $user, IContextSource $context, &$defaultPreferences)
Definition: Preferences.php:767
PreferencesForm\filterDataForSubmit
filterDataForSubmit( $data)
Separate multi-option preferences into multiple preferences, since we have to store them separately.
Definition: Preferences.php:1580
PreferencesForm\getExtraSuccessRedirectParameters
getExtraSuccessRedirectParameters()
Get extra parameters for the query string when redirecting after successful save.
Definition: Preferences.php:1539
Preferences\$defaultPreferences
static $defaultPreferences
Definition: Preferences.php:49
text
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
$timestamp
if( $limit) $timestamp
Definition: importImages.php:104
Preferences\$saveFilters
static $saveFilters
Definition: Preferences.php:50
Title\newMainPage
static newMainPage()
Create a new Title for the Main Page.
Definition: Title.php:441
$form
usually copyright or history_copyright This message must be in HTML not wikitext $subpages will be ignored and the rest of subPageSubtitle() will run. 'SkinTemplateBuildNavUrlsNav_urlsAfterPermalink' whether MediaWiki currently thinks this is a CSS JS page Hooks may change this value to override the return value of Title::isCssOrJsPage(). 'TitleIsAlwaysKnown' whether MediaWiki currently thinks this page is known isMovable() always returns false. $title whether MediaWiki currently thinks this page is movable Hooks may change this value to override the return value of Title::isMovable(). 'TitleIsWikitextPage' whether MediaWiki currently thinks this is a wikitext page Hooks may change this value to override the return value of Title::isWikitextPage() 'TitleMove' use UploadVerification and UploadVerifyFile instead $form
Definition: hooks.txt:2573
SearchEngine\searchableNamespaces
static searchableNamespaces()
Make a list of searchable namespaces and their canonical names.
Definition: SearchEngine.php:334
MediaWiki\getTitle
getTitle()
Get the Title object that we'll be acting on, as specified in the WebRequest.
Definition: Wiki.php:134
$defaultOptions
return false to override stock group addition can be modified try getUserPermissionsErrors userCan checks are continued by internal code can override on output return false to not delete it return false to override the default password checks this Boolean value will be checked to determine if the password was valid return false to implement your own hashing method this String will be used as the hash which may be added to this hook is run right before returning the options to the caller which means it s potentially called dozens or hundreds of times You may want to cache the results of non trivial operations in your hook function for this reason & $defaultOptions
Definition: hooks.txt:2697
User\makeGroupLinkHTML
static makeGroupLinkHTML( $group, $text='')
Create a link to the group in HTML, if available; else return the group name.
Definition: User.php:4282
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1530
PreferencesForm\wrapForm
wrapForm( $html)
Definition: Preferences.php:1547
Status\newGood
static newGood( $value=null)
Factory function for good results.
Definition: Status.php:77
PreferencesForm\getLegend
getLegend( $key)
Get the "<legend>" for a given section key.
Definition: Preferences.php:1609
PreferencesForm\getBody
getBody()
Get the whole body of the form.
Definition: Preferences.php:1599
Preferences\searchPreferences
static searchPreferences( $user, IContextSource $context, &$defaultPreferences)
Definition: Preferences.php:1016
IContextSource\msg
msg()
Get a Message object with context set.
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name.
Definition: SpecialPage.php:74
Preferences\filterIntval
static filterIntval( $value, $alldata)
Definition: Preferences.php:1341
Html\hidden
static hidden( $name, $value, $attribs=array())
Convenience function to produce an input element with type=hidden.
Definition: Html.php:662
$wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
Definition: design.txt:56
Preferences\getDateOptions
static getDateOptions(IContextSource $context)
Definition: Preferences.php:1110
Preferences\tryUISubmit
static tryUISubmit( $formData, $form)
Definition: Preferences.php:1444
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:132
$link
set to $title object and return false for a match for latest after cache objects are set use the ContentHandler facility to handle CSS and JavaScript for highlighting & $link
Definition: hooks.txt:2149
PreferencesForm\$modifiedUser
$modifiedUser
Definition: Preferences.php:1513
PreferencesForm\getButtons
getButtons()
Definition: Preferences.php:1556
Linker\linkKnown
static linkKnown( $target, $html=null, $customAttribs=array(), $query=array(), $options=array( 'known', 'noclasses'))
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:264
Preferences\getSaveBlacklist
static getSaveBlacklist()
Definition: Preferences.php:68
User\getDefaultOptions
static getDefaultOptions()
Combine the language default options with any site-specific options and add the default language vari...
Definition: User.php:1350
Linker\link
static link( $target, $html=null, $customAttribs=array(), $query=array(), $options=array())
This function returns an HTML link to the given target.
Definition: Linker.php:192
below
controlled by $wgMainCacheType controlled by $wgParserCacheType controlled by $wgMessageCacheType If you set CACHE_NONE to one of the three control default value for MediaWiki still create a but requests to it are no ops and we always fall through to the database If the cache daemon can t be it should also disable itself fairly smoothly By $wgMemc is used but when it is $parserMemc or $messageMemc this is mentioned below
Definition: memcached.txt:96
Preferences
We're now using the HTMLForm object with some customisation to generate the Preferences form.
Definition: Preferences.php:48
Preferences\getFormObject
static getFormObject( $user, IContextSource $context, $formClass='PreferencesForm', array $remove=array())
Definition: Preferences.php:1227
MWException
MediaWiki exception.
Definition: MWException.php:26
PreferencesForm\getModifiedUser
getModifiedUser()
Definition: Preferences.php:1525
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1127
Language\fetchLanguageNames
static fetchLanguageNames( $inLanguage=null, $include='mw')
Get an array of language names, indexed by code.
Definition: Language.php:875
Preferences\generateSkinOptions
static generateSkinOptions( $user, IContextSource $context)
Definition: Preferences.php:1053
Xml\element
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:39
wfRunHooks
wfRunHooks( $event, array $args=array(), $deprecatedVersion=null)
Call hook functions defined in $wgHooks.
Definition: GlobalFunctions.php:4001
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
PreferencesForm
Some tweaks to allow js prefs to work.
Definition: Preferences.php:1509
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:2514
$columns
if(! $in) $columns
Definition: Utf8Test.php:50
Preferences\validateSignature
static validateSignature( $signature, $alldata, $form)
Definition: Preferences.php:1183
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:188
Preferences\miscPreferences
static miscPreferences( $user, IContextSource $context, &$defaultPreferences)
Dummy, kept for backwards-compatibility.
Definition: Preferences.php:1045
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1530
Preferences\watchlistPreferences
static watchlistPreferences( $user, IContextSource $context, &$defaultPreferences)
Definition: Preferences.php:912
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:422
$languages
$languages
Definition: rebuildLanguage.php:129
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:336
Preferences\tryFormSubmit
static tryFormSubmit( $formData, $form)
Handle the form submission if everything validated properly.
Definition: Preferences.php:1384
Preferences\skinPreferences
static skinPreferences( $user, IContextSource $context, &$defaultPreferences)
Definition: Preferences.php:570
$size
$size
Definition: RandomTest.php:75
$value
$value
Definition: styleTest.css.php:45
ParserOptions\newFromContext
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
Definition: ParserOptions.php:396
Preferences\$saveBlacklist
static $saveBlacklist
Definition: Preferences.php:60
HTMLForm\displaySection
displaySection( $fields, $sectionName='', $fieldsetIDPrefix='', &$hasUserVisibleFields=false)
Definition: HTMLForm.php:1169
IContextSource\getUser
getUser()
Get the User object.
PreferencesForm\setModifiedUser
setModifiedUser( $user)
Definition: Preferences.php:1518
IContextSource\getTitle
getTitle()
Get the Title object.
HTMLForm\loadInputFromParameters
static loadInputFromParameters( $fieldname, $descriptor)
Initialise a new Object for the field.
Definition: HTMLForm.php:351
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:237
User\getGroupMember
static getGroupMember( $group, $username='#')
Get the localized descriptive name for a member of a group, if it exists.
Definition: User.php:4210
IContextSource
Interface for objects which can provide a context on request.
Definition: IContextSource.php:29
User\getGroupName
static getGroupName( $group)
Get the localized descriptive name for a group, if it exists.
Definition: User.php:4198
$wgParser
$wgParser
Definition: Setup.php:567
Preferences\profilePreferences
static profilePreferences( $user, IContextSource $context, &$defaultPreferences)
Definition: Preferences.php:194
Preferences\getTimezoneOptions
static getTimezoneOptions(IContextSource $context)
Definition: Preferences.php:1266
on
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going on
Definition: hooks.txt:86
PreferencesForm\$mSubSectionBeforeFields
$mSubSectionBeforeFields
Definition: Preferences.php:1511
HTMLNestedFilterable
Definition: HTMLNestedFilterable.php:3
used
you don t have to do a grep find to see where the $wgReverseTitle variable is used
Definition: hooks.txt:117
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
NS_USER
const NS_USER
Definition: Defines.php:81
IContextSource\getRequest
getRequest()
Get the WebRequest object.
HTMLFormField\flattenOptions
static flattenOptions( $options)
flatten an array of options to a single array, for instance, a set of "<options>" inside "<optgroups>...
Definition: HTMLFormField.php:601
$t
$t
Definition: testCompression.php:65
Skin\getAllowedSkins
static getAllowedSkins()
Fetch the list of user-selectable skins in regards to $wgSkipSkins.
Definition: Skin.php:108
Preferences\loadOldSearchNs
static loadOldSearchNs( $user)
Definition: Preferences.php:1491
Preferences\getImageSizes
static getImageSizes(IContextSource $context)
Definition: Preferences.php:1145
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:59
message
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a message
Definition: hooks.txt:1624
IContextSource\getOutput
getOutput()
Get the OutputPage object.
$res
$res
Definition: database.txt:21
MWTimestamp\getLocalInstance
static getLocalInstance( $ts=false)
Get a timestamp instance in the server local timezone ($wgLocaltimezone)
Definition: MWTimestamp.php:373
Preferences\filesPreferences
static filesPreferences( $user, IContextSource $context, &$defaultPreferences)
Definition: Preferences.php:613
Preferences\getOptionFromUser
static getOptionFromUser( $name, $info, $user)
Pull option from a user account.
Definition: Preferences.php:151
Preferences\renderingPreferences
static renderingPreferences( $user, IContextSource $context, &$defaultPreferences)
Definition: Preferences.php:707
IContextSource\getLanguage
getLanguage()
Get the Language object.
Status\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: Status.php:63
Preferences\cleanSignature
static cleanSignature( $signature, $alldata, $form)
Definition: Preferences.php:1208
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition: HTMLForm.php:100
Preferences\datetimePreferences
static datetimePreferences( $user, IContextSource $context, &$defaultPreferences)
Definition: Preferences.php:635