MediaWiki  master
SpecialBlock.php
Go to the documentation of this file.
1 <?php
26 
36  protected $target;
37 
39  protected $type;
40 
42  protected $previousTarget;
43 
45  protected $requestedHideUser;
46 
48  protected $alreadyBlocked;
49 
51  protected $preErrors = [];
52 
53  public function __construct() {
54  parent::__construct( 'Block', 'block' );
55  }
56 
57  public function doesWrites() {
58  return true;
59  }
60 
67  protected function checkExecutePermissions( User $user ) {
68  parent::checkExecutePermissions( $user );
69  # T17810: blocked admins should have limited access here
70  $status = self::checkUnblockSelf( $this->target, $user );
71  if ( $status !== true ) {
72  throw new ErrorPageError( 'badaccess', $status );
73  }
74  }
75 
81  public function requiresUnblock() {
82  return false;
83  }
84 
90  protected function setParameter( $par ) {
91  # Extract variables from the request. Try not to get into a situation where we
92  # need to extract *every* variable from the form just for processing here, but
93  # there are legitimate uses for some variables
94  $request = $this->getRequest();
95  list( $this->target, $this->type ) = self::getTargetAndType( $par, $request );
96  if ( $this->target instanceof User ) {
97  # Set the 'relevant user' in the skin, so it displays links like Contributions,
98  # User logs, UserRights, etc.
99  $this->getSkin()->setRelevantUser( $this->target );
100  }
101 
102  list( $this->previousTarget, /*...*/ ) =
103  Block::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
104  $this->requestedHideUser = $request->getBool( 'wpHideUser' );
105  }
106 
112  protected function alterForm( HTMLForm $form ) {
113  $form->setHeaderText( '' );
114  $form->setSubmitDestructive();
115 
116  $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
117  $form->setSubmitTextMsg( $msg );
118 
119  $this->addHelpLink( 'Help:Blocking users' );
120 
121  # Don't need to do anything if the form has been posted
122  if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
123  $s = $form->formatErrors( $this->preErrors );
124  if ( $s ) {
126  'div',
127  [ 'class' => 'error' ],
128  $s
129  ) );
130  }
131  }
132  }
133 
134  protected function getDisplayFormat() {
135  return 'ooui';
136  }
137 
142  protected function getFormFields() {
143  global $wgBlockAllowsUTEdit;
144 
145  $user = $this->getUser();
146 
147  $suggestedDurations = self::getSuggestedDurations();
148 
149  $conf = $this->getConfig();
150  $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD;
151  $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
152 
153  $a = [];
154 
155  $a['Target'] = [
156  'type' => 'user',
157  'ipallowed' => true,
158  'iprange' => true,
159  'label-message' => 'ipaddressorusername',
160  'id' => 'mw-bi-target',
161  'size' => '45',
162  'autofocus' => true,
163  'required' => true,
164  'validation-callback' => [ __CLASS__, 'validateTargetField' ],
165  ];
166 
167  if ( $enablePartialBlocks ) {
168  $a['EditingRestriction'] = [
169  'type' => 'radio',
170  'label' => $this->msg( 'ipb-type-label' )->text(),
171  'options' => [
172  $this->msg( 'ipb-sitewide' )->text() => 'sitewide',
173  $this->msg( 'ipb-partial' )->text() => 'partial',
174  ],
175  ];
176  $a['PageRestrictions'] = [
177  'type' => 'titlesmultiselect',
178  'label' => $this->msg( 'ipb-pages-label' )->text(),
179  'exists' => true,
180  'max' => 10,
181  'cssclass' => 'mw-block-page-restrictions',
182  'showMissing' => false,
183  'input' => [
184  'autocomplete' => false
185  ],
186  ];
187  }
188 
189  $a['Expiry'] = [
190  'type' => 'expiry',
191  'label-message' => 'ipbexpiry',
192  'required' => true,
193  'options' => $suggestedDurations,
194  'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
195  ];
196 
197  $a['Reason'] = [
198  'type' => 'selectandother',
199  // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
200  // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
201  // Unicode codepoints (or 255 UTF-8 bytes for old schema).
202  'maxlength' => $oldCommentSchema ? 255 : CommentStore::COMMENT_CHARACTER_LIMIT,
203  'maxlength-unit' => 'codepoints',
204  'label-message' => 'ipbreason',
205  'options-message' => 'ipbreason-dropdown',
206  ];
207 
208  $a['CreateAccount'] = [
209  'type' => 'check',
210  'label-message' => 'ipbcreateaccount',
211  'default' => true,
212  ];
213 
214  if ( self::canBlockEmail( $user ) ) {
215  $a['DisableEmail'] = [
216  'type' => 'check',
217  'label-message' => 'ipbemailban',
218  ];
219  }
220 
221  if ( $wgBlockAllowsUTEdit ) {
222  $a['DisableUTEdit'] = [
223  'type' => 'check',
224  'label-message' => 'ipb-disableusertalk',
225  'default' => false,
226  ];
227  }
228 
229  $a['AutoBlock'] = [
230  'type' => 'check',
231  'label-message' => 'ipbenableautoblock',
232  'default' => true,
233  ];
234 
235  # Allow some users to hide name from block log, blocklist and listusers
236  if ( $user->isAllowed( 'hideuser' ) ) {
237  $a['HideUser'] = [
238  'type' => 'check',
239  'label-message' => 'ipbhidename',
240  'cssclass' => 'mw-block-hideuser',
241  ];
242  }
243 
244  # Watchlist their user page? (Only if user is logged in)
245  if ( $user->isLoggedIn() ) {
246  $a['Watch'] = [
247  'type' => 'check',
248  'label-message' => 'ipbwatchuser',
249  ];
250  }
251 
252  $a['HardBlock'] = [
253  'type' => 'check',
254  'label-message' => 'ipb-hardblock',
255  'default' => false,
256  ];
257 
258  # This is basically a copy of the Target field, but the user can't change it, so we
259  # can see if the warnings we maybe showed to the user before still apply
260  $a['PreviousTarget'] = [
261  'type' => 'hidden',
262  'default' => false,
263  ];
264 
265  # We'll turn this into a checkbox if we need to
266  $a['Confirm'] = [
267  'type' => 'hidden',
268  'default' => '',
269  'label-message' => 'ipb-confirm',
270  'cssclass' => 'mw-block-confirm',
271  ];
272 
273  $this->maybeAlterFormDefaults( $a );
274 
275  // Allow extensions to add more fields
276  Hooks::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
277 
278  return $a;
279  }
280 
288  protected function maybeAlterFormDefaults( &$fields ) {
289  # This will be overwritten by request data
290  $fields['Target']['default'] = (string)$this->target;
291 
292  if ( $this->target ) {
293  $status = self::validateTarget( $this->target, $this->getUser() );
294  if ( !$status->isOK() ) {
295  $errors = $status->getErrorsArray();
296  $this->preErrors = array_merge( $this->preErrors, $errors );
297  }
298  }
299 
300  # This won't be
301  $fields['PreviousTarget']['default'] = (string)$this->target;
302 
303  $block = Block::newFromTarget( $this->target );
304 
305  if ( $block instanceof Block && !$block->mAuto # The block exists and isn't an autoblock
306  && ( $this->type != Block::TYPE_RANGE # The block isn't a rangeblock
307  || $block->getTarget() == $this->target ) # or if it is, the range is what we're about to block
308  ) {
309  $fields['HardBlock']['default'] = $block->isHardblock();
310  $fields['CreateAccount']['default'] = $block->prevents( 'createaccount' );
311  $fields['AutoBlock']['default'] = $block->isAutoblocking();
312 
313  if ( isset( $fields['DisableEmail'] ) ) {
314  $fields['DisableEmail']['default'] = $block->prevents( 'sendemail' );
315  }
316 
317  if ( isset( $fields['HideUser'] ) ) {
318  $fields['HideUser']['default'] = $block->mHideName;
319  }
320 
321  if ( isset( $fields['DisableUTEdit'] ) ) {
322  $fields['DisableUTEdit']['default'] = $block->prevents( 'editownusertalk' );
323  }
324 
325  // If the username was hidden (ipb_deleted == 1), don't show the reason
326  // unless this user also has rights to hideuser: T37839
327  if ( !$block->mHideName || $this->getUser()->isAllowed( 'hideuser' ) ) {
328  $fields['Reason']['default'] = $block->mReason;
329  } else {
330  $fields['Reason']['default'] = '';
331  }
332 
333  if ( $this->getRequest()->wasPosted() ) {
334  # Ok, so we got a POST submission asking us to reblock a user. So show the
335  # confirm checkbox; the user will only see it if they haven't previously
336  $fields['Confirm']['type'] = 'check';
337  } else {
338  # We got a target, but it wasn't a POST request, so the user must have gone
339  # to a link like [[Special:Block/User]]. We don't need to show the checkbox
340  # as long as they go ahead and block *that* user
341  $fields['Confirm']['default'] = 1;
342  }
343 
344  if ( $block->mExpiry == 'infinity' ) {
345  $fields['Expiry']['default'] = 'infinite';
346  } else {
347  $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->mExpiry );
348  }
349 
350  $this->alreadyBlocked = true;
351  $this->preErrors[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
352  }
353 
354  # We always need confirmation to do HideUser
355  if ( $this->requestedHideUser ) {
356  $fields['Confirm']['type'] = 'check';
357  unset( $fields['Confirm']['default'] );
358  $this->preErrors[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
359  }
360 
361  # Or if the user is trying to block themselves
362  if ( (string)$this->target === $this->getUser()->getName() ) {
363  $fields['Confirm']['type'] = 'check';
364  unset( $fields['Confirm']['default'] );
365  $this->preErrors[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
366  }
367 
368  if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
369  if ( $block instanceof Block && !$block->isSitewide() ) {
370  $fields['EditingRestriction']['default'] = 'partial';
371  } else {
372  $fields['EditingRestriction']['default'] = 'sitewide';
373  }
374 
375  if ( $block instanceof Block ) {
376  $pageRestrictions = [];
377  foreach ( $block->getRestrictions() as $restriction ) {
378  if ( $restriction->getType() !== 'page' ) {
379  continue;
380  }
381 
382  $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
383  }
384 
385  // Sort the restrictions so they are in alphabetical order.
386  sort( $pageRestrictions );
387  $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
388  }
389  }
390  }
391 
396  protected function preText() {
397  $this->getOutput()->addModuleStyles( 'mediawiki.widgets.TitlesMultiselectWidget.styles' );
398  $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
399 
400  $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
401  $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
402 
403  $otherBlockMessages = [];
404  if ( $this->target !== null ) {
405  $targetName = $this->target;
406  if ( $this->target instanceof User ) {
407  $targetName = $this->target->getName();
408  }
409  # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
410  Hooks::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
411 
412  if ( count( $otherBlockMessages ) ) {
414  'h2',
415  [],
416  $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
417  ) . "\n";
418 
419  $list = '';
420 
421  foreach ( $otherBlockMessages as $link ) {
422  $list .= Html::rawElement( 'li', [], $link ) . "\n";
423  }
424 
425  $s .= Html::rawElement(
426  'ul',
427  [ 'class' => 'mw-blockip-alreadyblocked' ],
428  $list
429  ) . "\n";
430 
431  $text .= $s;
432  }
433  }
434 
435  return $text;
436  }
437 
442  protected function postText() {
443  $links = [];
444 
445  $this->getOutput()->addModuleStyles( 'mediawiki.special' );
446 
447  $linkRenderer = $this->getLinkRenderer();
448  # Link to the user's contributions, if applicable
449  if ( $this->target instanceof User ) {
450  $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
451  $links[] = $linkRenderer->makeLink(
452  $contribsPage,
453  $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->text()
454  );
455  }
456 
457  # Link to unblock the specified user, or to a blank unblock form
458  if ( $this->target instanceof User ) {
459  $message = $this->msg(
460  'ipb-unblock-addr',
461  wfEscapeWikiText( $this->target->getName() )
462  )->parse();
463  $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
464  } else {
465  $message = $this->msg( 'ipb-unblock' )->parse();
466  $list = SpecialPage::getTitleFor( 'Unblock' );
467  }
468  $links[] = $linkRenderer->makeKnownLink(
469  $list,
470  new HtmlArmor( $message )
471  );
472 
473  # Link to the block list
474  $links[] = $linkRenderer->makeKnownLink(
475  SpecialPage::getTitleFor( 'BlockList' ),
476  $this->msg( 'ipb-blocklist' )->text()
477  );
478 
479  $user = $this->getUser();
480 
481  # Link to edit the block dropdown reasons, if applicable
482  if ( $user->isAllowed( 'editinterface' ) ) {
483  $links[] = $linkRenderer->makeKnownLink(
484  $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
485  $this->msg( 'ipb-edit-dropdown' )->text(),
486  [],
487  [ 'action' => 'edit' ]
488  );
489  }
490 
491  $text = Html::rawElement(
492  'p',
493  [ 'class' => 'mw-ipb-conveniencelinks' ],
494  $this->getLanguage()->pipeList( $links )
495  );
496 
497  $userTitle = self::getTargetUserTitle( $this->target );
498  if ( $userTitle ) {
499  # Get relevant extracts from the block and suppression logs, if possible
500  $out = '';
501 
503  $out,
504  'block',
505  $userTitle,
506  '',
507  [
508  'lim' => 10,
509  'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
510  'showIfEmpty' => false
511  ]
512  );
513  $text .= $out;
514 
515  # Add suppression block entries if allowed
516  if ( $user->isAllowed( 'suppressionlog' ) ) {
518  $out,
519  'suppress',
520  $userTitle,
521  '',
522  [
523  'lim' => 10,
524  'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
525  'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
526  'showIfEmpty' => false
527  ]
528  );
529 
530  $text .= $out;
531  }
532  }
533 
534  return $text;
535  }
536 
543  protected static function getTargetUserTitle( $target ) {
544  if ( $target instanceof User ) {
545  return $target->getUserPage();
546  } elseif ( IP::isIPAddress( $target ) ) {
548  }
549 
550  return null;
551  }
552 
561  public static function getTargetAndType( $par, WebRequest $request = null ) {
562  $i = 0;
563  $target = null;
564 
565  while ( true ) {
566  switch ( $i++ ) {
567  case 0:
568  # The HTMLForm will check wpTarget first and only if it doesn't get
569  # a value use the default, which will be generated from the options
570  # below; so this has to have a higher precedence here than $par, or
571  # we could end up with different values in $this->target and the HTMLForm!
572  if ( $request instanceof WebRequest ) {
573  $target = $request->getText( 'wpTarget', null );
574  }
575  break;
576  case 1:
577  $target = $par;
578  break;
579  case 2:
580  if ( $request instanceof WebRequest ) {
581  $target = $request->getText( 'ip', null );
582  }
583  break;
584  case 3:
585  # B/C @since 1.18
586  if ( $request instanceof WebRequest ) {
587  $target = $request->getText( 'wpBlockAddress', null );
588  }
589  break;
590  case 4:
591  break 2;
592  }
593 
595 
596  if ( $type !== null ) {
597  return [ $target, $type ];
598  }
599  }
600 
601  return [ null, null ];
602  }
603 
612  public static function validateTargetField( $value, $alldata, $form ) {
613  $status = self::validateTarget( $value, $form->getUser() );
614  if ( !$status->isOK() ) {
615  $errors = $status->getErrorsArray();
616 
617  return $form->msg( ...$errors[0] );
618  } else {
619  return true;
620  }
621  }
622 
631  public static function validateTarget( $value, User $user ) {
632  global $wgBlockCIDRLimit;
633 
635  list( $target, $type ) = self::getTargetAndType( $value );
637 
638  if ( $type == Block::TYPE_USER ) {
639  if ( $target->isAnon() ) {
640  $status->fatal(
641  'nosuchusershort',
643  );
644  }
645 
646  $unblockStatus = self::checkUnblockSelf( $target, $user );
647  if ( $unblockStatus !== true ) {
648  $status->fatal( 'badaccess', $unblockStatus );
649  }
650  } elseif ( $type == Block::TYPE_RANGE ) {
651  list( $ip, $range ) = explode( '/', $target, 2 );
652 
653  if (
654  ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
655  ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
656  ) {
657  // Range block effectively disabled
658  $status->fatal( 'range_block_disabled' );
659  }
660 
661  if (
662  ( IP::isIPv4( $ip ) && $range > 32 ) ||
663  ( IP::isIPv6( $ip ) && $range > 128 )
664  ) {
665  // Dodgy range
666  $status->fatal( 'ip_range_invalid' );
667  }
668 
669  if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
670  $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
671  }
672 
673  if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
674  $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
675  }
676  } elseif ( $type == Block::TYPE_IP ) {
677  # All is well
678  } else {
679  $status->fatal( 'badipaddress' );
680  }
681 
682  return $status;
683  }
684 
692  public static function processForm( array $data, IContextSource $context ) {
694 
695  $performer = $context->getUser();
696  $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
697 
698  // Handled by field validator callback
699  // self::validateTargetField( $data['Target'] );
700 
701  # This might have been a hidden field or a checkbox, so interesting data
702  # can come from it
703  $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
704 
706  list( $target, $type ) = self::getTargetAndType( $data['Target'] );
707  if ( $type == Block::TYPE_USER ) {
708  $user = $target;
709  $target = $user->getName();
710  $userId = $user->getId();
711 
712  # Give admins a heads-up before they go and block themselves. Much messier
713  # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
714  # permission anyway, although the code does allow for it.
715  # Note: Important to use $target instead of $data['Target']
716  # since both $data['PreviousTarget'] and $target are normalized
717  # but $data['target'] gets overridden by (non-normalized) request variable
718  # from previous request.
719  if ( $target === $performer->getName() &&
720  ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
721  ) {
722  return [ 'ipb-blockingself', 'ipb-confirmaction' ];
723  }
724  } elseif ( $type == Block::TYPE_RANGE ) {
725  $user = null;
726  $userId = 0;
727  } elseif ( $type == Block::TYPE_IP ) {
728  $user = null;
729  $target = $target->getName();
730  $userId = 0;
731  } else {
732  # This should have been caught in the form field validation
733  return [ 'badipaddress' ];
734  }
735 
736  $expiryTime = self::parseExpiryInput( $data['Expiry'] );
737 
738  if (
739  // an expiry time is needed
740  ( strlen( $data['Expiry'] ) == 0 ) ||
741  // can't be a larger string as 50 (it should be a time format in any way)
742  ( strlen( $data['Expiry'] ) > 50 ) ||
743  // check, if the time could be parsed
744  !$expiryTime
745  ) {
746  return [ 'ipb_expiry_invalid' ];
747  }
748 
749  // an expiry time should be in the future, not in the
750  // past (wouldn't make any sense) - bug T123069
751  if ( $expiryTime < wfTimestampNow() ) {
752  return [ 'ipb_expiry_old' ];
753  }
754 
755  if ( !isset( $data['DisableEmail'] ) ) {
756  $data['DisableEmail'] = false;
757  }
758 
759  # If the user has done the form 'properly', they won't even have been given the
760  # option to suppress-block unless they have the 'hideuser' permission
761  if ( !isset( $data['HideUser'] ) ) {
762  $data['HideUser'] = false;
763  }
764 
765  if ( $data['HideUser'] ) {
766  if ( !$performer->isAllowed( 'hideuser' ) ) {
767  # this codepath is unreachable except by a malicious user spoofing forms,
768  # or by race conditions (user has hideuser and block rights, loads block form,
769  # and loses hideuser rights before submission); so need to fail completely
770  # rather than just silently disable hiding
771  return [ 'badaccess-group0' ];
772  }
773 
774  # Recheck params here...
775  if ( $type != Block::TYPE_USER ) {
776  $data['HideUser'] = false; # IP users should not be hidden
777  } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
778  # Bad expiry.
779  return [ 'ipb_expiry_temp' ];
780  } elseif ( $wgHideUserContribLimit !== false
781  && $user->getEditCount() > $wgHideUserContribLimit
782  ) {
783  # Typically, the user should have a handful of edits.
784  # Disallow hiding users with many edits for performance.
785  return [ [ 'ipb_hide_invalid',
786  Message::numParam( $wgHideUserContribLimit ) ] ];
787  } elseif ( !$data['Confirm'] ) {
788  return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
789  }
790  }
791 
792  # Create block object.
793  $block = new Block();
794  $block->setTarget( $target );
795  $block->setBlocker( $performer );
796  $block->mReason = $data['Reason'][0];
797  $block->mExpiry = $expiryTime;
798  $block->prevents( 'createaccount', $data['CreateAccount'] );
799  $block->prevents( 'editownusertalk', ( !$wgBlockAllowsUTEdit || $data['DisableUTEdit'] ) );
800  $block->prevents( 'sendemail', $data['DisableEmail'] );
801  $block->isHardblock( $data['HardBlock'] );
802  $block->isAutoblocking( $data['AutoBlock'] );
803  $block->mHideName = $data['HideUser'];
804 
805  if (
806  $enablePartialBlocks &&
807  isset( $data['EditingRestriction'] ) &&
808  $data['EditingRestriction'] === 'partial'
809  ) {
810  $block->isSitewide( false );
811  }
812 
813  $reason = [ 'hookaborted' ];
814  if ( !Hooks::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
815  return $reason;
816  }
817 
818  $restrictions = [];
819  if ( $enablePartialBlocks ) {
820  if ( !empty( $data['PageRestrictions'] ) ) {
821  $restrictions = array_map( function ( $text ) {
822  $title = Title::newFromText( $text );
823  // Use the link cache since the title has already been loaded when
824  // the field was validated.
825  $restriction = new PageRestriction( 0, $title->getArticleId() );
826  $restriction->setTitle( $title );
827  return $restriction;
828  }, explode( "\n", $data['PageRestrictions'] ) );
829  }
830 
831  $block->setRestrictions( $restrictions );
832  }
833 
834  $priorBlock = null;
835  # Try to insert block. Is there a conflicting block?
836  $status = $block->insert();
837  if ( !$status ) {
838  # Indicates whether the user is confirming the block and is aware of
839  # the conflict (did not change the block target in the meantime)
840  $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
841  && $data['PreviousTarget'] !== $target );
842 
843  # Special case for API - T34434
844  $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
845 
846  # Show form unless the user is already aware of this...
847  if ( $blockNotConfirmed || $reblockNotAllowed ) {
848  return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
849  # Otherwise, try to update the block...
850  } else {
851  # This returns direct blocks before autoblocks/rangeblocks, since we should
852  # be sure the user is blocked by now it should work for our purposes
853  $currentBlock = Block::newFromTarget( $target );
854  if ( $block->equals( $currentBlock ) ) {
855  return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
856  }
857  # If the name was hidden and the blocking user cannot hide
858  # names, then don't allow any block changes...
859  if ( $currentBlock->mHideName && !$performer->isAllowed( 'hideuser' ) ) {
860  return [ 'cant-see-hidden-user' ];
861  }
862 
863  $priorBlock = clone $currentBlock;
864  $currentBlock->isHardblock( $block->isHardblock() );
865  $currentBlock->prevents( 'createaccount', $block->prevents( 'createaccount' ) );
866  $currentBlock->mExpiry = $block->mExpiry;
867  $currentBlock->isAutoblocking( $block->isAutoblocking() );
868  $currentBlock->mHideName = $block->mHideName;
869  $currentBlock->prevents( 'sendemail', $block->prevents( 'sendemail' ) );
870  $currentBlock->prevents( 'editownusertalk', $block->prevents( 'editownusertalk' ) );
871  $currentBlock->mReason = $block->mReason;
872 
873  if ( $enablePartialBlocks ) {
874  // Maintain the sitewide status. If partial blocks is not enabled,
875  // saving the block will result in a sitewide block.
876  $currentBlock->isSitewide( $block->isSitewide() );
877 
878  // Set the block id of the restrictions.
879  $currentBlock->setRestrictions(
880  BlockRestriction::setBlockId( $currentBlock->getId(), $restrictions )
881  );
882  }
883 
884  $status = $currentBlock->update();
885 
886  $logaction = 'reblock';
887 
888  # Unset _deleted fields if requested
889  if ( $currentBlock->mHideName && !$data['HideUser'] ) {
891  }
892 
893  # If hiding/unhiding a name, this should go in the private logs
894  if ( (bool)$currentBlock->mHideName ) {
895  $data['HideUser'] = true;
896  }
897  }
898  } else {
899  $logaction = 'block';
900  }
901 
902  Hooks::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
903 
904  # Set *_deleted fields if requested
905  if ( $data['HideUser'] ) {
907  }
908 
909  # Can't watch a rangeblock
910  if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
913  $performer,
915  );
916  }
917 
918  # Block constructor sanitizes certain block options on insert
919  $data['BlockEmail'] = $block->prevents( 'sendemail' );
920  $data['AutoBlock'] = $block->isAutoblocking();
921 
922  # Prepare log parameters
923  $logParams = [];
924  $logParams['5::duration'] = $data['Expiry'];
925  $logParams['6::flags'] = self::blockLogFlags( $data, $type );
926  $logParams['sitewide'] = $block->isSitewide();
927 
928  if ( $enablePartialBlocks && !empty( $data['PageRestrictions'] ) ) {
929  $logParams['7::restrictions'] = [
930  'pages' => explode( "\n", $data['PageRestrictions'] ),
931  ];
932  }
933 
934  # Make log entry, if the name is hidden, put it in the suppression log
935  $log_type = $data['HideUser'] ? 'suppress' : 'block';
936  $logEntry = new ManualLogEntry( $log_type, $logaction );
937  $logEntry->setTarget( Title::makeTitle( NS_USER, $target ) );
938  $logEntry->setComment( $data['Reason'][0] );
939  $logEntry->setPerformer( $performer );
940  $logEntry->setParameters( $logParams );
941  # Relate log ID to block IDs (T27763)
942  $blockIds = array_merge( [ $status['id'] ], $status['autoIds'] );
943  $logEntry->setRelations( [ 'ipb_id' => $blockIds ] );
944  $logId = $logEntry->insert();
945 
946  if ( !empty( $data['Tags'] ) ) {
947  $logEntry->setTags( $data['Tags'] );
948  }
949 
950  $logEntry->publish( $logId );
951 
952  return true;
953  }
954 
965  public static function getSuggestedDurations( Language $lang = null, $includeOther = true ) {
966  $a = [];
967  $msg = $lang === null
968  ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
969  : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
970 
971  if ( $msg == '-' ) {
972  return [];
973  }
974 
975  foreach ( explode( ',', $msg ) as $option ) {
976  if ( strpos( $option, ':' ) === false ) {
977  $option = "$option:$option";
978  }
979 
980  list( $show, $value ) = explode( ':', $option );
981  $a[$show] = $value;
982  }
983 
984  if ( $a && $includeOther ) {
985  // if options exist, add other to the end instead of the begining (which
986  // is what happens by default).
987  $a[ wfMessage( 'ipbother' )->text() ] = 'other';
988  }
989 
990  return $a;
991  }
992 
1004  public static function parseExpiryInput( $expiry ) {
1005  if ( wfIsInfinity( $expiry ) ) {
1006  return 'infinity';
1007  }
1008 
1009  $expiry = strtotime( $expiry );
1010 
1011  if ( $expiry < 0 || $expiry === false ) {
1012  return false;
1013  }
1014 
1015  return wfTimestamp( TS_MW, $expiry );
1016  }
1017 
1023  public static function canBlockEmail( $user ) {
1025 
1026  return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1027  }
1028 
1041  public static function checkUnblockSelf( $user, User $performer ) {
1042  if ( is_int( $user ) ) {
1044  } elseif ( is_string( $user ) ) {
1046  }
1047  if ( $performer->isBlocked() ) {
1048  if ( $user instanceof User && $user->getId() == $performer->getId() ) {
1049  # User is trying to unblock themselves
1050  if ( $performer->isAllowed( 'unblockself' ) ) {
1051  return true;
1052  # User blocked themselves and is now trying to reverse it
1053  } elseif ( $performer->blockedBy() === $performer->getName() ) {
1054  return true;
1055  } else {
1056  return 'ipbnounblockself';
1057  }
1058  } elseif (
1059  $user instanceof User &&
1060  $performer->getBlock() instanceof Block &&
1061  $performer->getBlock()->getBy() &&
1062  $performer->getBlock()->getBy() === $user->getId()
1063  ) {
1064  // Allow users to block the user that blocked them.
1065  // This is to prevent a situation where a malicious user
1066  // blocks all other users. This way, the non-malicious
1067  // user can block the malicious user back, resulting
1068  // in a stalemate.
1069  return true;
1070 
1071  } else {
1072  # User is trying to block/unblock someone else
1073  return 'ipbblocked';
1074  }
1075  } else {
1076  return true;
1077  }
1078  }
1079 
1087  protected static function blockLogFlags( array $data, $type ) {
1088  $config = RequestContext::getMain()->getConfig();
1089 
1090  $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1091 
1092  $flags = [];
1093 
1094  # when blocking a user the option 'anononly' is not available/has no effect
1095  # -> do not write this into log
1096  if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
1097  // For grepping: message block-log-flags-anononly
1098  $flags[] = 'anononly';
1099  }
1100 
1101  if ( $data['CreateAccount'] ) {
1102  // For grepping: message block-log-flags-nocreate
1103  $flags[] = 'nocreate';
1104  }
1105 
1106  # Same as anononly, this is not displayed when blocking an IP address
1107  if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
1108  // For grepping: message block-log-flags-noautoblock
1109  $flags[] = 'noautoblock';
1110  }
1111 
1112  if ( $data['DisableEmail'] ) {
1113  // For grepping: message block-log-flags-noemail
1114  $flags[] = 'noemail';
1115  }
1116 
1117  if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1118  // For grepping: message block-log-flags-nousertalk
1119  $flags[] = 'nousertalk';
1120  }
1121 
1122  if ( $data['HideUser'] ) {
1123  // For grepping: message block-log-flags-hiddenname
1124  $flags[] = 'hiddenname';
1125  }
1126 
1127  return implode( ',', $flags );
1128  }
1129 
1136  public function onSubmit( array $data, HTMLForm $form = null ) {
1137  return self::processForm( $data, $form->getContext() );
1138  }
1139 
1144  public function onSuccess() {
1145  $out = $this->getOutput();
1146  $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1147  $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
1148  }
1149 
1158  public function prefixSearchSubpages( $search, $limit, $offset ) {
1159  $user = User::newFromName( $search );
1160  if ( !$user ) {
1161  // No prefix suggestion for invalid user
1162  return [];
1163  }
1164  // Autocomplete subpage as user list - public to allow caching
1165  return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
1166  }
1167 
1168  protected function getGroupName() {
1169  return 'users';
1170  }
1171 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
static getSuggestedDurations(Language $lang=null, $includeOther=true)
Get an array of suggested block durations from MediaWiki:Ipboptions.
A special page that allows users with &#39;block&#39; right to block users from editing pages and other actio...
static isIPAddress( $ip)
Determine if a string is as valid IP address or network (CIDR prefix).
Definition: IP.php:77
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
static processForm(array $data, IContextSource $context)
Given the form data, actually implement a block.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
static validateTarget( $value, User $user)
Validate a block target.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:785
static validateTargetField( $value, $alldata, $form)
HTMLForm field validation-callback for Target field.
const TYPE_RANGE
Definition: Block.php:93
setTitle(\Title $title)
Set the title.
static canBlockEmail( $user)
Can we do an email block?
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
$wgSysopEmailBans
Allow sysops to ban users from accessing Emailuser.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(!isset( $args[0])) $lang
static newFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target&#39;s type, get an existing Block object if possible.
Definition: Block.php:1264
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1277
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
requiresUnblock()
We allow certain special cases where user is blocked.
blockedBy()
If user is blocked, return the name of the user who placed the block.
Definition: User.php:2329
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
$value
wfIsInfinity( $str)
Determine input string is represents as infinity.
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
bool $requestedHideUser
Whether the previous submission of the form asked for HideUser.
const TYPE_IP
Definition: Block.php:92
static getTargetUserTitle( $target)
Get a user page target for things like logs.
isBlocked( $bFromReplica=true)
Check if user is blocked.
Definition: User.php:2272
getOutput()
Get the OutputPage being used for this instance.
const COMMENT_CHARACTER_LIMIT
Maximum length of a comment in UTF-8 characters.
preText()
Add header elements like block log entries, etc.
static numParam( $num)
Definition: Message.php:1050
Special page which uses an HTMLForm to handle processing.
static parseTarget( $target)
From an existing Block, get the target and the type of target.
Definition: Block.php:1486
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2468
static search( $audience, $search, $limit, $offset=0)
Do a prefix search of user names and return a list of matching user names.
This document provides an overview of the usage of PageUpdater and that is
Definition: pageupdater.txt:3
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3043
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:47
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$wgBlockCIDRLimit
Limits on the possible sizes of range blocks.
getConfig()
Get the site configuration.
setSubmitDestructive()
Identify that the submit button in the form has a destructive action.
Definition: HTMLForm.php:1345
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead 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 set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
static getMain()
Get the RequestContext object associated with the main request.
int $type
Block::TYPE_ constant.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging a wrapping ErrorException block
Definition: hooks.txt:2173
onSuccess()
Do something exciting on successful processing of the form, most likely to show a confirmation messag...
An error page which can definitely be safely rendered using the OutputPage.
isAnon()
Get whether the user is anonymous.
Definition: User.php:3813
static unsuppressUserName( $name, $userId, $dbw=null)
const MIGRATION_OLD
Definition: Defines.php:315
static getTargetAndType( $par, WebRequest $request=null)
Determine the target of the block, and the type of target.
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
postText()
Add footer elements to the form.
$wgHideUserContribLimit
The maximum number of edits a user can have and can still be hidden by users with the hideuser permis...
setHeaderText( $msg, $section=null)
Set header text, inside the form.
Definition: HTMLForm.php:797
formatErrors( $errors)
Format a stack of error messages into a single HTML string.
Definition: HTMLForm.php:1310
static checkUnblockSelf( $user, User $performer)
T17810: blocked admins should not be able to block/unblock others, and probably shouldn&#39;t be able to ...
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
setParameter( $par)
Handle some magic here.
const IGNORE_USER_RIGHTS
Definition: User.php:77
static doWatch(Title $title, User $user, $checkRights=User::CHECK_USER_RIGHTS)
Watch a page.
getSkin()
Shortcut to get the skin being used for this instance.
isAllowed( $action='')
Internal mechanics of testing a permission.
Definition: User.php:3868
and(b) You must cause any modified files to carry prominent notices stating that You changed the files
bool $alreadyBlocked
isSitewide( $x=null)
Indicates that the block is a sitewide block.
Definition: Block.php:1138
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:936
$wgEnableUserEmail
Set to true to enable user-to-user e-mail.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:82
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
User string $previousTarget
The previous block target.
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:573
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:545
getTitle( $subpage=false)
Get a self-referential title object.
$expiryTime
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static isIPv6( $ip)
Given a string, determine if it as valid IP in IPv6 only.
Definition: IP.php:88
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:608
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
Definition: postgres.txt:22
getName()
Get the name of this Special Page.
getFormFields()
Get the HTMLForm descriptor array for the block form.
getBlock( $bFromReplica=true)
Get the block affecting the user, or null if the user is not blocked.
Definition: User.php:2282
getId()
Get the user&#39;s ID.
Definition: User.php:2443
static blockLogFlags(array $data, $type)
Return a comma-delimited list of "flags" to be passed to the log reader for this block, to provide more information in the logs.
getUser()
Shortcut to get the User executing this instance.
string $par
The sub-page of the special page.
checkExecutePermissions(User $user)
Checks that the user can unblock themselves if they are trying to do so.
getConfig()
Shortcut to get main config object.
getUserPage()
Get this user&#39;s personal page title.
Definition: User.php:4561
alterForm(HTMLForm $form)
Customizes the HTMLForm a bit.
static isIPv4( $ip)
Given a string, determine if it as valid IP in IPv4 only.
Definition: IP.php:99
static parseExpiryInput( $expiry)
Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute ("24 May 2034"...
getLanguage()
Shortcut to get user&#39;s language.
msg( $key)
Wrapper around wfMessage that sets the current context.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2626
const TYPE_USER
Definition: Block.php:91
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1374
User string null $target
User to be blocked, as passed either by parameter (url?wpTarget=Foo) or as subpage (Special:Block/Foo...
array $preErrors
$wgBlockAllowsUTEdit
Set this to true to allow blocked users to edit their own user talk page.
onSubmit(array $data, HTMLForm $form=null)
Process the form on POST submission.
maybeAlterFormDefaults(&$fields)
If the user has already been blocked with similar settings, load that block and change the defaults f...
static suppressUserName( $name, $userId, $dbw=null)
getRequest()
Get the WebRequest being used for this instance.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:585
=Architecture==Two class hierarchies are used to provide the functionality associated with the different content models:*Content interface(and AbstractContent base class) define functionality that acts on the concrete content of a page, and *ContentHandler base class provides functionality specific to a content model, but not acting on concrete content. The most important function of ContentHandler is to act as a factory for the appropriate implementation of Content. These Content objects are to be used by MediaWiki everywhere, instead of passing page content around as text. All manipulation and analysis of page content must be done via the appropriate methods of the Content object. For each content model, a subclass of ContentHandler has to be registered with $wgContentHandlers. The ContentHandler object for a given content model can be obtained using ContentHandler::getForModelID($id). Also Title, WikiPage and Revision now have getContentHandler() methods for convenience. ContentHandler objects are singletons that provide functionality specific to the content type, but not directly acting on the content of some page. ContentHandler::makeEmptyContent() and ContentHandler::unserializeContent() can be used to create a Content object of the appropriate type. However, it is recommended to instead use WikiPage::getContent() resp. Revision::getContent() to get a page 's content as a Content object. These two methods should be the ONLY way in which page content is accessed. Another important function of ContentHandler objects is to define custom action handlers for a content model, see ContentHandler::getActionOverrides(). This is similar to what WikiPage::getActionOverrides() was already doing.==Serialization==With the ContentHandler facility, page content no longer has to be text based. Objects implementing the Content interface are used to represent and handle the content internally. For storage and data exchange, each content model supports at least one serialization format via ContentHandler::serializeContent($content). The list of supported formats for a given content model can be accessed using ContentHandler::getSupportedFormats(). Content serialization formats are identified using MIME type like strings. The following formats are built in:*text/x-wiki - wikitext *text/javascript - for js pages *text/css - for css pages *text/plain - for future use, e.g. with plain text messages. *text/html - for future use, e.g. with plain html messages. *application/vnd.php.serialized - for future use with the api and for extensions *application/json - for future use with the api, and for use by extensions *application/xml - for future use with the api, and for use by extensions In PHP, use the corresponding CONTENT_FORMAT_XXX constant. Note that when using the API to access page content, especially action=edit, action=parse and action=query &prop=revisions, the model and format of the content should always be handled explicitly. Without that information, interpretation of the provided content is not reliable. The same applies to XML dumps generated via maintenance/dumpBackup.php or Special:Export. Also note that the API will provide encapsulated, serialized content - so if the API was called with format=json, and contentformat is also json(or rather, application/json), the page content is represented as a string containing an escaped json structure. Extensions that use JSON to serialize some types of page content may provide specialized API modules that allow access to that content in a more natural form.==Compatibility==The ContentHandler facility is introduced in a way that should allow all existing code to keep functioning at least for pages that contain wikitext or other text based content. However, a number of functions and hooks have been deprecated in favor of new versions that are aware of the page 's content model, and will now generate warnings when used. Most importantly, the following functions have been deprecated:*Revisions::getText() is deprecated in favor Revisions::getContent() *WikiPage::getText() is deprecated in favor WikiPage::getContent() Also, the old Article::getContent()(which returns text) is superceded by Article::getContentObject(). However, both methods should be avoided since they do not provide clean access to the page 's actual content. For instance, they may return a system message for non-existing pages. Use WikiPage::getContent() instead. Code that relies on a textual representation of the page content should eventually be rewritten. However, ContentHandler::getContentText() provides a stop-gap that can be used to get text for a page. Its behavior is controlled by $wgContentHandlerTextFallback it
addHeaderText( $msg, $section=null)
Add HTML to the header, inside the form.
Definition: HTMLForm.php:775
Definition: Block.php:29
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2626
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1487
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
MediaWiki Linker LinkRenderer null $linkRenderer
Definition: SpecialPage.php:66
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:280