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