MediaWiki  master
SpecialBlock.php
Go to the documentation of this file.
1 <?php
27 
37  protected $target;
38 
40  protected $type;
41 
43  protected $previousTarget;
44 
46  protected $requestedHideUser;
47 
49  protected $alreadyBlocked;
50 
52  protected $preErrors = [];
53 
54  public function __construct() {
55  parent::__construct( 'Block', 'block' );
56  }
57 
58  public function doesWrites() {
59  return true;
60  }
61 
68  protected function checkExecutePermissions( User $user ) {
69  parent::checkExecutePermissions( $user );
70  # T17810: blocked admins should have limited access here
71  $status = self::checkUnblockSelf( $this->target, $user );
72  if ( $status !== true ) {
73  throw new ErrorPageError( 'badaccess', $status );
74  }
75  }
76 
82  public function requiresUnblock() {
83  return false;
84  }
85 
91  protected function setParameter( $par ) {
92  # Extract variables from the request. Try not to get into a situation where we
93  # need to extract *every* variable from the form just for processing here, but
94  # there are legitimate uses for some variables
95  $request = $this->getRequest();
96  list( $this->target, $this->type ) = self::getTargetAndType( $par, $request );
97  if ( $this->target instanceof User ) {
98  # Set the 'relevant user' in the skin, so it displays links like Contributions,
99  # User logs, UserRights, etc.
100  $this->getSkin()->setRelevantUser( $this->target );
101  }
102 
103  list( $this->previousTarget, /*...*/ ) =
104  Block::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
105  $this->requestedHideUser = $request->getBool( 'wpHideUser' );
106  }
107 
113  protected function alterForm( HTMLForm $form ) {
114  $form->setHeaderText( '' );
115  $form->setSubmitDestructive();
116 
117  $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
118  $form->setSubmitTextMsg( $msg );
119 
120  $this->addHelpLink( 'Help:Blocking users' );
121 
122  # Don't need to do anything if the form has been posted
123  if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
124  $s = $form->formatErrors( $this->preErrors );
125  if ( $s ) {
127  'div',
128  [ 'class' => 'error' ],
129  $s
130  ) );
131  }
132  }
133  }
134 
135  protected function getDisplayFormat() {
136  return 'ooui';
137  }
138 
143  protected function getFormFields() {
144  $conf = $this->getConfig();
145  $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
146  $blockAllowsUTEdit = $conf->get( 'BlockAllowsUTEdit' );
147 
148  $this->getOutput()->enableOOUI();
149 
150  $user = $this->getUser();
151 
152  $suggestedDurations = self::getSuggestedDurations();
153 
154  $a = [];
155 
156  $a['Target'] = [
157  'type' => 'user',
158  'ipallowed' => true,
159  'iprange' => true,
160  'id' => 'mw-bi-target',
161  'size' => '45',
162  'autofocus' => true,
163  'required' => true,
164  'validation-callback' => [ __CLASS__, 'validateTargetField' ],
165  'section' => 'target',
166  ];
167 
168  $a['Editing'] = [
169  'type' => 'check',
170  'label-message' => 'block-prevent-edit',
171  'default' => true,
172  'section' => 'actions',
173  'disabled' => $enablePartialBlocks ? false : true,
174  ];
175 
176  if ( $enablePartialBlocks ) {
177  $a['EditingRestriction'] = [
178  'type' => 'radio',
179  'cssclass' => 'mw-block-editing-restriction',
180  'options' => [
181  $this->msg( 'ipb-sitewide' )->escaped() .
182  new \OOUI\LabelWidget( [
183  'classes' => [ 'oo-ui-inline-help' ],
184  'label' => $this->msg( 'ipb-sitewide-help' )->text(),
185  ] ) => 'sitewide',
186  $this->msg( 'ipb-partial' )->escaped() .
187  new \OOUI\LabelWidget( [
188  'classes' => [ 'oo-ui-inline-help' ],
189  'label' => $this->msg( 'ipb-partial-help' )->text(),
190  ] ) => 'partial',
191  ],
192  'section' => 'actions',
193  ];
194  $a['PageRestrictions'] = [
195  'type' => 'titlesmultiselect',
196  'label' => $this->msg( 'ipb-pages-label' )->text(),
197  'exists' => true,
198  'max' => 10,
199  'cssclass' => 'mw-block-restriction',
200  'showMissing' => false,
201  'excludeDynamicNamespaces' => true,
202  'input' => [
203  'autocomplete' => false
204  ],
205  'section' => 'actions',
206  ];
207  $a['NamespaceRestrictions'] = [
208  'type' => 'namespacesmultiselect',
209  'label' => $this->msg( 'ipb-namespaces-label' )->text(),
210  'exists' => true,
211  'cssclass' => 'mw-block-restriction',
212  'input' => [
213  'autocomplete' => false
214  ],
215  'section' => 'actions',
216  ];
217  }
218 
219  $a['CreateAccount'] = [
220  'type' => 'check',
221  'label-message' => 'ipbcreateaccount',
222  'default' => true,
223  'section' => 'actions',
224  ];
225 
226  if ( self::canBlockEmail( $user ) ) {
227  $a['DisableEmail'] = [
228  'type' => 'check',
229  'label-message' => 'ipbemailban',
230  'section' => 'actions',
231  ];
232  }
233 
234  if ( $blockAllowsUTEdit ) {
235  $a['DisableUTEdit'] = [
236  'type' => 'check',
237  'label-message' => 'ipb-disableusertalk',
238  'default' => false,
239  'section' => 'actions',
240  ];
241  }
242 
243  $a['Expiry'] = [
244  'type' => 'expiry',
245  'required' => true,
246  'options' => $suggestedDurations,
247  'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
248  'section' => 'expiry',
249  ];
250 
251  $a['Reason'] = [
252  'type' => 'selectandother',
253  // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
254  // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
255  // Unicode codepoints.
257  'maxlength-unit' => 'codepoints',
258  'options-message' => 'ipbreason-dropdown',
259  'section' => 'reason',
260  ];
261 
262  $a['AutoBlock'] = [
263  'type' => 'check',
264  'label-message' => 'ipbenableautoblock',
265  'default' => true,
266  'section' => 'options',
267  ];
268 
269  # Allow some users to hide name from block log, blocklist and listusers
270  if ( $user->isAllowed( 'hideuser' ) ) {
271  $a['HideUser'] = [
272  'type' => 'check',
273  'label-message' => 'ipbhidename',
274  'cssclass' => 'mw-block-hideuser',
275  'section' => 'options',
276  ];
277  }
278 
279  # Watchlist their user page? (Only if user is logged in)
280  if ( $user->isLoggedIn() ) {
281  $a['Watch'] = [
282  'type' => 'check',
283  'label-message' => 'ipbwatchuser',
284  'section' => 'options',
285  ];
286  }
287 
288  $a['HardBlock'] = [
289  'type' => 'check',
290  'label-message' => 'ipb-hardblock',
291  'default' => false,
292  'section' => 'options',
293  ];
294 
295  # This is basically a copy of the Target field, but the user can't change it, so we
296  # can see if the warnings we maybe showed to the user before still apply
297  $a['PreviousTarget'] = [
298  'type' => 'hidden',
299  'default' => false,
300  ];
301 
302  # We'll turn this into a checkbox if we need to
303  $a['Confirm'] = [
304  'type' => 'hidden',
305  'default' => '',
306  'label-message' => 'ipb-confirm',
307  'cssclass' => 'mw-block-confirm',
308  ];
309 
310  $this->maybeAlterFormDefaults( $a );
311 
312  // Allow extensions to add more fields
313  Hooks::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
314 
315  return $a;
316  }
317 
323  protected function maybeAlterFormDefaults( &$fields ) {
324  # This will be overwritten by request data
325  $fields['Target']['default'] = (string)$this->target;
326 
327  if ( $this->target ) {
328  $status = self::validateTarget( $this->target, $this->getUser() );
329  if ( !$status->isOK() ) {
330  $errors = $status->getErrorsArray();
331  $this->preErrors = array_merge( $this->preErrors, $errors );
332  }
333  }
334 
335  # This won't be
336  $fields['PreviousTarget']['default'] = (string)$this->target;
337 
338  $block = Block::newFromTarget( $this->target );
339 
340  // Populate fields if there is a block that is not an autoblock; if it is a range
341  // block, only populate the fields if the range is the same as $this->target
342  if ( $block instanceof Block && $block->getType() !== Block::TYPE_AUTO
343  && ( $this->type != Block::TYPE_RANGE
344  || $block->getTarget() == $this->target )
345  ) {
346  $fields['HardBlock']['default'] = $block->isHardblock();
347  $fields['CreateAccount']['default'] = $block->isCreateAccountBlocked();
348  $fields['AutoBlock']['default'] = $block->isAutoblocking();
349 
350  if ( isset( $fields['DisableEmail'] ) ) {
351  $fields['DisableEmail']['default'] = $block->isEmailBlocked();
352  }
353 
354  if ( isset( $fields['HideUser'] ) ) {
355  $fields['HideUser']['default'] = $block->getHideName();
356  }
357 
358  if ( isset( $fields['DisableUTEdit'] ) ) {
359  $fields['DisableUTEdit']['default'] = !$block->isUsertalkEditAllowed();
360  }
361 
362  // If the username was hidden (ipb_deleted == 1), don't show the reason
363  // unless this user also has rights to hideuser: T37839
364  if ( !$block->getHideName() || $this->getUser()->isAllowed( 'hideuser' ) ) {
365  $fields['Reason']['default'] = $block->getReason();
366  } else {
367  $fields['Reason']['default'] = '';
368  }
369 
370  if ( $this->getRequest()->wasPosted() ) {
371  # Ok, so we got a POST submission asking us to reblock a user. So show the
372  # confirm checkbox; the user will only see it if they haven't previously
373  $fields['Confirm']['type'] = 'check';
374  } else {
375  # We got a target, but it wasn't a POST request, so the user must have gone
376  # to a link like [[Special:Block/User]]. We don't need to show the checkbox
377  # as long as they go ahead and block *that* user
378  $fields['Confirm']['default'] = 1;
379  }
380 
381  if ( $block->getExpiry() == 'infinity' ) {
382  $fields['Expiry']['default'] = 'infinite';
383  } else {
384  $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->getExpiry() );
385  }
386 
387  $this->alreadyBlocked = true;
388  $this->preErrors[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
389  }
390 
391  if ( $this->alreadyBlocked || $this->getRequest()->wasPosted()
392  || $this->getRequest()->getCheck( 'wpCreateAccount' )
393  ) {
394  $this->getOutput()->addJsConfigVars( 'wgCreateAccountDirty', true );
395  }
396 
397  # We always need confirmation to do HideUser
398  if ( $this->requestedHideUser ) {
399  $fields['Confirm']['type'] = 'check';
400  unset( $fields['Confirm']['default'] );
401  $this->preErrors[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
402  }
403 
404  # Or if the user is trying to block themselves
405  if ( (string)$this->target === $this->getUser()->getName() ) {
406  $fields['Confirm']['type'] = 'check';
407  unset( $fields['Confirm']['default'] );
408  $this->preErrors[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
409  }
410 
411  if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
412  if ( $block instanceof Block && !$block->isSitewide() ) {
413  $fields['EditingRestriction']['default'] = 'partial';
414  } else {
415  $fields['EditingRestriction']['default'] = 'sitewide';
416  }
417 
418  if ( $block instanceof Block ) {
419  $pageRestrictions = [];
420  $namespaceRestrictions = [];
421  foreach ( $block->getRestrictions() as $restriction ) {
422  switch ( $restriction->getType() ) {
423  case PageRestriction::TYPE:
424  if ( $restriction->getTitle() ) {
425  $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
426  }
427  break;
428  case NamespaceRestriction::TYPE:
429  $namespaceRestrictions[] = $restriction->getValue();
430  break;
431  }
432  }
433 
434  if (
435  !$block->isSitewide() &&
436  empty( $pageRestrictions ) &&
437  empty( $namespaceRestrictions )
438  ) {
439  $fields['Editing']['default'] = false;
440  }
441 
442  // Sort the restrictions so they are in alphabetical order.
443  sort( $pageRestrictions );
444  $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
445  sort( $namespaceRestrictions );
446  $fields['NamespaceRestrictions']['default'] = implode( "\n", $namespaceRestrictions );
447  }
448  }
449  }
450 
455  protected function preText() {
456  $this->getOutput()->addModuleStyles( [
457  'mediawiki.widgets.TagMultiselectWidget.styles',
458  'mediawiki.special',
459  ] );
460  $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
461 
462  $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
463  $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
464 
465  $otherBlockMessages = [];
466  if ( $this->target !== null ) {
467  $targetName = $this->target;
468  if ( $this->target instanceof User ) {
469  $targetName = $this->target->getName();
470  }
471  # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
472  Hooks::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
473 
474  if ( count( $otherBlockMessages ) ) {
476  'h2',
477  [],
478  $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
479  ) . "\n";
480 
481  $list = '';
482 
483  foreach ( $otherBlockMessages as $link ) {
484  $list .= Html::rawElement( 'li', [], $link ) . "\n";
485  }
486 
487  $s .= Html::rawElement(
488  'ul',
489  [ 'class' => 'mw-blockip-alreadyblocked' ],
490  $list
491  ) . "\n";
492 
493  $text .= $s;
494  }
495  }
496 
497  return $text;
498  }
499 
504  protected function postText() {
505  $links = [];
506 
507  $this->getOutput()->addModuleStyles( 'mediawiki.special' );
508 
509  $linkRenderer = $this->getLinkRenderer();
510  # Link to the user's contributions, if applicable
511  if ( $this->target instanceof User ) {
512  $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
513  $links[] = $linkRenderer->makeLink(
514  $contribsPage,
515  $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->text()
516  );
517  }
518 
519  # Link to unblock the specified user, or to a blank unblock form
520  if ( $this->target instanceof User ) {
521  $message = $this->msg(
522  'ipb-unblock-addr',
523  wfEscapeWikiText( $this->target->getName() )
524  )->parse();
525  $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
526  } else {
527  $message = $this->msg( 'ipb-unblock' )->parse();
528  $list = SpecialPage::getTitleFor( 'Unblock' );
529  }
530  $links[] = $linkRenderer->makeKnownLink(
531  $list,
532  new HtmlArmor( $message )
533  );
534 
535  # Link to the block list
536  $links[] = $linkRenderer->makeKnownLink(
537  SpecialPage::getTitleFor( 'BlockList' ),
538  $this->msg( 'ipb-blocklist' )->text()
539  );
540 
541  $user = $this->getUser();
542 
543  # Link to edit the block dropdown reasons, if applicable
544  if ( $user->isAllowed( 'editinterface' ) ) {
545  $links[] = $linkRenderer->makeKnownLink(
546  $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
547  $this->msg( 'ipb-edit-dropdown' )->text(),
548  [],
549  [ 'action' => 'edit' ]
550  );
551  }
552 
553  $text = Html::rawElement(
554  'p',
555  [ 'class' => 'mw-ipb-conveniencelinks' ],
556  $this->getLanguage()->pipeList( $links )
557  );
558 
559  $userTitle = self::getTargetUserTitle( $this->target );
560  if ( $userTitle ) {
561  # Get relevant extracts from the block and suppression logs, if possible
562  $out = '';
563 
565  $out,
566  'block',
567  $userTitle,
568  '',
569  [
570  'lim' => 10,
571  'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
572  'showIfEmpty' => false
573  ]
574  );
575  $text .= $out;
576 
577  # Add suppression block entries if allowed
578  if ( $user->isAllowed( 'suppressionlog' ) ) {
580  $out,
581  'suppress',
582  $userTitle,
583  '',
584  [
585  'lim' => 10,
586  'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
587  'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
588  'showIfEmpty' => false
589  ]
590  );
591 
592  $text .= $out;
593  }
594  }
595 
596  return $text;
597  }
598 
605  protected static function getTargetUserTitle( $target ) {
606  if ( $target instanceof User ) {
607  return $target->getUserPage();
608  } elseif ( IP::isIPAddress( $target ) ) {
610  }
611 
612  return null;
613  }
614 
624  public static function getTargetAndType( $par, WebRequest $request = null ) {
625  $i = 0;
626  $target = null;
627 
628  while ( true ) {
629  switch ( $i++ ) {
630  case 0:
631  # The HTMLForm will check wpTarget first and only if it doesn't get
632  # a value use the default, which will be generated from the options
633  # below; so this has to have a higher precedence here than $par, or
634  # we could end up with different values in $this->target and the HTMLForm!
635  if ( $request instanceof WebRequest ) {
636  $target = $request->getText( 'wpTarget', null );
637  }
638  break;
639  case 1:
640  $target = $par;
641  break;
642  case 2:
643  if ( $request instanceof WebRequest ) {
644  $target = $request->getText( 'ip', null );
645  }
646  break;
647  case 3:
648  # B/C @since 1.18
649  if ( $request instanceof WebRequest ) {
650  $target = $request->getText( 'wpBlockAddress', null );
651  }
652  break;
653  case 4:
654  break 2;
655  }
656 
658 
659  if ( $type !== null ) {
660  return [ $target, $type ];
661  }
662  }
663 
664  return [ null, null ];
665  }
666 
675  public static function validateTargetField( $value, $alldata, $form ) {
676  $status = self::validateTarget( $value, $form->getUser() );
677  if ( !$status->isOK() ) {
678  $errors = $status->getErrorsArray();
679 
680  return $form->msg( ...$errors[0] );
681  } else {
682  return true;
683  }
684  }
685 
694  public static function validateTarget( $value, User $user ) {
695  global $wgBlockCIDRLimit;
696 
698  list( $target, $type ) = self::getTargetAndType( $value );
700 
701  if ( $type == Block::TYPE_USER ) {
702  if ( $target->isAnon() ) {
703  $status->fatal(
704  'nosuchusershort',
706  );
707  }
708 
709  $unblockStatus = self::checkUnblockSelf( $target, $user );
710  if ( $unblockStatus !== true ) {
711  $status->fatal( 'badaccess', $unblockStatus );
712  }
713  } elseif ( $type == Block::TYPE_RANGE ) {
714  list( $ip, $range ) = explode( '/', $target, 2 );
715 
716  if (
717  ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
718  ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
719  ) {
720  // Range block effectively disabled
721  $status->fatal( 'range_block_disabled' );
722  }
723 
724  if (
725  ( IP::isIPv4( $ip ) && $range > 32 ) ||
726  ( IP::isIPv6( $ip ) && $range > 128 )
727  ) {
728  // Dodgy range
729  $status->fatal( 'ip_range_invalid' );
730  }
731 
732  if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
733  $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
734  }
735 
736  if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
737  $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
738  }
739  } elseif ( $type == Block::TYPE_IP ) {
740  # All is well
741  } else {
742  $status->fatal( 'badipaddress' );
743  }
744 
745  return $status;
746  }
747 
755  public static function processForm( array $data, IContextSource $context ) {
757 
758  $performer = $context->getUser();
759  $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
760  $isPartialBlock = $enablePartialBlocks &&
761  isset( $data['EditingRestriction'] ) &&
762  $data['EditingRestriction'] === 'partial';
763 
764  // Handled by field validator callback
765  // self::validateTargetField( $data['Target'] );
766 
767  # This might have been a hidden field or a checkbox, so interesting data
768  # can come from it
769  $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
770 
772  list( $target, $type ) = self::getTargetAndType( $data['Target'] );
773  if ( $type == Block::TYPE_USER ) {
774  $user = $target;
775  $target = $user->getName();
776  $userId = $user->getId();
777 
778  # Give admins a heads-up before they go and block themselves. Much messier
779  # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
780  # permission anyway, although the code does allow for it.
781  # Note: Important to use $target instead of $data['Target']
782  # since both $data['PreviousTarget'] and $target are normalized
783  # but $data['target'] gets overridden by (non-normalized) request variable
784  # from previous request.
785  if ( $target === $performer->getName() &&
786  ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
787  ) {
788  return [ 'ipb-blockingself', 'ipb-confirmaction' ];
789  }
790  } elseif ( $type == Block::TYPE_RANGE ) {
791  $user = null;
792  $userId = 0;
793  } elseif ( $type == Block::TYPE_IP ) {
794  $user = null;
795  $target = $target->getName();
796  $userId = 0;
797  } else {
798  # This should have been caught in the form field validation
799  return [ 'badipaddress' ];
800  }
801 
802  $expiryTime = self::parseExpiryInput( $data['Expiry'] );
803 
804  if (
805  // an expiry time is needed
806  ( strlen( $data['Expiry'] ) == 0 ) ||
807  // can't be a larger string as 50 (it should be a time format in any way)
808  ( strlen( $data['Expiry'] ) > 50 ) ||
809  // check, if the time could be parsed
810  !$expiryTime
811  ) {
812  return [ 'ipb_expiry_invalid' ];
813  }
814 
815  // an expiry time should be in the future, not in the
816  // past (wouldn't make any sense) - bug T123069
817  if ( $expiryTime < wfTimestampNow() ) {
818  return [ 'ipb_expiry_old' ];
819  }
820 
821  if ( !isset( $data['DisableEmail'] ) ) {
822  $data['DisableEmail'] = false;
823  }
824 
825  # If the user has done the form 'properly', they won't even have been given the
826  # option to suppress-block unless they have the 'hideuser' permission
827  if ( !isset( $data['HideUser'] ) ) {
828  $data['HideUser'] = false;
829  }
830 
831  if ( $data['HideUser'] ) {
832  if ( !$performer->isAllowed( 'hideuser' ) ) {
833  # this codepath is unreachable except by a malicious user spoofing forms,
834  # or by race conditions (user has hideuser and block rights, loads block form,
835  # and loses hideuser rights before submission); so need to fail completely
836  # rather than just silently disable hiding
837  return [ 'badaccess-group0' ];
838  }
839 
840  if ( $isPartialBlock ) {
841  return [ 'ipb_hide_partial' ];
842  }
843 
844  # Recheck params here...
845  if ( $type != Block::TYPE_USER ) {
846  $data['HideUser'] = false; # IP users should not be hidden
847  } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
848  # Bad expiry.
849  return [ 'ipb_expiry_temp' ];
850  } elseif ( $wgHideUserContribLimit !== false
851  && $user->getEditCount() > $wgHideUserContribLimit
852  ) {
853  # Typically, the user should have a handful of edits.
854  # Disallow hiding users with many edits for performance.
855  return [ [ 'ipb_hide_invalid',
856  Message::numParam( $wgHideUserContribLimit ) ] ];
857  } elseif ( !$data['Confirm'] ) {
858  return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
859  }
860  }
861 
862  # Create block object.
863  $block = new Block();
864  $block->setTarget( $target );
865  $block->setBlocker( $performer );
866  $block->setReason( $data['Reason'][0] );
867  $block->setExpiry( $expiryTime );
868  $block->isCreateAccountBlocked( $data['CreateAccount'] );
869  $block->isUsertalkEditAllowed( !$wgBlockAllowsUTEdit || !$data['DisableUTEdit'] );
870  $block->isEmailBlocked( $data['DisableEmail'] );
871  $block->isHardblock( $data['HardBlock'] );
872  $block->isAutoblocking( $data['AutoBlock'] );
873  $block->setHideName( $data['HideUser'] );
874 
875  if ( $isPartialBlock ) {
876  $block->isSitewide( false );
877  }
878 
879  $reason = [ 'hookaborted' ];
880  if ( !Hooks::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
881  return $reason;
882  }
883 
884  $pageRestrictions = [];
885  $namespaceRestrictions = [];
886  if ( $enablePartialBlocks ) {
887  if ( $data['PageRestrictions'] !== '' ) {
888  $pageRestrictions = array_map( function ( $text ) {
889  $title = Title::newFromText( $text );
890  // Use the link cache since the title has already been loaded when
891  // the field was validated.
892  $restriction = new PageRestriction( 0, $title->getArticleID() );
893  $restriction->setTitle( $title );
894  return $restriction;
895  }, explode( "\n", $data['PageRestrictions'] ) );
896  }
897  if ( $data['NamespaceRestrictions'] !== '' ) {
898  $namespaceRestrictions = array_map( function ( $id ) {
899  return new NamespaceRestriction( 0, $id );
900  }, explode( "\n", $data['NamespaceRestrictions'] ) );
901  }
902 
903  $restrictions = ( array_merge( $pageRestrictions, $namespaceRestrictions ) );
904  $block->setRestrictions( $restrictions );
905  }
906 
907  $priorBlock = null;
908  # Try to insert block. Is there a conflicting block?
909  $status = $block->insert();
910  if ( !$status ) {
911  # Indicates whether the user is confirming the block and is aware of
912  # the conflict (did not change the block target in the meantime)
913  $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
914  && $data['PreviousTarget'] !== $target );
915 
916  # Special case for API - T34434
917  $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
918 
919  # Show form unless the user is already aware of this...
920  if ( $blockNotConfirmed || $reblockNotAllowed ) {
921  return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
922  # Otherwise, try to update the block...
923  } else {
924  # This returns direct blocks before autoblocks/rangeblocks, since we should
925  # be sure the user is blocked by now it should work for our purposes
926  $currentBlock = Block::newFromTarget( $target );
927  if ( $block->equals( $currentBlock ) ) {
928  return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
929  }
930  # If the name was hidden and the blocking user cannot hide
931  # names, then don't allow any block changes...
932  if ( $currentBlock->getHideName() && !$performer->isAllowed( 'hideuser' ) ) {
933  return [ 'cant-see-hidden-user' ];
934  }
935 
936  $priorBlock = clone $currentBlock;
937  $currentBlock->isHardblock( $block->isHardblock() );
938  $currentBlock->isCreateAccountBlocked( $block->isCreateAccountBlocked() );
939  $currentBlock->setExpiry( $block->getExpiry() );
940  $currentBlock->isAutoblocking( $block->isAutoblocking() );
941  $currentBlock->setHideName( $block->getHideName() );
942  $currentBlock->isEmailBlocked( $block->isEmailBlocked() );
943  $currentBlock->isUsertalkEditAllowed( $block->isUsertalkEditAllowed() );
944  $currentBlock->setReason( $block->getReason() );
945 
946  if ( $enablePartialBlocks ) {
947  // Maintain the sitewide status. If partial blocks is not enabled,
948  // saving the block will result in a sitewide block.
949  $currentBlock->isSitewide( $block->isSitewide() );
950 
951  // Set the block id of the restrictions.
952  $currentBlock->setRestrictions(
953  BlockRestriction::setBlockId( $currentBlock->getId(), $restrictions )
954  );
955  }
956 
957  $status = $currentBlock->update();
958  // TODO handle failure
959 
960  $logaction = 'reblock';
961 
962  # Unset _deleted fields if requested
963  if ( $currentBlock->getHideName() && !$data['HideUser'] ) {
965  }
966 
967  # If hiding/unhiding a name, this should go in the private logs
968  if ( (bool)$currentBlock->getHideName() ) {
969  $data['HideUser'] = true;
970  }
971 
972  $block = $currentBlock;
973  }
974  } else {
975  $logaction = 'block';
976  }
977 
978  Hooks::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
979 
980  # Set *_deleted fields if requested
981  if ( $data['HideUser'] ) {
983  }
984 
985  # Can't watch a rangeblock
986  if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
989  $performer,
991  );
992  }
993 
994  # Block constructor sanitizes certain block options on insert
995  $data['BlockEmail'] = $block->isEmailBlocked();
996  $data['AutoBlock'] = $block->isAutoblocking();
997 
998  # Prepare log parameters
999  $logParams = [];
1000  $logParams['5::duration'] = $data['Expiry'];
1001  $logParams['6::flags'] = self::blockLogFlags( $data, $type );
1002  $logParams['sitewide'] = $block->isSitewide();
1003 
1004  if ( $enablePartialBlocks && !$block->isSitewide() ) {
1005  if ( $data['PageRestrictions'] !== '' ) {
1006  $logParams['7::restrictions']['pages'] = explode( "\n", $data['PageRestrictions'] );
1007  }
1008 
1009  if ( $data['NamespaceRestrictions'] !== '' ) {
1010  $logParams['7::restrictions']['namespaces'] = explode( "\n", $data['NamespaceRestrictions'] );
1011  }
1012  }
1013 
1014  # Make log entry, if the name is hidden, put it in the suppression log
1015  $log_type = $data['HideUser'] ? 'suppress' : 'block';
1016  $logEntry = new ManualLogEntry( $log_type, $logaction );
1017  $logEntry->setTarget( Title::makeTitle( NS_USER, $target ) );
1018  $logEntry->setComment( $data['Reason'][0] );
1019  $logEntry->setPerformer( $performer );
1020  $logEntry->setParameters( $logParams );
1021  # Relate log ID to block ID (T27763)
1022  $logEntry->setRelations( [ 'ipb_id' => $block->getId() ] );
1023  $logId = $logEntry->insert();
1024 
1025  if ( !empty( $data['Tags'] ) ) {
1026  $logEntry->setTags( $data['Tags'] );
1027  }
1028 
1029  $logEntry->publish( $logId );
1030 
1031  return true;
1032  }
1033 
1044  public static function getSuggestedDurations( Language $lang = null, $includeOther = true ) {
1045  $a = [];
1046  $msg = $lang === null
1047  ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
1048  : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
1049 
1050  if ( $msg == '-' ) {
1051  return [];
1052  }
1053 
1054  foreach ( explode( ',', $msg ) as $option ) {
1055  if ( strpos( $option, ':' ) === false ) {
1056  $option = "$option:$option";
1057  }
1058 
1059  list( $show, $value ) = explode( ':', $option );
1060  $a[$show] = $value;
1061  }
1062 
1063  if ( $a && $includeOther ) {
1064  // if options exist, add other to the end instead of the begining (which
1065  // is what happens by default).
1066  $a[ wfMessage( 'ipbother' )->text() ] = 'other';
1067  }
1068 
1069  return $a;
1070  }
1071 
1083  public static function parseExpiryInput( $expiry ) {
1084  if ( wfIsInfinity( $expiry ) ) {
1085  return 'infinity';
1086  }
1087 
1088  $expiry = strtotime( $expiry );
1089 
1090  if ( $expiry < 0 || $expiry === false ) {
1091  return false;
1092  }
1093 
1094  return wfTimestamp( TS_MW, $expiry );
1095  }
1096 
1102  public static function canBlockEmail( $user ) {
1104 
1105  return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1106  }
1107 
1122  public static function checkUnblockSelf( $target, User $performer ) {
1123  if ( is_int( $target ) ) {
1125  } elseif ( is_string( $target ) ) {
1127  }
1128  if ( $performer->isBlocked() ) {
1129  if ( $target instanceof User && $target->getId() == $performer->getId() ) {
1130  # User is trying to unblock themselves
1131  if ( $performer->isAllowed( 'unblockself' ) ) {
1132  return true;
1133  # User blocked themselves and is now trying to reverse it
1134  } elseif ( $performer->blockedBy() === $performer->getName() ) {
1135  return true;
1136  } else {
1137  return 'ipbnounblockself';
1138  }
1139  } elseif (
1140  $target instanceof User &&
1141  $performer->getBlock() instanceof Block &&
1142  $performer->getBlock()->getBy() &&
1143  $performer->getBlock()->getBy() === $target->getId()
1144  ) {
1145  // Allow users to block the user that blocked them.
1146  // This is to prevent a situation where a malicious user
1147  // blocks all other users. This way, the non-malicious
1148  // user can block the malicious user back, resulting
1149  // in a stalemate.
1150  return true;
1151 
1152  } else {
1153  # User is trying to block/unblock someone else
1154  return 'ipbblocked';
1155  }
1156  } else {
1157  return true;
1158  }
1159  }
1160 
1168  protected static function blockLogFlags( array $data, $type ) {
1169  $config = RequestContext::getMain()->getConfig();
1170 
1171  $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1172 
1173  $flags = [];
1174 
1175  # when blocking a user the option 'anononly' is not available/has no effect
1176  # -> do not write this into log
1177  if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
1178  // For grepping: message block-log-flags-anononly
1179  $flags[] = 'anononly';
1180  }
1181 
1182  if ( $data['CreateAccount'] ) {
1183  // For grepping: message block-log-flags-nocreate
1184  $flags[] = 'nocreate';
1185  }
1186 
1187  # Same as anononly, this is not displayed when blocking an IP address
1188  if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
1189  // For grepping: message block-log-flags-noautoblock
1190  $flags[] = 'noautoblock';
1191  }
1192 
1193  if ( $data['DisableEmail'] ) {
1194  // For grepping: message block-log-flags-noemail
1195  $flags[] = 'noemail';
1196  }
1197 
1198  if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1199  // For grepping: message block-log-flags-nousertalk
1200  $flags[] = 'nousertalk';
1201  }
1202 
1203  if ( $data['HideUser'] ) {
1204  // For grepping: message block-log-flags-hiddenname
1205  $flags[] = 'hiddenname';
1206  }
1207 
1208  return implode( ',', $flags );
1209  }
1210 
1217  public function onSubmit( array $data, HTMLForm $form = null ) {
1218  // If "Editing" checkbox is unchecked, the block must be a partial block affecting
1219  // actions other than editing, and there must be no restrictions.
1220  if ( isset( $data['Editing'] ) && $data['Editing'] === false ) {
1221  $data['EditingRestriction'] = 'partial';
1222  $data['PageRestrictions'] = '';
1223  $data['NamespaceRestrictions'] = '';
1224  }
1225  return self::processForm( $data, $form->getContext() );
1226  }
1227 
1232  public function onSuccess() {
1233  $out = $this->getOutput();
1234  $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1235  $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
1236  }
1237 
1246  public function prefixSearchSubpages( $search, $limit, $offset ) {
1247  $user = User::newFromName( $search );
1248  if ( !$user ) {
1249  // No prefix suggestion for invalid user
1250  return [];
1251  }
1252  // Autocomplete subpage as user list - public to allow caching
1253  return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
1254  }
1255 
1256  protected function getGroupName() {
1257  return 'users';
1258  }
1259 }
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 checkUnblockSelf( $target, User $performer)
T17810: blocked admins should not be able to block/unblock others, and probably shouldn&#39;t be able to ...
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.
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
static validateTargetField( $value, $alldata, $form)
HTMLForm field validation-callback for Target field.
const TYPE_RANGE
Definition: Block.php:98
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
getType()
Get the type of target for this particular block.
Definition: Block.php:1676
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:1397
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:2306
getBlock( $fromReplica=true)
Get the block affecting the user, or null if the user is not blocked.
Definition: User.php:2280
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:97
static getTargetUserTitle( $target)
Get a user page target for things like logs.
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:1049
Special page which uses an HTMLForm to handle processing.
isBlocked( $fromReplica=true)
Check if user is blocked.
Definition: User.php:2269
static parseTarget( $target)
From an existing Block, get the target and the type of target.
Definition: Block.php:1619
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:2443
static search( $audience, $search, $limit, $offset=0)
Do a prefix search of user names and return a list of matching user names.
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3050
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:48
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:780
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 '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:1263
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:1369
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.
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:3795
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:809
formatErrors( $errors)
Format a stack of error messages into a single HTML string.
Definition: HTMLForm.php:1334
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
setParameter( $par)
Handle some magic here.
const IGNORE_USER_RIGHTS
Definition: User.php:80
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:3850
bool $alreadyBlocked
static unsuppressUserName( $name, $userId, IDatabase $dbw=null)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
isSitewide( $x=null)
Indicates that the block is a sitewide block.
Definition: Block.php:1174
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
$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
const TYPE_AUTO
Definition: Block.php:99
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:617
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:589
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
string null $par
The sub-page of the special page.
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:611
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.
getId()
Get the user&#39;s ID.
Definition: User.php:2416
static suppressUserName( $name, $userId, IDatabase $dbw=null)
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.
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:4541
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:2633
const TYPE_USER
Definition: Block.php:96
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1398
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...
getRequest()
Get the WebRequest being used for this instance.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:587
addHeaderText( $msg, $section=null)
Add HTML to the header, inside the form.
Definition: HTMLForm.php:787
Definition: Block.php:31
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:2633
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
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:319