MediaWiki  1.33.0
SimpleCaptcha.php
Go to the documentation of this file.
1 <?php
2 
4 
8 class SimpleCaptcha {
9  protected static $messagePrefix = 'captcha-';
10 
12  private $captchaSolved = null;
13 
19  protected $action;
20 
22  protected $trigger;
23 
27  public function setAction( $action ) {
28  $this->action = $action;
29  }
30 
34  public function setTrigger( $trigger ) {
35  $this->trigger = $trigger;
36  }
37 
43  public function getError() {
44  return null;
45  }
46 
53  public function getCaptcha() {
54  $a = mt_rand( 0, 100 );
55  $b = mt_rand( 0, 10 );
56 
57  /* Minus sign is used in the question. UTF-8,
58  since the api uses text/plain, not text/html */
59  $op = mt_rand( 0, 1 ) ? '+' : '−';
60 
61  // No space before and after $op, to ensure correct
62  // directionality.
63  $test = "$a$op$b";
64  $answer = ( $op == '+' ) ? ( $a + $b ) : ( $a - $b );
65  return [ 'question' => $test, 'answer' => $answer ];
66  }
67 
71  protected function addCaptchaAPI( &$resultArr ) {
72  $captcha = $this->getCaptcha();
73  $index = $this->storeCaptcha( $captcha );
74  $resultArr['captcha'] = $this->describeCaptchaType();
75  $resultArr['captcha']['id'] = $index;
76  $resultArr['captcha']['question'] = $captcha['question'];
77  }
78 
84  public function describeCaptchaType() {
85  return [
86  'type' => 'simple',
87  'mime' => 'text/plain',
88  ];
89  }
90 
120  public function getFormInformation( $tabIndex = 1 ) {
121  $captcha = $this->getCaptcha();
122  $index = $this->storeCaptcha( $captcha );
123 
124  return [
125  'html' =>
126  new OOUI\FieldLayout(
127  new OOUI\NumberInputWidget( [
128  'name' => 'wpCaptchaWord',
129  'classes' => [ 'simplecaptcha-answer' ],
130  'id' => 'wpCaptchaWord',
131  'autocomplete' => 'off',
132  // tab in before the edit textarea
133  'tabIndex' => $tabIndex
134  ] ),
135  [
136  'align' => 'left',
137  'label' => $captcha['question'] . ' = ',
138  'classes' => [ 'simplecaptcha-field' ],
139  ]
140  ) .
141  new OOUI\HiddenInputWidget( [
142  'name' => 'wpCaptchaId',
143  'id' => 'wpCaptchaId',
144  'value' => $index
145  ] ),
146  'modulestyles' => [
147  'ext.confirmEdit.simpleCaptcha'
148  ]
149  ];
150  }
151 
159  public function addFormToOutput( OutputPage $out, $tabIndex = 1 ) {
160  $this->addFormInformationToOutput( $out, $this->getFormInformation( $tabIndex ) );
161  }
162 
170  public function addFormInformationToOutput( OutputPage $out, array $formInformation ) {
171  if ( !$formInformation ) {
172  return;
173  }
174  if ( isset( $formInformation['html'] ) ) {
175  $out->addHTML( $formInformation['html'] );
176  }
177  if ( isset( $formInformation['modules'] ) ) {
178  $out->addModules( $formInformation['modules'] );
179  }
180  if ( isset( $formInformation['modulestyles'] ) ) {
181  $out->addModuleStyles( $formInformation['modulestyles'] );
182  }
183  if ( isset( $formInformation['headitems'] ) ) {
184  $out->addHeadItems( $formInformation['headitems'] );
185  }
186  }
187 
193  public function getCaptchaInfo( $captchaData, $id ) {
194  return $captchaData['question'] . ' =';
195  }
196 
202  public function showEditFormFields( &$editPage, &$out ) {
203  $page = $editPage->getArticle()->getPage();
204  if ( !isset( $page->ConfirmEdit_ActivateCaptcha ) ) {
205  return;
206  }
207 
208  if ( $this->action !== 'edit' ) {
209  unset( $page->ConfirmEdit_ActivateCaptcha );
210  $out->addHTML( $this->getMessage( $this->action )->parseAsBlock() );
211  $this->addFormToOutput( $out );
212  }
213  }
214 
219  public function editShowCaptcha( $editPage ) {
220  $context = $editPage->getArticle()->getContext();
221  $page = $editPage->getArticle()->getPage();
222  $out = $context->getOutput();
223  if ( isset( $page->ConfirmEdit_ActivateCaptcha ) ||
224  $this->shouldCheck( $page, '', '', $context )
225  ) {
226  $out->addHTML( $this->getMessage( $this->action )->parseAsBlock() );
227  $this->addFormToOutput( $out );
228  }
229  unset( $page->ConfirmEdit_ActivateCaptcha );
230  }
231 
239  public function getMessage( $action ) {
240  // one of captcha-edit, captcha-addurl, captcha-badlogin, captcha-createaccount,
241  // captcha-create, captcha-sendemail
242  $name = static::$messagePrefix . $action;
243  $msg = wfMessage( $name );
244  // obtain a more tailored message, if possible, otherwise, fall back to
245  // the default for edits
246  return $msg->isDisabled() ? wfMessage( static::$messagePrefix . 'edit' ) : $msg;
247  }
248 
255  public function injectEmailUser( &$form ) {
256  $out = $form->getOutput();
257  $user = $form->getUser();
259  $this->action = 'sendemail';
260  if ( $this->canSkipCaptcha( $user, $form->getConfig() ) ) {
261  return true;
262  }
263  $formInformation = $this->getFormInformation();
264  $formMetainfo = $formInformation;
265  unset( $formMetainfo['html'] );
266  $this->addFormInformationToOutput( $out, $formMetainfo );
267  $form->addFooterText(
268  "<div class='captcha'>" .
269  $this->getMessage( 'sendemail' )->parseAsBlock() .
270  $formInformation['html'] .
271  "</div>\n" );
272  }
273  return true;
274  }
275 
282  public function increaseBadLoginCounter( $username ) {
283  global $wgCaptchaBadLoginExpiration, $wgCaptchaBadLoginPerUserExpiration;
284 
286 
288  $key = $this->badLoginKey();
289  $count = ObjectCache::getLocalClusterInstance()->get( $key );
290  if ( !$count ) {
291  $cache->add( $key, 0, $wgCaptchaBadLoginExpiration );
292  }
293 
294  $cache->incr( $key );
295  }
296 
298  $key = $this->badLoginPerUserKey( $username );
299  $count = $cache->get( $key );
300  if ( !$count ) {
301  $cache->add( $key, 0, $wgCaptchaBadLoginPerUserExpiration );
302  }
303 
304  $cache->incr( $key );
305  }
306  }
307 
312  public function resetBadLoginCounter( $username ) {
315  $cache->delete( $this->badLoginPerUserKey( $username ) );
316  }
317  }
318 
325  public function isBadLoginTriggered() {
326  global $wgCaptchaBadLoginAttempts;
327 
330  && (int)$cache->get( $this->badLoginKey() ) >= $wgCaptchaBadLoginAttempts;
331  }
332 
339  public function isBadLoginPerUserTriggered( $u ) {
340  global $wgCaptchaBadLoginPerUserAttempts;
341 
343 
344  if ( is_object( $u ) ) {
345  $u = $u->getName();
346  }
348  && (int)$cache->get( $this->badLoginPerUserKey( $u ) ) >= $wgCaptchaBadLoginPerUserAttempts;
349  }
350 
359  private function isIPWhitelisted() {
360  global $wgCaptchaWhitelistIP, $wgRequest;
361  $ip = $wgRequest->getIP();
362 
363  if ( $wgCaptchaWhitelistIP ) {
364  if ( IP::isInRanges( $ip, $wgCaptchaWhitelistIP ) ) {
365  return true;
366  }
367  }
368 
369  $whitelistMsg = wfMessage( 'captcha-ip-whitelist' )->inContentLanguage();
370  if ( !$whitelistMsg->isDisabled() ) {
371  $whitelistedIPs = $this->getWikiIPWhitelist( $whitelistMsg );
372  if ( IP::isInRanges( $ip, $whitelistedIPs ) ) {
373  return true;
374  }
375  }
376 
377  return false;
378  }
379 
387  private function getWikiIPWhitelist( Message $msg ) {
389  $cacheKey = $cache->makeKey( 'confirmedit', 'ipwhitelist' );
390 
391  $cachedWhitelist = $cache->get( $cacheKey );
392  if ( $cachedWhitelist === false ) {
393  // Could not retrieve from cache so build the whitelist directly
394  // from the wikipage
395  $whitelist = $this->buildValidIPs(
396  explode( "\n", $msg->plain() )
397  );
398  // And then store it in cache for one day. This cache is cleared on
399  // modifications to the whitelist page.
400  // @see ConfirmEditHooks::onPageContentSaveComplete()
401  $cache->set( $cacheKey, $whitelist, 86400 );
402  } else {
403  // Whitelist from the cache
404  $whitelist = $cachedWhitelist;
405  }
406 
407  return $whitelist;
408  }
409 
421  private function buildValidIPs( array $input ) {
422  // Remove whitespace and blank lines first
423  $ips = array_map( 'trim', $input );
424  $ips = array_filter( $ips );
425 
426  $validIPs = [];
427  foreach ( $ips as $ip ) {
428  if ( IP::isIPAddress( $ip ) ) {
429  $validIPs[] = $ip;
430  }
431  }
432 
433  return $validIPs;
434  }
435 
440  private function badLoginKey() {
441  global $wgRequest;
442  $ip = $wgRequest->getIP();
443  return wfGlobalCacheKey( 'captcha', 'badlogin', 'ip', $ip );
444  }
445 
451  private function badLoginPerUserKey( $username ) {
453  return wfGlobalCacheKey( 'captcha', 'badlogin', 'user', md5( $username ) );
454  }
455 
466  protected function keyMatch( $answer, $info ) {
467  return $answer == $info['answer'];
468  }
469 
470  // ----------------------------------
471 
478  public function captchaTriggers( $title, $action ) {
479  return $this->triggersCaptcha( $action, $title );
480  }
481 
492  public function triggersCaptcha( $action, $title = null ) {
493  global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
494 
495  $result = false;
496  $triggers = $wgCaptchaTriggers;
497  $attributeCaptchaTriggers = ExtensionRegistry::getInstance()
498  ->getAttribute( CaptchaTriggers::EXT_REG_ATTRIBUTE_NAME );
499  if ( is_array( $attributeCaptchaTriggers ) ) {
500  $triggers += $attributeCaptchaTriggers;
501  }
502 
503  if ( isset( $triggers[$action] ) ) {
504  $result = $triggers[$action];
505  }
506 
507  if (
508  $title !== null &&
509  isset( $wgCaptchaTriggersOnNamespace[$title->getNamespace()][$action] )
510  ) {
511  $result = $wgCaptchaTriggersOnNamespace[$title->getNamespace()][$action];
512  }
513 
514  return $result;
515  }
516 
526  public function shouldCheck( WikiPage $page, $content, $section, $context, $oldtext = null ) {
527  if ( !$context instanceof IContextSource ) {
529  }
530 
531  $request = $context->getRequest();
532  $user = $context->getUser();
533 
534  if ( $this->canSkipCaptcha( $user, $context->getConfig() ) ) {
535  return false;
536  }
537 
538  $title = $page->getTitle();
539  $this->trigger = '';
540 
541  if ( $content instanceof Content ) {
542  if ( $content->getModel() == CONTENT_MODEL_WIKITEXT ) {
543  $newtext = $content->getNativeData();
544  } else {
545  $newtext = null;
546  }
547  $isEmpty = $content->isEmpty();
548  } else {
549  $newtext = $content;
550  $isEmpty = $content === '';
551  }
552 
553  if ( $this->triggersCaptcha( 'edit', $title ) ) {
554  // Check on all edits
555  $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
556  $user->getName(),
557  $title->getPrefixedText() );
558  $this->action = 'edit';
559  wfDebug( "ConfirmEdit: checking all edits...\n" );
560  return true;
561  }
562 
563  if ( $this->triggersCaptcha( 'create', $title ) && !$title->exists() ) {
564  // Check if creating a page
565  $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
566  $user->getName(),
567  $title->getPrefixedText() );
568  $this->action = 'create';
569  wfDebug( "ConfirmEdit: checking on page creation...\n" );
570  return true;
571  }
572 
573  // The following checks are expensive and should be done only,
574  // if we can assume, that the edit will be saved
575  if ( !$request->wasPosted() ) {
576  wfDebug(
577  "ConfirmEdit: request not posted, assuming that no content will be saved -> no CAPTCHA check"
578  );
579  return false;
580  }
581 
582  if ( !$isEmpty && $this->triggersCaptcha( 'addurl', $title ) ) {
583  // Only check edits that add URLs
584  if ( $content instanceof Content ) {
585  // Get links from the database
586  $oldLinks = $this->getLinksFromTracker( $title );
587  // Share a parse operation with Article::doEdit()
588  $editInfo = $page->prepareContentForEdit( $content );
589  if ( $editInfo->output ) {
590  $newLinks = array_keys( $editInfo->output->getExternalLinks() );
591  } else {
592  $newLinks = [];
593  }
594  } else {
595  // Get link changes in the slowest way known to man
596  if ( $oldtext === null ) {
597  $oldtext = $this->loadText( $title, $section );
598  }
599  $oldLinks = $this->findLinks( $title, $oldtext );
600  $newLinks = $this->findLinks( $title, $newtext );
601  }
602 
603  $unknownLinks = array_filter( $newLinks, [ $this, 'filterLink' ] );
604  $addedLinks = array_diff( $unknownLinks, $oldLinks );
605  $numLinks = count( $addedLinks );
606 
607  if ( $numLinks > 0 ) {
608  $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
609  $numLinks,
610  $user->getName(),
611  $title->getPrefixedText(),
612  implode( ", ", $addedLinks ) );
613  $this->action = 'addurl';
614  return true;
615  }
616  }
617 
618  global $wgCaptchaRegexes;
619  if ( $newtext !== null && $wgCaptchaRegexes ) {
620  if ( !is_array( $wgCaptchaRegexes ) ) {
621  throw new UnexpectedValueException(
622  '$wgCaptchaRegexes is required to be an array, ' . gettype( $wgCaptchaRegexes ) . ' given.'
623  );
624  }
625  // Custom regex checks. Reuse $oldtext if set above.
626  if ( $oldtext === null ) {
627  $oldtext = $this->loadText( $title, $section );
628  }
629 
630  foreach ( $wgCaptchaRegexes as $regex ) {
631  $newMatches = [];
632  if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
633  $oldMatches = [];
634  preg_match_all( $regex, $oldtext, $oldMatches );
635 
636  $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
637 
638  $numHits = count( $addedMatches );
639  if ( $numHits > 0 ) {
640  $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
641  $numHits,
642  $regex,
643  $user->getName(),
644  $title->getPrefixedText(),
645  implode( ", ", $addedMatches ) );
646  $this->action = 'edit';
647  return true;
648  }
649  }
650  }
651  }
652 
653  return false;
654  }
655 
661  private function filterLink( $url ) {
662  global $wgCaptchaWhitelist;
663  static $regexes = null;
664 
665  if ( $regexes === null ) {
666  $source = wfMessage( 'captcha-addurl-whitelist' )->inContentLanguage();
667 
668  $regexes = $source->isDisabled()
669  ? []
670  : $this->buildRegexes( explode( "\n", $source->plain() ) );
671 
672  if ( $wgCaptchaWhitelist !== false ) {
673  array_unshift( $regexes, $wgCaptchaWhitelist );
674  }
675  }
676 
677  foreach ( $regexes as $regex ) {
678  if ( preg_match( $regex, $url ) ) {
679  return false;
680  }
681  }
682 
683  return true;
684  }
685 
692  private function buildRegexes( $lines ) {
693  # Code duplicated from the SpamBlacklist extension (r19197)
694  # and later modified.
695 
696  # Strip comments and whitespace, then remove blanks
697  $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
698 
699  # No lines, don't make a regex which will match everything
700  if ( count( $lines ) == 0 ) {
701  wfDebug( "No lines\n" );
702  return [];
703  } else {
704  # Make regex
705  # It's faster using the S modifier even though it will usually only be run once
706  // $regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
707  // return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
708  $regexes = [];
709  $regexStart = [
710  'normal' => '/^(?:https?:)?\/\/+[a-z0-9_\-.]*(?:',
711  'noprotocol' => '/^(?:',
712  ];
713  $regexEnd = [
714  'normal' => ')/Si',
715  'noprotocol' => ')/Si',
716  ];
717  $regexMax = 4096;
718  $build = [];
719  foreach ( $lines as $line ) {
720  # Extract flags from the line
721  $options = [];
722  if ( preg_match( '/^(.*?)\s*<([^<>]*)>$/', $line, $matches ) ) {
723  if ( $matches[1] === '' ) {
724  wfDebug( "Line with empty regex\n" );
725  continue;
726  }
727  $line = $matches[1];
728  $opts = preg_split( '/\s*\|\s*/', trim( $matches[2] ) );
729  foreach ( $opts as $opt ) {
730  $opt = strtolower( $opt );
731  if ( $opt == 'noprotocol' ) {
732  $options['noprotocol'] = true;
733  }
734  }
735  }
736 
737  $key = isset( $options['noprotocol'] ) ? 'noprotocol' : 'normal';
738 
739  // FIXME: not very robust size check, but should work. :)
740  if ( !isset( $build[$key] ) ) {
741  $build[$key] = $line;
742  } elseif ( strlen( $build[$key] ) + strlen( $line ) > $regexMax ) {
743  $regexes[] = $regexStart[$key] .
744  str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build[$key] ) ) .
745  $regexEnd[$key];
746  $build[$key] = $line;
747  } else {
748  $build[$key] .= '|' . $line;
749  }
750  }
751  foreach ( $build as $key => $value ) {
752  $regexes[] = $regexStart[$key] .
753  str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build[$key] ) ) .
754  $regexEnd[$key];
755  }
756  return $regexes;
757  }
758  }
759 
765  private function getLinksFromTracker( $title ) {
766  $dbr = wfGetDB( DB_REPLICA );
767  // should be zero queries
768  $id = $title->getArticleID();
769  $res = $dbr->select( 'externallinks', [ 'el_to' ],
770  [ 'el_from' => $id ], __METHOD__ );
771  $links = [];
772  foreach ( $res as $row ) {
773  $links[] = $row->el_to;
774  }
775  return $links;
776  }
777 
786  private function doConfirmEdit( WikiPage $page, $newtext, $section, IContextSource $context ) {
787  global $wgUser, $wgRequest;
788  $request = $context->getRequest();
789 
790  // FIXME: Stop using wgRequest in other parts of ConfirmEdit so we can
791  // stop having to duplicate code for it.
792  if ( $request->getVal( 'captchaid' ) ) {
793  $request->setVal( 'wpCaptchaId', $request->getVal( 'captchaid' ) );
794  $wgRequest->setVal( 'wpCaptchaId', $request->getVal( 'captchaid' ) );
795  }
796  if ( $request->getVal( 'captchaword' ) ) {
797  $request->setVal( 'wpCaptchaWord', $request->getVal( 'captchaword' ) );
798  $wgRequest->setVal( 'wpCaptchaWord', $request->getVal( 'captchaword' ) );
799  }
800  if ( $this->shouldCheck( $page, $newtext, $section, $context ) ) {
801  return $this->passCaptchaLimitedFromRequest( $wgRequest, $wgUser );
802  } else {
803  wfDebug( "ConfirmEdit: no need to show captcha.\n" );
804  return true;
805  }
806  }
807 
818  public function confirmEditMerged( $context, $content, $status, $summary, $user, $minorEdit ) {
819  if ( !$context->canUseWikiPage() ) {
820  // we check WikiPage only
821  // try to get an appropriate title for this page
822  $title = $context->getTitle();
823  if ( $title instanceof Title ) {
824  $title = $title->getFullText();
825  } else {
826  // otherwise it's an unknown page where this function is called from
827  $title = 'unknown';
828  }
829  // log this error, it could be a problem in another extension,
830  // edits should always have a WikiPage if
831  // they go through EditFilterMergedContent.
832  wfDebug( __METHOD__ . ': Skipped ConfirmEdit check: No WikiPage for title ' . $title );
833  return true;
834  }
835  $page = $context->getWikiPage();
836  if ( !$this->doConfirmEdit( $page, $content, false, $context ) ) {
838  $status->apiHookResult = [];
839  // give an error message for the user to know, what goes wrong here.
840  // this can't be done for addurl trigger, because this requires one "free" save
841  // for the user, which we don't know, when he did it.
842  if ( $this->action === 'edit' ) {
843  $status->fatal(
844  new RawMessage(
845  Html::element(
846  'div',
847  [ 'class' => 'errorbox' ],
848  $context->msg( 'captcha-edit-fail' )->text()
849  )
850  )
851  );
852  }
853  $this->addCaptchaAPI( $status->apiHookResult );
854  $page->ConfirmEdit_ActivateCaptcha = true;
855  return false;
856  }
857  return true;
858  }
859 
867  public function needCreateAccountCaptcha( User $creatingUser = null ) {
868  global $wgUser;
869  $creatingUser = $creatingUser ?: $wgUser;
870 
872  if ( $this->canSkipCaptcha( $creatingUser,
873  \MediaWiki\MediaWikiServices::getInstance()->getMainConfig() ) ) {
874  return false;
875  }
876  return true;
877  }
878  return false;
879  }
880 
890  public function confirmEmailUser( $from, $to, $subject, $text, &$error ) {
891  global $wgUser, $wgRequest;
892 
894  if ( $this->canSkipCaptcha( $wgUser,
895  \MediaWiki\MediaWikiServices::getInstance()->getMainConfig() ) ) {
896  return true;
897  }
898 
899  if ( defined( 'MW_API' ) ) {
900  # API mode
901  # Asking for captchas in the API is really silly
902  $error = Status::newFatal( 'captcha-disabledinapi' );
903  return false;
904  }
905  $this->trigger = "{$wgUser->getName()} sending email";
906  if ( !$this->passCaptchaLimitedFromRequest( $wgRequest, $wgUser ) ) {
907  $error = Status::newFatal( 'captcha-sendemail-fail' );
908  return false;
909  }
910  }
911  return true;
912  }
913 
918  protected function isAPICaptchaModule( $module ) {
919  return $module instanceof ApiEditPage;
920  }
921 
928  public function apiGetAllowedParams( &$module, &$params, $flags ) {
929  if ( $this->isAPICaptchaModule( $module ) ) {
930  $params['captchaword'] = [
931  ApiBase::PARAM_HELP_MSG => 'captcha-apihelp-param-captchaword',
932  ];
933  $params['captchaid'] = [
934  ApiBase::PARAM_HELP_MSG => 'captcha-apihelp-param-captchaid',
935  ];
936  }
937 
938  return true;
939  }
940 
950  list( $index, $word ) = $this->getCaptchaParamsFromRequest( $request );
951  return $this->passCaptchaLimited( $index, $word, $user );
952  }
953 
959  $index = $request->getVal( 'wpCaptchaId' );
960  $word = $request->getVal( 'wpCaptchaWord' );
961  return [ $index, $word ];
962  }
963 
974  public function passCaptchaLimited( $index, $word, User $user ) {
975  // don't increase pingLimiter here, just check, if CAPTCHA limit exceeded
976  if ( $user->pingLimiter( 'badcaptcha', 0 ) ) {
977  // for debugging add an proper error message, the user just see an false captcha error message
978  $this->log( 'User reached RateLimit, preventing action' );
979  return false;
980  }
981 
982  if ( $this->passCaptcha( $index, $word ) ) {
983  return true;
984  }
985 
986  // captcha was not solved: increase limit and return false
987  $user->pingLimiter( 'badcaptcha' );
988  return false;
989  }
990 
999  list( $index, $word ) = $this->getCaptchaParamsFromRequest( $request );
1000  return $this->passCaptcha( $index, $word );
1001  }
1002 
1010  protected function passCaptcha( $index, $word ) {
1011  // Don't check the same CAPTCHA twice in one session,
1012  // if the CAPTCHA was already checked - Bug T94276
1013  if ( isset( $this->captchaSolved ) ) {
1014  return $this->captchaSolved;
1015  }
1016 
1017  $info = $this->retrieveCaptcha( $index );
1018  if ( $info ) {
1019  if ( $this->keyMatch( $word, $info ) ) {
1020  $this->log( "passed" );
1021  $this->clearCaptcha( $index );
1022  $this->captchaSolved = true;
1023  return true;
1024  } else {
1025  $this->clearCaptcha( $index );
1026  $this->log( "bad form input" );
1027  $this->captchaSolved = false;
1028  return false;
1029  }
1030  } else {
1031  $this->log( "new captcha session" );
1032  return false;
1033  }
1034  }
1035 
1040  protected function log( $message ) {
1041  wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
1042  }
1043 
1055  public function storeCaptcha( $info ) {
1056  if ( !isset( $info['index'] ) ) {
1057  // Assign random index if we're not udpating
1058  $info['index'] = strval( mt_rand() );
1059  }
1060  CaptchaStore::get()->store( $info['index'], $info );
1061  return $info['index'];
1062  }
1063 
1069  public function retrieveCaptcha( $index ) {
1070  return CaptchaStore::get()->retrieve( $index );
1071  }
1072 
1078  public function clearCaptcha( $index ) {
1079  CaptchaStore::get()->clear( $index );
1080  }
1081 
1090  private function loadText( $title, $section, $flags = Revision::READ_LATEST ) {
1091  global $wgParser;
1092 
1093  $rev = Revision::newFromTitle( $title, false, $flags );
1094  if ( is_null( $rev ) ) {
1095  return "";
1096  }
1097 
1098  $content = $rev->getContent();
1100  if ( $section !== '' ) {
1101  return $wgParser->getSection( $text, $section );
1102  }
1103 
1104  return $text;
1105  }
1106 
1113  private function findLinks( $title, $text ) {
1114  global $wgParser, $wgUser;
1115 
1116  $options = new ParserOptions();
1117  $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
1118  $out = $wgParser->parse( $text, $title, $options );
1119 
1120  return array_keys( $out->getExternalLinks() );
1121  }
1122 
1126  public function showHelp() {
1127  global $wgOut;
1128  $wgOut->setPageTitle( wfMessage( 'captchahelp-title' )->text() );
1129  $wgOut->addWikiMsg( 'captchahelp-text' );
1130  if ( CaptchaStore::get()->cookiesNeeded() ) {
1131  $wgOut->addWikiMsg( 'captchahelp-cookies-needed' );
1132  }
1133  }
1134 
1138  public function createAuthenticationRequest() {
1139  $captchaData = $this->getCaptcha();
1140  $id = $this->storeCaptcha( $captchaData );
1141  return new CaptchaAuthenticationRequest( $id, $captchaData );
1142  }
1143 
1151  public function onAuthChangeFormFields(
1153  ) {
1154  $req = AuthenticationRequest::getRequestByClass( $requests,
1156  if ( !$req ) {
1157  return;
1158  }
1159 
1160  $formDescriptor['captchaWord'] = [
1161  'label-message' => null,
1162  'autocomplete' => false,
1163  'persistent' => false,
1164  'required' => true,
1165  ] + $formDescriptor['captchaWord'];
1166  }
1167 
1175  public function canSkipCaptcha( $user, Config $config ) {
1176  $allowConfirmEmail = $config->get( 'AllowConfirmedEmail' );
1177 
1178  if ( $user->isAllowed( 'skipcaptcha' ) ) {
1179  wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
1180  return true;
1181  }
1182 
1183  if ( $this->isIPWhitelisted() ) {
1184  wfDebug( "ConfirmEdit: user IP is whitelisted" );
1185  return true;
1186  }
1187 
1188  if ( $allowConfirmEmail && $user->isEmailConfirmed() ) {
1189  wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
1190  return true;
1191  }
1192 
1193  return false;
1194  }
1195 }
ApiEditPage
A module that allows for editing and creating pages.
Definition: ApiEditPage.php:32
SimpleCaptcha\confirmEmailUser
confirmEmailUser( $from, $to, $subject, $text, &$error)
Check the captcha on Special:EmailUser.
Definition: SimpleCaptcha.php:890
$status
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:1266
ParserOptions
Set options of the Parser.
Definition: ParserOptions.php:42
CaptchaStore\get
static get()
Get somewhere to store captcha data that will persist between requests.
Definition: CaptchaStore.php:42
$user
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
SimpleCaptcha\badLoginPerUserKey
badLoginPerUserKey( $username)
Cache key for badloginPerUser checks.
Definition: SimpleCaptcha.php:451
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:356
$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:2636
$wgParser
$wgParser
Definition: Setup.php:886
SimpleCaptcha\loadText
loadText( $title, $section, $flags=Revision::READ_LATEST)
Retrieve the current version of the page or section being edited...
Definition: SimpleCaptcha.php:1090
CaptchaTriggers\SENDEMAIL
const SENDEMAIL
Definition: CaptchaTriggers.php:10
SimpleCaptcha\passCaptchaLimitedFromRequest
passCaptchaLimitedFromRequest(WebRequest $request, User $user)
Checks, if the user reached the amount of false CAPTCHAs and give him some vacation or run self::pass...
Definition: SimpleCaptcha.php:949
IP\isInRanges
static isInRanges( $ip, $ranges)
Determines if an IP address is a list of CIDR a.b.c.d/n ranges.
Definition: IP.php:668
$opt
$opt
Definition: postprocess-phan.php:115
captcha-old.count
count
Definition: captcha-old.py:249
SimpleCaptcha\addFormToOutput
addFormToOutput(OutputPage $out, $tabIndex=1)
Uses getFormInformation() to get the CAPTCHA form and adds it to the given OutputPage object.
Definition: SimpleCaptcha.php:159
ApiBase\PARAM_HELP_MSG
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:124
MediaWiki\getTitle
getTitle()
Get the Title object that we'll be acting on, as specified in the WebRequest.
Definition: MediaWiki.php:137
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1983
$out
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
SimpleCaptcha\keyMatch
keyMatch( $answer, $info)
Check if the submitted form matches the captcha session data provided by the plugin when the form was...
Definition: SimpleCaptcha.php:466
SimpleCaptcha\editShowCaptcha
editShowCaptcha( $editPage)
Insert the captcha prompt into an edit form.
Definition: SimpleCaptcha.php:219
$req
this hook is for auditing only $req
Definition: hooks.txt:979
WikiPage
Class representing a MediaWiki article and history.
Definition: WikiPage.php:45
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
$params
$params
Definition: styleTest.css.php:44
SimpleCaptcha\captchaTriggers
captchaTriggers( $title, $action)
Definition: SimpleCaptcha.php:478
$formDescriptor
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 & $formDescriptor
Definition: hooks.txt:2064
$res
$res
Definition: database.txt:21
SimpleCaptcha\$action
string $action
Used to select the right message.
Definition: SimpleCaptcha.php:19
CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:235
SimpleCaptcha\showHelp
showHelp()
Show a page explaining what this wacky thing is.
Definition: SimpleCaptcha.php:1126
SimpleCaptcha\setAction
setAction( $action)
Definition: SimpleCaptcha.php:27
SimpleCaptcha\injectEmailUser
injectEmailUser(&$form)
Inject whazawhoo @fixme if multiple thingies insert a header, could break.
Definition: SimpleCaptcha.php:255
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1043
SimpleCaptcha\buildRegexes
buildRegexes( $lines)
Build regex from whitelist.
Definition: SimpleCaptcha.php:692
php
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
$dbr
$dbr
Definition: testCompression.php:50
SimpleCaptcha\getCaptchaInfo
getCaptchaInfo( $captchaData, $id)
Definition: SimpleCaptcha.php:193
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:98
Revision\newFromTitle
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Definition: Revision.php:137
SimpleCaptcha\canSkipCaptcha
canSkipCaptcha( $user, Config $config)
Check whether the user provided / IP making the request is allowed to skip captchas.
Definition: SimpleCaptcha.php:1175
Config
Interface for configuration instances.
Definition: Config.php:28
SimpleCaptcha\passCaptchaLimited
passCaptchaLimited( $index, $word, User $user)
Checks, if the user reached the amount of false CAPTCHAs and give him some vacation or run self::pass...
Definition: SimpleCaptcha.php:974
SimpleCaptcha\addCaptchaAPI
addCaptchaAPI(&$resultArr)
Definition: SimpleCaptcha.php:71
CaptchaTriggers\CREATE_ACCOUNT
const CREATE_ACCOUNT
Definition: CaptchaTriggers.php:12
SimpleCaptcha\resetBadLoginCounter
resetBadLoginCounter( $username)
Reset bad login counter after a successful login.
Definition: SimpleCaptcha.php:312
CaptchaTriggers\BAD_LOGIN
const BAD_LOGIN
Definition: CaptchaTriggers.php:13
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
SimpleCaptcha\getCaptcha
getCaptcha()
Returns an array with 'question' and 'answer' keys.
Definition: SimpleCaptcha.php:53
Config\get
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
SimpleCaptcha\filterLink
filterLink( $url)
Filter callback function for URL whitelisting.
Definition: SimpleCaptcha.php:661
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2636
$input
if(is_array( $mode)) switch( $mode) $input
Definition: postprocess-phan.php:141
$matches
$matches
Definition: NoLocalSettings.php:24
SimpleCaptcha\findLinks
findLinks( $title, $text)
Extract a list of all recognized HTTP links in the text.
Definition: SimpleCaptcha.php:1113
SimpleCaptcha\getWikiIPWhitelist
getWikiIPWhitelist(Message $msg)
Get the on-wiki IP whitelist stored in [[MediaWiki:Captcha-ip-whitelist]] page from cache if possible...
Definition: SimpleCaptcha.php:387
WikiPage\getTitle
getTitle()
Get the title object of the article.
Definition: WikiPage.php:294
MediaWiki
A helper class for throttling authentication attempts.
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
SimpleCaptcha\getCaptchaParamsFromRequest
getCaptchaParamsFromRequest(WebRequest $request)
Definition: SimpleCaptcha.php:958
$lines
$lines
Definition: router.php:61
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
array
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))
SimpleCaptcha\onAuthChangeFormFields
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
Modify the appearance of the captcha field.
Definition: SimpleCaptcha.php:1151
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:949
list
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
captcha-old.action
action
Definition: captcha-old.py:212
SimpleCaptcha\apiGetAllowedParams
apiGetAllowedParams(&$module, &$params, $flags)
Definition: SimpleCaptcha.php:928
$request
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:2636
SimpleCaptcha\doConfirmEdit
doConfirmEdit(WikiPage $page, $newtext, $section, IContextSource $context)
Backend function for confirmEditMerged()
Definition: SimpleCaptcha.php:786
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
SimpleCaptcha\badLoginKey
badLoginKey()
Internal cache key for badlogin checks.
Definition: SimpleCaptcha.php:440
$line
$line
Definition: cdb.php:59
wfGlobalCacheKey
wfGlobalCacheKey(... $args)
Make a cache key with database-agnostic prefix.
Definition: GlobalFunctions.php:2592
SimpleCaptcha\confirmEditMerged
confirmEditMerged( $context, $content, $status, $summary, $user, $minorEdit)
An efficient edit filter callback based on the text after section merging.
Definition: SimpleCaptcha.php:818
SimpleCaptcha\isIPWhitelisted
isIPWhitelisted()
Check if the current IP is allowed to skip captchas.
Definition: SimpleCaptcha.php:359
SimpleCaptcha\isBadLoginTriggered
isBadLoginTriggered()
Check if a bad login has already been registered for this IP address.
Definition: SimpleCaptcha.php:325
$value
$value
Definition: styleTest.css.php:49
WikiPage\prepareContentForEdit
prepareContentForEdit(Content $content, $revision=null, User $user=null, $serialFormat=null, $useCache=true)
Prepare content which is about to be saved.
Definition: WikiPage.php:1977
SimpleCaptcha\setTrigger
setTrigger( $trigger)
Definition: SimpleCaptcha.php:34
SimpleCaptcha\log
log( $message)
Log the status and any triggering info for debugging or statistics.
Definition: SimpleCaptcha.php:1040
SimpleCaptcha\retrieveCaptcha
retrieveCaptcha( $index)
Fetch this session's captcha info.
Definition: SimpleCaptcha.php:1069
SimpleCaptcha\createAuthenticationRequest
createAuthenticationRequest()
Definition: SimpleCaptcha.php:1138
SimpleCaptcha\needCreateAccountCaptcha
needCreateAccountCaptcha(User $creatingUser=null)
Logic to check if we need to pass a captcha for the current user to create a new account,...
Definition: SimpleCaptcha.php:867
SimpleCaptcha\$messagePrefix
static $messagePrefix
Definition: SimpleCaptcha.php:9
SimpleCaptcha\addFormInformationToOutput
addFormInformationToOutput(OutputPage $out, array $formInformation)
Processes the given $formInformation array and adds the options (see getFormInformation()) to the giv...
Definition: SimpleCaptcha.php:170
SimpleCaptcha
Demo CAPTCHA (not for production usage) and base class for real CAPTCHAs.
Definition: SimpleCaptcha.php:8
SimpleCaptcha\getError
getError()
Return the error from the last passCaptcha* call.
Definition: SimpleCaptcha.php:43
SimpleCaptcha\storeCaptcha
storeCaptcha( $info)
Generate a captcha session ID and save the info in PHP's session storage.
Definition: SimpleCaptcha.php:1055
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:430
CaptchaTriggers\EXT_REG_ATTRIBUTE_NAME
const EXT_REG_ATTRIBUTE_NAME
Definition: CaptchaTriggers.php:16
SimpleCaptcha\getMessage
getMessage( $action)
Show a message asking the user to enter a captcha on edit The result will be treated as wiki text.
Definition: SimpleCaptcha.php:239
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:53
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:41
SimpleCaptcha\describeCaptchaType
describeCaptchaType()
Describes the captcha type for API clients.
Definition: SimpleCaptcha.php:84
SimpleCaptcha\isBadLoginPerUserTriggered
isBadLoginPerUserTriggered( $u)
Is the per-user captcha triggered?
Definition: SimpleCaptcha.php:339
Content
Base interface for content objects.
Definition: Content.php:34
SimpleCaptcha\isAPICaptchaModule
isAPICaptchaModule( $module)
Definition: SimpleCaptcha.php:918
text
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
Definition: All_system_messages.txt:1267
Title
Represents a title within MediaWiki.
Definition: Title.php:40
SimpleCaptcha\$trigger
string $trigger
Used in log messages.
Definition: SimpleCaptcha.php:22
ContentHandler\getContentText
static getContentText(Content $content=null)
Convenience function for getting flat text from a Content object.
Definition: ContentHandler.php:83
SimpleCaptcha\shouldCheck
shouldCheck(WikiPage $page, $content, $section, $context, $oldtext=null)
Definition: SimpleCaptcha.php:526
$cache
$cache
Definition: mcc.php:33
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1985
ObjectCache\getMainWANInstance
static getMainWANInstance()
Get the main WAN cache object.
Definition: ObjectCache.php:369
SimpleCaptcha\increaseBadLoginCounter
increaseBadLoginCounter( $username)
Increase bad login counter after a failed login.
Definition: SimpleCaptcha.php:282
SimpleCaptcha\$captchaSolved
boolean null $captchaSolved
Was the CAPTCHA already passed and if yes, with which result?
Definition: SimpleCaptcha.php:12
SimpleCaptcha\passCaptcha
passCaptcha( $index, $word)
Given a required captcha run, test form input for correct input on the open session.
Definition: SimpleCaptcha.php:1010
$section
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition: hooks.txt:3053
User\getCanonicalName
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
Definition: User.php:1244
SimpleCaptcha\getLinksFromTracker
getLinksFromTracker( $title)
Load external links from the externallinks table.
Definition: SimpleCaptcha.php:765
$rev
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1769
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$requests
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead. & $feedLinks hooks can tweak the array to change how login etc forms should look $requests
Definition: hooks.txt:273
$source
$source
Definition: mwdoc-filter.php:46
$content
$content
Definition: pageupdater.txt:72
CaptchaTriggers\BAD_LOGIN_PER_USER
const BAD_LOGIN_PER_USER
Definition: CaptchaTriggers.php:14
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:728
SimpleCaptcha\triggersCaptcha
triggersCaptcha( $action, $title=null)
Checks, whether the passed action should trigger a CAPTCHA.
Definition: SimpleCaptcha.php:492
RawMessage
Variant of the Message class.
Definition: RawMessage.php:34
$wgOut
$wgOut
Definition: Setup.php:880
wfMessage
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
SimpleCaptcha\showEditFormFields
showEditFormFields(&$editPage, &$out)
Show error message for missing or incorrect captcha on EditPage.
Definition: SimpleCaptcha.php:202
SimpleCaptcha\getFormInformation
getFormInformation( $tabIndex=1)
Insert a captcha prompt into the edit form.
Definition: SimpleCaptcha.php:120
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:48
$username
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:780
SimpleCaptcha\passCaptchaFromRequest
passCaptchaFromRequest(WebRequest $request, User $user)
Given a required captcha run, test form input for correct input on the open session.
Definition: SimpleCaptcha.php:998
EditPage\AS_HOOK_ERROR_EXPECTED
const AS_HOOK_ERROR_EXPECTED
Status: A hook function returned an error.
Definition: EditPage.php:68
MediaWiki\Auth\AuthenticationRequest
This is a value object for authentication requests.
Definition: AuthenticationRequest.php:37
IP\isIPAddress
static isIPAddress( $ip)
Determine if a string is as valid IP address or network (CIDR prefix).
Definition: IP.php:77
CaptchaAuthenticationRequest
Generic captcha authentication request class.
Definition: CaptchaAuthenticationRequest.php:10
SimpleCaptcha\buildValidIPs
buildValidIPs(array $input)
From a list of unvalidated input, get all the valid IP addresses and IP ranges from it.
Definition: SimpleCaptcha.php:421
SimpleCaptcha\clearCaptcha
clearCaptcha( $index)
Clear out existing captcha info from the session, to ensure it can't be reused.
Definition: SimpleCaptcha.php:1078