MediaWiki  master
LoginSignupSpecialPage.php
Go to the documentation of this file.
1 <?php
31 
38  protected $mReturnTo;
39  protected $mPosted;
40  protected $mAction;
41  protected $mLanguage;
42  protected $mReturnToQuery;
43  protected $mToken;
44  protected $mStickHTTPS;
45  protected $mFromHTTP;
46  protected $mEntryError = '';
47  protected $mEntryErrorType = 'error';
48 
49  protected $mLoaded = false;
50  protected $mLoadedRequest = false;
51  protected $mSecureLoginUrl;
52 
54  protected $securityLevel;
55 
60  protected $targetUser;
61 
63  protected $authForm;
64 
65  abstract protected function isSignup();
66 
73  abstract protected function successfulAction( $direct = false, $extraMessages = null );
74 
80  abstract protected function logAuthResult( $success, $status = null );
81 
82  public function __construct( $name ) {
84  parent::__construct( $name );
85 
86  // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
87  $wgUseMediaWikiUIEverywhere = true;
88  }
89 
90  protected function setRequest( array $data, $wasPosted = null ) {
91  parent::setRequest( $data, $wasPosted );
92  $this->mLoadedRequest = false;
93  }
94 
99  private function loadRequestParameters( $subPage ) {
100  if ( $this->mLoadedRequest ) {
101  return;
102  }
103  $this->mLoadedRequest = true;
104  $request = $this->getRequest();
105 
106  $this->mPosted = $request->wasPosted();
107  $this->mIsReturn = $subPage === 'return';
108  $this->mAction = $request->getVal( 'action' );
109  $this->mFromHTTP = $request->getBool( 'fromhttp', false )
110  || $request->getBool( 'wpFromhttp', false );
111  $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
112  || $request->getBool( 'wpForceHttps', false );
113  $this->mLanguage = $request->getText( 'uselang' );
114  $this->mReturnTo = $request->getVal( 'returnto', '' );
115  $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
116  }
117 
123  protected function load( $subPage ) {
124  global $wgSecureLogin;
125 
127  if ( $this->mLoaded ) {
128  return;
129  }
130  $this->mLoaded = true;
131  $request = $this->getRequest();
132 
133  $securityLevel = $this->getRequest()->getText( 'force' );
134  if (
135  $securityLevel && AuthManager::singleton()->securitySensitiveOperationStatus(
136  $securityLevel ) === AuthManager::SEC_REAUTH
137  ) {
138  $this->securityLevel = $securityLevel;
139  }
140 
141  $this->loadAuth( $subPage );
142 
143  $this->mToken = $request->getVal( $this->getTokenName() );
144 
145  // Show an error or warning passed on from a previous page
146  $entryError = $this->msg( $request->getVal( 'error', '' ) );
147  $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
148  // bc: provide login link as a parameter for messages where the translation
149  // was not updated
150  $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
151  $this->getPageTitle(),
152  $this->msg( 'loginreqlink' )->text(),
153  [],
154  [
155  'returnto' => $this->mReturnTo,
156  'returntoquery' => $this->mReturnToQuery,
157  'uselang' => $this->mLanguage ?: null,
158  'fromhttp' => $wgSecureLogin && $this->mFromHTTP ? '1' : null,
159  ]
160  );
161 
162  // Only show valid error or warning messages.
163  if ( $entryError->exists()
164  && in_array( $entryError->getKey(), LoginHelper::getValidErrorMessages(), true )
165  ) {
166  $this->mEntryErrorType = 'error';
167  $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
168 
169  } elseif ( $entryWarning->exists()
170  && in_array( $entryWarning->getKey(), LoginHelper::getValidErrorMessages(), true )
171  ) {
172  $this->mEntryErrorType = 'warning';
173  $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
174  }
175 
176  # 1. When switching accounts, it sucks to get automatically logged out
177  # 2. Do not return to PasswordReset after a successful password change
178  # but goto Wiki start page (Main_Page) instead ( T35997 )
179  $returnToTitle = Title::newFromText( $this->mReturnTo );
180  if ( is_object( $returnToTitle )
181  && ( $returnToTitle->isSpecial( 'Userlogout' )
182  || $returnToTitle->isSpecial( 'PasswordReset' ) )
183  ) {
184  $this->mReturnTo = '';
185  $this->mReturnToQuery = '';
186  }
187  }
188 
189  protected function getPreservedParams( $withToken = false ) {
190  global $wgSecureLogin;
191 
192  $params = parent::getPreservedParams( $withToken );
193  $params += [
194  'returnto' => $this->mReturnTo ?: null,
195  'returntoquery' => $this->mReturnToQuery ?: null,
196  ];
197  if ( $wgSecureLogin && !$this->isSignup() ) {
198  $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
199  }
200  return $params;
201  }
202 
203  protected function beforeExecute( $subPage ) {
204  // finish initializing the class before processing the request - T135924
206  return parent::beforeExecute( $subPage );
207  }
208 
212  public function execute( $subPage ) {
213  if ( $this->mPosted ) {
214  $time = microtime( true );
215  $profilingScope = new ScopedCallback( function () use ( $time ) {
216  $time = microtime( true ) - $time;
217  $statsd = MediaWikiServices::getInstance()->getStatsdDataFactory();
218  $statsd->timing( "timing.login.ui.{$this->authAction}", $time * 1000 );
219  } );
220  }
221 
222  $authManager = AuthManager::singleton();
223  $session = SessionManager::getGlobalSession();
224 
225  // Session data is used for various things in the authentication process, so we must make
226  // sure a session cookie or some equivalent mechanism is set.
227  $session->persist();
228 
229  $this->load( $subPage );
230  $this->setHeaders();
231  $this->checkPermissions();
232 
233  // Make sure the system configuration allows log in / sign up
234  if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
235  if ( !$session->canSetUser() ) {
236  throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
237  $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
238  ] );
239  }
240  throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
241  } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
242  throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
243  }
244 
245  /*
246  * In the case where the user is already logged in, and was redirected to
247  * the login form from a page that requires login, do not show the login
248  * page. The use case scenario for this is when a user opens a large number
249  * of tabs, is redirected to the login page on all of them, and then logs
250  * in on one, expecting all the others to work properly.
251  *
252  * However, do show the form if it was visited intentionally (no 'returnto'
253  * is present). People who often switch between several accounts have grown
254  * accustomed to this behavior.
255  *
256  * Also make an exception when force=<level> is set in the URL, which means the user must
257  * reauthenticate for security reasons.
258  */
259  if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
260  ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
261  $this->getUser()->isLoggedIn()
262  ) {
263  $this->successfulAction();
264  return;
265  }
266 
267  // If logging in and not on HTTPS, either redirect to it or offer a link.
268  global $wgSecureLogin;
269  if ( $this->getRequest()->getProtocol() !== 'https' ) {
270  $title = $this->getFullTitle();
271  $query = $this->getPreservedParams( false ) + [
272  'title' => null,
273  ( $this->mEntryErrorType === 'error' ? 'error'
274  : 'warning' ) => $this->mEntryError,
275  ] + $this->getRequest()->getQueryValues();
276  $url = $title->getFullURL( $query, false, PROTO_HTTPS );
277  if ( $wgSecureLogin && !$this->mFromHTTP &&
278  wfCanIPUseHTTPS( $this->getRequest()->getIP() )
279  ) {
280  // Avoid infinite redirect
281  $url = wfAppendQuery( $url, 'fromhttp=1' );
282  $this->getOutput()->redirect( $url );
283  // Since we only do this redir to change proto, always vary
284  $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
285 
286  return;
287  } else {
288  // A wiki without HTTPS login support should set $wgServer to
289  // http://somehost, in which case the secure URL generated
290  // above won't actually start with https://
291  if ( substr( $url, 0, 8 ) === 'https://' ) {
292  $this->mSecureLoginUrl = $url;
293  }
294  }
295  }
296 
297  if ( !$this->isActionAllowed( $this->authAction ) ) {
298  // FIXME how do we explain this to the user? can we handle session loss better?
299  // messages used: authpage-cannot-login, authpage-cannot-login-continue,
300  // authpage-cannot-create, authpage-cannot-create-continue
301  $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
302  return;
303  }
304 
305  if ( $this->canBypassForm( $button_name ) ) {
306  $this->setRequest( [], true );
307  $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
308  if ( $button_name ) {
309  $this->getRequest()->setVal( $button_name, true );
310  }
311  }
312 
313  $status = $this->trySubmit();
314 
315  if ( !$status || !$status->isGood() ) {
316  $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
317  return;
318  }
319 
321  $response = $status->getValue();
322 
323  $returnToUrl = $this->getPageTitle( 'return' )
324  ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
325  switch ( $response->status ) {
326  case AuthenticationResponse::PASS:
327  $this->logAuthResult( true );
328  $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
329  $this->targetUser = User::newFromName( $response->username );
330 
331  if (
332  !$this->proxyAccountCreation
333  && $response->loginRequest
334  && $authManager->canAuthenticateNow()
335  ) {
336  // successful registration; log the user in instantly
337  $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
338  $returnToUrl );
339  if ( $response2->status !== AuthenticationResponse::PASS ) {
340  LoggerFactory::getInstance( 'login' )
341  ->error( 'Could not log in after account creation' );
342  $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
343  break;
344  }
345  }
346 
347  if ( !$this->proxyAccountCreation ) {
348  // Ensure that the context user is the same as the session user.
350  }
351 
352  $this->successfulAction( true );
353  break;
354  case AuthenticationResponse::FAIL:
355  // fall through
356  case AuthenticationResponse::RESTART:
357  unset( $this->authForm );
358  if ( $response->status === AuthenticationResponse::FAIL ) {
359  $action = $this->getDefaultAction( $subPage );
360  $messageType = 'error';
361  } else {
362  $action = $this->getContinueAction( $this->authAction );
363  $messageType = 'warning';
364  }
365  $this->logAuthResult( false, $response->message ? $response->message->getKey() : '-' );
366  $this->loadAuth( $subPage, $action, true );
367  $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
368  break;
369  case AuthenticationResponse::REDIRECT:
370  unset( $this->authForm );
371  $this->getOutput()->redirect( $response->redirectTarget );
372  break;
373  case AuthenticationResponse::UI:
374  unset( $this->authForm );
375  $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
376  : AuthManager::ACTION_LOGIN_CONTINUE;
377  $this->authRequests = $response->neededRequests;
378  $this->mainLoginForm( $response->neededRequests, $response->message, $response->messageType );
379  break;
380  default:
381  throw new LogicException( 'invalid AuthenticationResponse' );
382  }
383  }
384 
398  private function canBypassForm( &$button_name ) {
399  $button_name = null;
400  if ( $this->isContinued() ) {
401  return false;
402  }
403  $fields = AuthenticationRequest::mergeFieldInfo( $this->authRequests );
404  foreach ( $fields as $fieldname => $field ) {
405  if ( !isset( $field['type'] ) ) {
406  return false;
407  }
408  if ( !empty( $field['skippable'] ) ) {
409  continue;
410  }
411  if ( $field['type'] === 'button' ) {
412  if ( $button_name !== null ) {
413  $button_name = null;
414  return false;
415  } else {
416  $button_name = $fieldname;
417  }
418  } elseif ( $field['type'] !== 'null' ) {
419  return false;
420  }
421  }
422  return true;
423  }
424 
434  protected function showSuccessPage(
435  $type, $title, $msgname, $injected_html, $extraMessages
436  ) {
437  $out = $this->getOutput();
438  $out->setPageTitle( $title );
439  if ( $msgname ) {
440  $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
441  }
442  if ( $extraMessages ) {
443  $extraMessages = Status::wrap( $extraMessages );
444  $out->addWikiTextAsInterface( $extraMessages->getWikiText() );
445  }
446 
447  $out->addHTML( $injected_html );
448 
449  $helper = new LoginHelper( $this->getContext() );
450  $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery, $this->mStickHTTPS );
451  }
452 
468  public function showReturnToPage(
469  $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
470  ) {
471  $helper = new LoginHelper( $this->getContext() );
472  $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
473  }
474 
479  protected function setSessionUserForCurrentRequest() {
480  global $wgUser, $wgLang;
481 
483  $localContext = $this->getContext();
484  if ( $context !== $localContext ) {
485  // remove AuthManagerSpecialPage context hack
486  $this->setContext( $context );
487  }
488 
489  $user = $context->getRequest()->getSession()->getUser();
490 
491  $wgUser = $user;
492  $context->setUser( $user );
493 
494  $code = $this->getRequest()->getVal( 'uselang', $user->getOption( 'language' ) );
495  $userLang = Language::factory( $code );
496  $wgLang = $userLang;
497  $context->setLanguage( $userLang );
498  }
499 
514  protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
515  $user = $this->getUser();
516  $out = $this->getOutput();
517 
518  // FIXME how to handle empty $requests - restart, or no form, just an error message?
519  // no form would be better for no session type errors, restart is better when can* fails.
520  if ( !$requests ) {
521  $this->authAction = $this->getDefaultAction( $this->subPage );
522  $this->authForm = null;
523  $requests = AuthManager::singleton()->getAuthenticationRequests( $this->authAction, $user );
524  }
525 
526  // Generic styles and scripts for both login and signup form
527  $out->addModuleStyles( [
528  'mediawiki.ui',
529  'mediawiki.ui.button',
530  'mediawiki.ui.checkbox',
531  'mediawiki.ui.input',
532  'mediawiki.special.userlogin.common.styles'
533  ] );
534  if ( $this->isSignup() ) {
535  // XXX hack pending RL or JS parse() support for complex content messages T27349
536  $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
537  $this->msg( 'createacct-imgcaptcha-help' )->parse() );
538 
539  // Additional styles and scripts for signup form
540  $out->addModules( [
541  'mediawiki.special.userlogin.signup.js'
542  ] );
543  $out->addModuleStyles( [
544  'mediawiki.special.userlogin.signup.styles'
545  ] );
546  } else {
547  // Additional styles for login form
548  $out->addModuleStyles( [
549  'mediawiki.special.userlogin.login.styles'
550  ] );
551  }
552  $out->disallowUserJs(); // just in case...
553 
554  $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
555  $form->prepareForm();
556 
557  $submitStatus = Status::newGood();
558  if ( $msg && $msgtype === 'warning' ) {
559  $submitStatus->warning( $msg );
560  } elseif ( $msg && $msgtype === 'error' ) {
561  $submitStatus->fatal( $msg );
562  }
563 
564  // warning header for non-standard workflows (e.g. security reauthentication)
565  if (
566  !$this->isSignup() &&
567  $this->getUser()->isLoggedIn() &&
568  $this->authAction !== AuthManager::ACTION_LOGIN_CONTINUE
569  ) {
570  $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
571  $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
572  }
573 
574  $formHtml = $form->getHTML( $submitStatus );
575 
576  $out->addHTML( $this->getPageHtml( $formHtml ) );
577  }
578 
585  protected function getPageHtml( $formHtml ) {
587 
588  $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
589  [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
590  $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
591  $signupStartMsg = $this->msg( 'signupstart' );
592  $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
593  ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
594  if ( $languageLinks ) {
595  $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
596  Html::rawElement( 'p', [], $languageLinks )
597  );
598  }
599 
600  $benefitsContainer = '';
601  if ( $this->isSignup() && $this->showExtraInformation() ) {
602  // messages used:
603  // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
604  // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
605  // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
606  $benefitCount = 3;
607  $benefitList = '';
608  for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
609  $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
610  $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->text();
611  $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
612  Html::rawElement( 'h3', [],
613  $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
614  )
615  . Html::rawElement( 'p', [],
616  $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
617  )
618  );
619  }
620  $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
621  Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
622  . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
623  $benefitList
624  )
625  );
626  }
627 
628  $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
629  $loginPrompt
630  . $languageLinks
631  . $signupStart
632  . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
633  $formHtml
634  )
635  . $benefitsContainer
636  );
637 
638  return $html;
639  }
640 
649  protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
650  global $wgSecureLogin;
651  // FIXME merge this with parent
652 
653  if ( isset( $this->authForm ) ) {
654  return $this->authForm;
655  }
656 
657  $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
658 
659  // get basic form description from the auth logic
660  $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
661  // this will call onAuthChangeFormFields()
662  $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
663  $this->postProcessFormDescriptor( $formDescriptor, $requests );
664 
665  $context = $this->getContext();
666  if ( $context->getRequest() !== $this->getRequest() ) {
667  // We have overridden the request, need to make sure the form uses that too.
668  $context = new DerivativeContext( $this->getContext() );
669  $context->setRequest( $this->getRequest() );
670  }
671  $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
672 
673  $form->addHiddenField( 'authAction', $this->authAction );
674  if ( $this->mLanguage ) {
675  $form->addHiddenField( 'uselang', $this->mLanguage );
676  }
677  $form->addHiddenField( 'force', $this->securityLevel );
678  $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
679  if ( $wgSecureLogin ) {
680  // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
681  if ( !$this->isSignup() ) {
682  $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
683  $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
684  }
685  }
686 
687  // set properties of the form itself
688  $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
689  $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
690  if ( $this->isSignup() ) {
691  $form->setId( 'userlogin2' );
692  }
693 
694  $form->suppressDefaultSubmit();
695 
696  $this->authForm = $form;
697 
698  return $form;
699  }
700 
701  public function onAuthChangeFormFields(
702  array $requests, array $fieldInfo, array &$formDescriptor, $action
703  ) {
704  $coreFieldDescriptors = $this->getFieldDefinitions();
705 
706  // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
707  foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
708  $requestField = $formDescriptor[$fieldName] ?? [];
709 
710  // remove everything that is not in the fieldinfo, is not marked as a supplemental field
711  // to something in the fieldinfo, and is not an info field or a submit button
712  if (
713  !isset( $fieldInfo[$fieldName] )
714  && (
715  !isset( $coreField['baseField'] )
716  || !isset( $fieldInfo[$coreField['baseField']] )
717  )
718  && (
719  !isset( $coreField['type'] )
720  || !in_array( $coreField['type'], [ 'submit', 'info' ], true )
721  )
722  ) {
723  $coreFieldDescriptors[$fieldName] = null;
724  continue;
725  }
726 
727  // core message labels should always take priority
728  if (
729  isset( $coreField['label'] )
730  || isset( $coreField['label-message'] )
731  || isset( $coreField['label-raw'] )
732  ) {
733  unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
734  }
735 
736  $coreFieldDescriptors[$fieldName] += $requestField;
737  }
738 
739  $formDescriptor = array_filter( $coreFieldDescriptors + $formDescriptor );
740  return true;
741  }
742 
749  protected function showExtraInformation() {
750  return $this->authAction !== $this->getContinueAction( $this->authAction )
752  }
753 
758  protected function getFieldDefinitions() {
759  global $wgEmailConfirmToEdit;
760 
761  $isLoggedIn = $this->getUser()->isLoggedIn();
762  $continuePart = $this->isContinued() ? 'continue-' : '';
763  $anotherPart = $isLoggedIn ? 'another-' : '';
764  $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
765  $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
766  $secureLoginLink = '';
767  if ( $this->mSecureLoginUrl ) {
768  $secureLoginLink = Html::element( 'a', [
769  'href' => $this->mSecureLoginUrl,
770  'class' => 'mw-ui-flush-right mw-secure',
771  ], $this->msg( 'userlogin-signwithsecure' )->text() );
772  }
773  $usernameHelpLink = '';
774  if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
775  $usernameHelpLink = Html::rawElement( 'span', [
776  'class' => 'mw-ui-flush-right',
777  ], $this->msg( 'createacct-helpusername' )->parse() );
778  }
779 
780  if ( $this->isSignup() ) {
781  $fieldDefinitions = [
782  'statusarea' => [
783  // used by the mediawiki.special.userlogin.signup.js module for error display
784  // FIXME merge this with HTMLForm's normal status (error) area
785  'type' => 'info',
786  'raw' => true,
787  'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
788  'weight' => -105,
789  ],
790  'username' => [
791  'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
792  'id' => 'wpName2',
793  'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
794  : 'userlogin-yourname-ph',
795  ],
796  'mailpassword' => [
797  // create account without providing password, a temporary one will be mailed
798  'type' => 'check',
799  'label-message' => 'createaccountmail',
800  'name' => 'wpCreateaccountMail',
801  'id' => 'wpCreateaccountMail',
802  ],
803  'password' => [
804  'id' => 'wpPassword2',
805  'placeholder-message' => 'createacct-yourpassword-ph',
806  'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
807  ],
808  'domain' => [],
809  'retype' => [
810  'baseField' => 'password',
811  'type' => 'password',
812  'label-message' => 'createacct-yourpasswordagain',
813  'id' => 'wpRetype',
814  'cssclass' => 'loginPassword',
815  'size' => 20,
816  'validation-callback' => function ( $value, $alldata ) {
817  if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
818  if ( !$value ) {
819  return $this->msg( 'htmlform-required' );
820  } elseif ( $value !== $alldata['password'] ) {
821  return $this->msg( 'badretype' );
822  }
823  }
824  return true;
825  },
826  'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
827  'placeholder-message' => 'createacct-yourpasswordagain-ph',
828  ],
829  'email' => [
830  'type' => 'email',
831  'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
832  : 'createacct-emailoptional',
833  'id' => 'wpEmail',
834  'cssclass' => 'loginText',
835  'size' => '20',
836  // FIXME will break non-standard providers
837  'required' => $wgEmailConfirmToEdit,
838  'validation-callback' => function ( $value, $alldata ) {
839  global $wgEmailConfirmToEdit;
840 
841  // AuthManager will check most of these, but that will make the auth
842  // session fail and this won't, so nicer to do it this way
843  if ( !$value && $wgEmailConfirmToEdit ) {
844  // no point in allowing registration without email when email is
845  // required to edit
846  return $this->msg( 'noemailtitle' );
847  } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
848  // cannot send password via email when there is no email address
849  return $this->msg( 'noemailcreate' );
850  } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
851  return $this->msg( 'invalidemailaddress' );
852  }
853  return true;
854  },
855  'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
856  ],
857  'realname' => [
858  'type' => 'text',
859  'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
860  : 'prefs-help-realname',
861  'label-message' => 'createacct-realname',
862  'cssclass' => 'loginText',
863  'size' => 20,
864  'id' => 'wpRealName',
865  ],
866  'reason' => [
867  // comment for the user creation log
868  'type' => 'text',
869  'label-message' => 'createacct-reason',
870  'cssclass' => 'loginText',
871  'id' => 'wpReason',
872  'size' => '20',
873  'placeholder-message' => 'createacct-reason-ph',
874  ],
875  'createaccount' => [
876  // submit button
877  'type' => 'submit',
878  'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
879  'submit' )->text(),
880  'name' => 'wpCreateaccount',
881  'id' => 'wpCreateaccount',
882  'weight' => 100,
883  ],
884  ];
885  } else {
886  $fieldDefinitions = [
887  'username' => [
888  'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
889  'id' => 'wpName1',
890  'placeholder-message' => 'userlogin-yourname-ph',
891  ],
892  'password' => [
893  'id' => 'wpPassword1',
894  'placeholder-message' => 'userlogin-yourpassword-ph',
895  ],
896  'domain' => [],
897  'rememberMe' => [
898  // option for saving the user token to a cookie
899  'type' => 'check',
900  'name' => 'wpRemember',
901  'label-message' => $this->msg( 'userlogin-remembermypassword' )
902  ->numParams( $expirationDays ),
903  'id' => 'wpRemember',
904  ],
905  'loginattempt' => [
906  // submit button
907  'type' => 'submit',
908  'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
909  'id' => 'wpLoginAttempt',
910  'weight' => 100,
911  ],
912  'linkcontainer' => [
913  // help link
914  'type' => 'info',
915  'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
916  // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
917  'raw' => true,
918  'default' => Html::element( 'a', [
919  'href' => Skin::makeInternalOrExternalUrl( $this->msg( 'helplogin-url' )
920  ->inContentLanguage()
921  ->text() ),
922  ], $this->msg( 'userlogin-helplink2' )->text() ),
923  'weight' => 200,
924  ],
925  // button for ResetPasswordSecondaryAuthenticationProvider
926  'skipReset' => [
927  'weight' => 110,
928  'flags' => [],
929  ],
930  ];
931  }
932 
933  $fieldDefinitions['username'] += [
934  'type' => 'text',
935  'name' => 'wpName',
936  'cssclass' => 'loginText',
937  'size' => 20,
938  // 'required' => true,
939  ];
940  $fieldDefinitions['password'] += [
941  'type' => 'password',
942  // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
943  'name' => 'wpPassword',
944  'cssclass' => 'loginPassword',
945  'size' => 20,
946  // 'required' => true,
947  ];
948 
949  if ( $this->mEntryError ) {
950  $fieldDefinitions['entryError'] = [
951  'type' => 'info',
952  'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
953  $this->mEntryError ),
954  'raw' => true,
955  'rawrow' => true,
956  'weight' => -100,
957  ];
958  }
959  if ( !$this->showExtraInformation() ) {
960  unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
961  }
962  if ( $this->isSignup() && $this->showExtraInformation() ) {
963  // blank signup footer for site customization
964  // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
965  $signupendMsg = $this->msg( 'signupend' );
966  $signupendHttpsMsg = $this->msg( 'signupend-https' );
967  if ( !$signupendMsg->isDisabled() ) {
968  $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
969  $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
970  ? $signupendHttpsMsg->parse() : $signupendMsg->parse();
971  $fieldDefinitions['signupend'] = [
972  'type' => 'info',
973  'raw' => true,
974  'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
975  'weight' => 225,
976  ];
977  }
978  }
979  if ( !$this->isSignup() && $this->showExtraInformation() ) {
980  $passwordReset = new PasswordReset( $this->getConfig(), AuthManager::singleton() );
981  if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
982  $fieldDefinitions['passwordReset'] = [
983  'type' => 'info',
984  'raw' => true,
985  'cssclass' => 'mw-form-related-link-container',
986  'default' => $this->getLinkRenderer()->makeLink(
987  SpecialPage::getTitleFor( 'PasswordReset' ),
988  $this->msg( 'userlogin-resetpassword-link' )->text()
989  ),
990  'weight' => 230,
991  ];
992  }
993 
994  // Don't show a "create account" link if the user can't.
995  if ( $this->showCreateAccountLink() ) {
996  // link to the other action
997  $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' : 'CreateAccount' );
998  $linkq = $this->getReturnToQueryStringFragment();
999  // Pass any language selection on to the mode switch link
1000  if ( $this->mLanguage ) {
1001  $linkq .= '&uselang=' . urlencode( $this->mLanguage );
1002  }
1003  $loggedIn = $this->getUser()->isLoggedIn();
1004 
1005  $fieldDefinitions['createOrLogin'] = [
1006  'type' => 'info',
1007  'raw' => true,
1008  'linkQuery' => $linkq,
1009  'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1010  return Html::rawElement( 'div',
1011  [ 'id' => 'mw-createaccount' . ( !$loggedIn ? '-cta' : '' ),
1012  'class' => ( $loggedIn ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1013  ( $loggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1014  . Html::element( 'a',
1015  [
1016  'id' => 'mw-createaccount-join' . ( $loggedIn ? '-loggedin' : '' ),
1017  'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1018  'class' => ( $loggedIn ? '' : 'mw-ui-button' ),
1019  'tabindex' => 100,
1020  ],
1021  $this->msg(
1022  $loggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1023  )->text()
1024  )
1025  );
1026  },
1027  'weight' => 235,
1028  ];
1029  }
1030  }
1031 
1032  return $fieldDefinitions;
1033  }
1034 
1044  protected function hasSessionCookie() {
1046 
1047  return $wgDisableCookieCheck || (
1048  $wgInitialSessionId &&
1049  $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1050  );
1051  }
1052 
1058  protected function getReturnToQueryStringFragment() {
1059  $returnto = '';
1060  if ( $this->mReturnTo !== '' ) {
1061  $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1062  if ( $this->mReturnToQuery !== '' ) {
1063  $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1064  }
1065  }
1066  return $returnto;
1067  }
1068 
1074  private function showCreateAccountLink() {
1075  if ( $this->isSignup() ) {
1076  return true;
1077  } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1078  return true;
1079  } else {
1080  return false;
1081  }
1082  }
1083 
1084  protected function getTokenName() {
1085  return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1086  }
1087 
1094  protected function makeLanguageSelector() {
1095  $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1096  if ( $msg->isBlank() ) {
1097  return '';
1098  }
1099  $langs = explode( "\n", $msg->text() );
1100  $links = [];
1101  foreach ( $langs as $lang ) {
1102  $lang = trim( $lang, '* ' );
1103  $parts = explode( '|', $lang );
1104  if ( count( $parts ) >= 2 ) {
1105  $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1106  }
1107  }
1108 
1109  return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1110  $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1111  }
1112 
1121  protected function makeLanguageSelectorLink( $text, $lang ) {
1122  if ( $this->getLanguage()->getCode() == $lang ) {
1123  // no link for currently used language
1124  return htmlspecialchars( $text );
1125  }
1126  $query = [ 'uselang' => $lang ];
1127  if ( $this->mReturnTo !== '' ) {
1128  $query['returnto'] = $this->mReturnTo;
1129  $query['returntoquery'] = $this->mReturnToQuery;
1130  }
1131 
1132  $attr = [];
1133  $targetLanguage = Language::factory( $lang );
1134  $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1135 
1136  return $this->getLinkRenderer()->makeKnownLink(
1137  $this->getPageTitle(),
1138  $text,
1139  $attr,
1140  $query
1141  );
1142  }
1143 
1144  protected function getGroupName() {
1145  return 'login';
1146  }
1147 
1153  // Pre-fill username (if not creating an account, T46775).
1154  if (
1155  isset( $formDescriptor['username'] ) &&
1156  !isset( $formDescriptor['username']['default'] ) &&
1157  !$this->isSignup()
1158  ) {
1159  $user = $this->getUser();
1160  if ( $user->isLoggedIn() ) {
1161  $formDescriptor['username']['default'] = $user->getName();
1162  } else {
1163  $formDescriptor['username']['default'] =
1164  $this->getRequest()->getSession()->suggestLoginUsername();
1165  }
1166  }
1167 
1168  // don't show a submit button if there is nothing to submit (i.e. the only form content
1169  // is other submit buttons, for redirect flows)
1170  if ( !$this->needsSubmitButton( $requests ) ) {
1171  unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1172  }
1173 
1174  if ( !$this->isSignup() ) {
1175  // FIXME HACK don't focus on non-empty field
1176  // maybe there should be an autofocus-if similar to hide-if?
1177  if (
1178  isset( $formDescriptor['username'] )
1179  && empty( $formDescriptor['username']['default'] )
1180  && !$this->getRequest()->getCheck( 'wpName' )
1181  ) {
1182  $formDescriptor['username']['autofocus'] = true;
1183  } elseif ( isset( $formDescriptor['password'] ) ) {
1184  $formDescriptor['password']['autofocus'] = true;
1185  }
1186  }
1187 
1188  $this->addTabIndex( $formDescriptor );
1189  }
1190 }
$wgInitialSessionId
Definition: Setup.php:834
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))
setSessionUserForCurrentRequest()
Replace some globals to make sure the fact that the user has just been logged in is reflected in the ...
loadAuth( $subPage, $authAction=null, $reset=false)
Load or initialize $authAction, $authRequests and $subPage.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1996
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:785
showReturnToPage( $type, $returnTo='', $returnToQuery='', $stickHTTPS=false)
Add a "return to" link or redirect to it.
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1599
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:232
A special page subclass for authentication-related special pages.
getContext()
Gets the context this SpecialPage is executed in.
$success
loadRequestParameters( $subPage)
Load basic request parameters for this Special page.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
mainLoginForm(array $requests, $msg='', $msgtype='error')
needsSubmitButton(array $requests)
Returns true if the form built from the given AuthenticationRequests needs a submit button...
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:2075
makeLanguageSelector()
Produce a bar of links which allow the user to select another language during login/registration but ...
if(!isset( $args[0])) $lang
logAuthResult( $success, $status=null)
Logs to the authmanager-stats channel.
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1277
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
An IContextSource implementation which will inherit context from another source but allow individual ...
getPreservedParams( $withToken=false)
hasSessionCookie()
Check if a session cookie is present.
$wgSecureLogin
This is to let user authenticate using https when they come from http.
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
getToken()
Returns the CSRF token.
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 MediaWikiServices
Definition: injection.txt:23
$wgEmailConfirmToEdit
Should editors be required to have a validated e-mail address before being allowed to edit...
User $targetUser
FIXME another flag for passing data.
getOutput()
Get the OutputPage being used for this instance.
successfulAction( $direct=false, $extraMessages=null)
this hook is for auditing only $response
Definition: hooks.txt:785
static factory( $displayFormat)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:284
Holds shared logic for login and account creation pages.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1813
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
showExtraInformation()
Show extra information such as password recovery information, link from login to signup, CTA etc? Such information should only be shown on the "landing page", ie.
static validateEmail( $addr)
Does a string look like an e-mail address?
Definition: Sanitizer.php:2124
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1996
getPageHtml( $formHtml)
Add page elements which are outside the form.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
getContinueAction( $action)
Gets the _CONTINUE version of an action.
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
$wgLoginLanguageSelector
Show a bar of language selection links in the user login and user registration forms; edit the "login...
getDefaultAction( $subPage)
Get the default action for this special page, if none is given via URL/POST data. ...
showSuccessPage( $type, $title, $msgname, $injected_html, $extraMessages)
Show the success page.
const PROTO_HTTPS
Definition: Defines.php:220
isContinued()
Returns true if this is not the first step of the authentication.
setContext( $context)
Sets the context this SpecialPage is executed in.
isActionAllowed( $action)
Checks whether AuthManager is ready to perform the action.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
$wgLang
Definition: Setup.php:902
static getMain()
Get the RequestContext object associated with the main request.
canBypassForm(&$button_name)
Determine if the login form can be bypassed.
addTabIndex(&$formDescriptor)
Adds a sequential tabindex starting from 1 to all form elements.
An error page which can definitely be safely rendered using the OutputPage.
$wgDisableCookieCheck
By default, MediaWiki checks if the client supports cookies during the login process, so that it can display an informative error message if cookies are disabled.
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
load( $subPage)
Load data from request.
$params
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes! ...
$wgUseMediaWikiUIEverywhere
Temporary variable that applies MediaWiki UI wherever it can be supported.
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:278
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:936
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:214
Helper functions for the login form that need to be shared with other special pages (such as CentralA...
Definition: LoginHelper.php:8
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:82
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:785
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
Helper class for the password reset functionality shared by the web UI and the API.
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:55
getFieldDefinitions()
Create a HTMLForm descriptor for the core login fields.
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
setRequest(array $data, $wasPosted=null)
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
getName()
Get the name of this Special Page.
getAuthForm(array $requests, $action, $msg='', $msgType='error')
Generates a form from the given request.
bool $proxyAccountCreation
True if the user if creating an account for someone else.
getUser()
Shortcut to get the User executing this instance.
getConfig()
Shortcut to get main config object.
static getValidErrorMessages()
Returns an array of all valid error messages.
Definition: LoginHelper.php:36
getLanguage()
Shortcut to get user&#39;s language.
msg( $key)
Wrapper around wfMessage that sets the current context.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2626
postProcessFormDescriptor(&$formDescriptor, $requests)
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
getFullTitle()
Return the full title, including $par.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:276
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS...
static makeInternalOrExternalUrl( $name)
If url string starts with http, consider as external URL, else internal.
Definition: Skin.php:1198
checkPermissions()
Checks if userCanExecute, and if not throws a PermissionsError.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:585
showCreateAccountLink()
Whether the login/create account form should display a link to the other form (in addition to whateve...
string $subPage
Subpage of the special page.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2626
getPageTitle( $subpage=false)
Get a self-referential title object.
makeLanguageSelectorLink( $text, $lang)
Create a language selector link for a particular language Links back to this page preserving type and...
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1487
getReturnToQueryStringFragment()
Returns a string that can be appended to the URL (without encoding) to preserve the return target...
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:280
trySubmit()
Attempts to do an authentication step with the submitted data.