/**
  * @param string|null $subPage
  */
 public function execute($subPage)
 {
     $authManager = AuthManager::singleton();
     $session = SessionManager::getGlobalSession();
     // Session data is used for various things in the authentication process, so we must make
     // sure a session cookie or some equivalent mechanism is set.
     $session->persist();
     $this->load($subPage);
     $this->setHeaders();
     $this->checkPermissions();
     // Make sure it's possible to log in
     if (!$this->isSignup() && !$session->canSetUser()) {
         throw new ErrorPageError('cannotloginnow-title', 'cannotloginnow-text', [$session->getProvider()->describe(RequestContext::getMain()->getLanguage())]);
     }
     /*
      * In the case where the user is already logged in, and was redirected to
      * the login form from a page that requires login, do not show the login
      * page. The use case scenario for this is when a user opens a large number
      * of tabs, is redirected to the login page on all of them, and then logs
      * in on one, expecting all the others to work properly.
      *
      * However, do show the form if it was visited intentionally (no 'returnto'
      * is present). People who often switch between several accounts have grown
      * accustomed to this behavior.
      *
      * Also make an exception when force=<level> is set in the URL, which means the user must
      * reauthenticate for security reasons.
      */
     if (!$this->isSignup() && !$this->mPosted && !$this->securityLevel && ($this->mReturnTo !== '' || $this->mReturnToQuery !== '') && $this->getUser()->isLoggedIn()) {
         $this->successfulAction();
     }
     // If logging in and not on HTTPS, either redirect to it or offer a link.
     global $wgSecureLogin;
     if ($this->getRequest()->getProtocol() !== 'https') {
         $title = $this->getFullTitle();
         $query = $this->getPreservedParams(false) + ['title' => null, $this->mEntryErrorType === 'error' ? 'error' : 'warning' => $this->mEntryError] + $this->getRequest()->getQueryValues();
         $url = $title->getFullURL($query, false, PROTO_HTTPS);
         if ($wgSecureLogin && !$this->mFromHTTP && wfCanIPUseHTTPS($this->getRequest()->getIP())) {
             // Avoid infinite redirect
             $url = wfAppendQuery($url, 'fromhttp=1');
             $this->getOutput()->redirect($url);
             // Since we only do this redir to change proto, always vary
             $this->getOutput()->addVaryHeader('X-Forwarded-Proto');
             return;
         } else {
             // A wiki without HTTPS login support should set $wgServer to
             // http://somehost, in which case the secure URL generated
             // above won't actually start with https://
             if (substr($url, 0, 8) === 'https://') {
                 $this->mSecureLoginUrl = $url;
             }
         }
     }
     if (!$this->isActionAllowed($this->authAction)) {
         // FIXME how do we explain this to the user? can we handle session loss better?
         // messages used: authpage-cannot-login, authpage-cannot-login-continue,
         // authpage-cannot-create, authpage-cannot-create-continue
         $this->mainLoginForm([], 'authpage-cannot-' . $this->authAction);
         return;
     }
     $status = $this->trySubmit();
     if (!$status || !$status->isGood()) {
         $this->mainLoginForm($this->authRequests, $status ? $status->getMessage() : '', 'error');
         return;
     }
     /** @var AuthenticationResponse $response */
     $response = $status->getValue();
     $returnToUrl = $this->getPageTitle('return')->getFullURL($this->getPreservedParams(true), false, PROTO_HTTPS);
     switch ($response->status) {
         case AuthenticationResponse::PASS:
             $this->logAuthResult(true);
             $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
             $this->targetUser = User::newFromName($response->username);
             if (!$this->proxyAccountCreation && $response->loginRequest && $authManager->canAuthenticateNow()) {
                 // successful registration; log the user in instantly
                 $response2 = $authManager->beginAuthentication([$response->loginRequest], $returnToUrl);
                 if ($response2->status !== AuthenticationResponse::PASS) {
                     LoggerFactory::getInstance('login')->error('Could not log in after account creation');
                     $this->successfulAction(true, Status::newFatal('createacct-loginerror'));
                     break;
                 }
             }
             if (!$this->proxyAccountCreation) {
                 // Ensure that the context user is the same as the session user.
                 $this->setSessionUserForCurrentRequest();
             }
             $this->successfulAction(true);
             break;
         case AuthenticationResponse::FAIL:
             // fall through
         // fall through
         case AuthenticationResponse::RESTART:
             unset($this->authForm);
             if ($response->status === AuthenticationResponse::FAIL) {
                 $action = $this->getDefaultAction($subPage);
                 $messageType = 'error';
             } else {
                 $action = $this->getContinueAction($this->authAction);
                 $messageType = 'warning';
             }
             $this->logAuthResult(false, $response->message ? $response->message->getKey() : '-');
             $this->loadAuth($subPage, $action, true);
             $this->mainLoginForm($this->authRequests, $response->message, $messageType);
             break;
         case AuthenticationResponse::REDIRECT:
             unset($this->authForm);
             $this->getOutput()->redirect($response->redirectTarget);
             break;
         case AuthenticationResponse::UI:
             unset($this->authForm);
             $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE : AuthManager::ACTION_LOGIN_CONTINUE;
             $this->authRequests = $response->neededRequests;
             $this->mainLoginForm($response->neededRequests, $response->message, 'warning');
             break;
         default:
             throw new LogicException('invalid AuthenticationResponse');
     }
 }
Ejemplo n.º 2
0
	/**
	 * @param $user User
	 * @param $context IContextSource
	 * @param $defaultPreferences
	 * @return void
	 */
	static function profilePreferences( $user, IContextSource $context, &$defaultPreferences ) {
		global $wgAuth, $wgContLang, $wgParser, $wgCookieExpiration, $wgLanguageCode,
			$wgDisableTitleConversion, $wgDisableLangConversion, $wgMaxSigChars,
			$wgEnableEmail, $wgEmailConfirmToEdit, $wgEnableUserEmail, $wgEmailAuthentication,
			$wgEnotifWatchlist, $wgEnotifUserTalk, $wgEnotifRevealEditorAddress,
			$wgSecureLogin;

		// retrieving user name for GENDER and misc.
		$userName = $user->getName();

		## User info #####################################
		// Information panel
		$defaultPreferences['username'] = array(
			'type' => 'info',
			'label-message' => array( 'username', $userName ),
			'default' => $userName,
			'section' => 'personal/info',
		);

		$defaultPreferences['userid'] = array(
			'type' => 'info',
			'label-message' => array( 'uid', $userName ),
			'default' => $user->getId(),
			'section' => 'personal/info',
		);

		# Get groups to which the user belongs
		$userEffectiveGroups = $user->getEffectiveGroups();
		$userGroups = $userMembers = array();
		foreach ( $userEffectiveGroups as $ueg ) {
			if ( $ueg == '*' ) {
				// Skip the default * group, seems useless here
				continue;
			}
			$groupName = User::getGroupName( $ueg );
			$userGroups[] = User::makeGroupLinkHTML( $ueg, $groupName );

			$memberName = User::getGroupMember( $ueg, $userName );
			$userMembers[] = User::makeGroupLinkHTML( $ueg, $memberName );
		}
		asort( $userGroups );
		asort( $userMembers );

		$lang = $context->getLanguage();

		$defaultPreferences['usergroups'] = array(
			'type' => 'info',
			'label' => $context->msg( 'prefs-memberingroups' )->numParams(
				count( $userGroups ) )->params( $userName )->parse(),
			'default' => $context->msg( 'prefs-memberingroups-type',
				$lang->commaList( $userGroups ),
				$lang->commaList( $userMembers )
			)->plain(),
			'raw' => true,
			'section' => 'personal/info',
		);

		$editCount = Linker::link( SpecialPage::getTitleFor( "Contributions", $userName ),
			$lang->formatNum( $user->getEditCount() ) );

		$defaultPreferences['editcount'] = array(
			'type' => 'info',
			'raw' => true,
			'label-message' => 'prefs-edits',
			'default' => $editCount,
			'section' => 'personal/info',
		);

		if ( $user->getRegistration() ) {
			$displayUser = $context->getUser();
			$userRegistration = $user->getRegistration();
			$defaultPreferences['registrationdate'] = array(
				'type' => 'info',
				'label-message' => 'prefs-registration',
				'default' => $context->msg(
					'prefs-registration-date-time',
					$lang->userTimeAndDate( $userRegistration, $displayUser ),
					$lang->userDate( $userRegistration, $displayUser ),
					$lang->userTime( $userRegistration, $displayUser )
				)->parse(),
				'section' => 'personal/info',
			);
		}

		$canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
		$canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );

		// Actually changeable stuff
		$defaultPreferences['realname'] = array(
			// (not really "private", but still shouldn't be edited without permission)
			'type' => $canEditPrivateInfo && $wgAuth->allowPropChange( 'realname' ) ? 'text' : 'info',
			'default' => $user->getRealName(),
			'section' => 'personal/info',
			'label-message' => 'yourrealname',
			'help-message' => 'prefs-help-realname',
		);

		if ( $canEditPrivateInfo && $wgAuth->allowPasswordChange() ) {
			$link = Linker::link( SpecialPage::getTitleFor( 'ChangePassword' ),
				$context->msg( 'prefs-resetpass' )->escaped(), array(),
				array( 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ) );

			$defaultPreferences['password'] = array(
				'type' => 'info',
				'raw' => true,
				'default' => $link,
				'label-message' => 'yourpassword',
				'section' => 'personal/info',
			);
		}
		if ( $wgCookieExpiration > 0 ) {
			$defaultPreferences['rememberpassword'] = array(
				'type' => 'toggle',
				'label' => $context->msg( 'tog-rememberpassword' )->numParams(
					ceil( $wgCookieExpiration / ( 3600 * 24 ) ) )->text(),
				'section' => 'personal/info',
			);
		}
		// Only show preferhttps if secure login is turned on
		if ( $wgSecureLogin && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
			$defaultPreferences['prefershttps'] = array(
				'type' => 'toggle',
				'label-message' => 'tog-prefershttps',
				'help-message' => 'prefs-help-prefershttps',
				'section' => 'personal/info'
			);
		}

		// Language
		$languages = Language::fetchLanguageNames( null, 'mw' );
		if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
			$languages[$wgLanguageCode] = $wgLanguageCode;
		}
		ksort( $languages );

		$options = array();
		foreach ( $languages as $code => $name ) {
			$display = wfBCP47( $code ) . ' - ' . $name;
			$options[$display] = $code;
		}
		$defaultPreferences['language'] = array(
			'type' => 'select',
			'section' => 'personal/i18n',
			'options' => $options,
			'label-message' => 'yourlanguage',
		);

		$defaultPreferences['gender'] = array(
			'type' => 'radio',
			'section' => 'personal/i18n',
			'options' => array(
				$context->msg( 'parentheses',
					$context->msg( 'gender-unknown' )->text()
				)->text() => 'unknown',
				$context->msg( 'gender-female' )->text() => 'female',
				$context->msg( 'gender-male' )->text() => 'male',
			),
			'label-message' => 'yourgender',
			'help-message' => 'prefs-help-gender',
		);

		// see if there are multiple language variants to choose from
		if ( !$wgDisableLangConversion ) {
			foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
				if ( $langCode == $wgContLang->getCode() ) {
					$variants = $wgContLang->getVariants();

					if ( count( $variants ) <= 1 ) {
						continue;
					}

					$variantArray = array();
					foreach ( $variants as $v ) {
						$v = str_replace( '_', '-', strtolower( $v ) );
						$variantArray[$v] = $lang->getVariantname( $v, false );
					}

					$options = array();
					foreach ( $variantArray as $code => $name ) {
						$display = wfBCP47( $code ) . ' - ' . $name;
						$options[$display] = $code;
					}

					$defaultPreferences['variant'] = array(
						'label-message' => 'yourvariant',
						'type' => 'select',
						'options' => $options,
						'section' => 'personal/i18n',
						'help-message' => 'prefs-help-variant',
					);

					if ( !$wgDisableTitleConversion ) {
						$defaultPreferences['noconvertlink'] = array(
							'type' => 'toggle',
							'section' => 'personal/i18n',
							'label-message' => 'tog-noconvertlink',
						);
					}
				} else {
					$defaultPreferences["variant-$langCode"] = array(
						'type' => 'api',
					);
				}
			}
		}

		// Stuff from Language::getExtraUserToggles()
		// FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
		$toggles = $wgContLang->getExtraUserToggles();

		foreach ( $toggles as $toggle ) {
			$defaultPreferences[$toggle] = array(
				'type' => 'toggle',
				'section' => 'personal/i18n',
				'label-message' => "tog-$toggle",
			);
		}

		// show a preview of the old signature first
		$oldsigWikiText = $wgParser->preSaveTransform( "~~~", $context->getTitle(), $user, ParserOptions::newFromContext( $context ) );
		$oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
		$defaultPreferences['oldsig'] = array(
			'type' => 'info',
			'raw' => true,
			'label-message' => 'tog-oldsig',
			'default' => $oldsigHTML,
			'section' => 'personal/signature',
		);
		$defaultPreferences['nickname'] = array(
			'type' => $wgAuth->allowPropChange( 'nickname' ) ? 'text' : 'info',
			'maxlength' => $wgMaxSigChars,
			'label-message' => 'yournick',
			'validation-callback' => array( 'Preferences', 'validateSignature' ),
			'section' => 'personal/signature',
			'filter-callback' => array( 'Preferences', 'cleanSignature' ),
		);
		$defaultPreferences['fancysig'] = array(
			'type' => 'toggle',
			'label-message' => 'tog-fancysig',
			'help-message' => 'prefs-help-signature', // show general help about signature at the bottom of the section
			'section' => 'personal/signature'
		);

		## Email stuff

		if ( $wgEnableEmail ) {
			if ( $canViewPrivateInfo ) {
				$helpMessages[] = $wgEmailConfirmToEdit
						? 'prefs-help-email-required'
						: 'prefs-help-email';

				if ( $wgEnableUserEmail ) {
					// additional messages when users can send email to each other
					$helpMessages[] = 'prefs-help-email-others';
				}

				$emailAddress = $user->getEmail() ? htmlspecialchars( $user->getEmail() ) : '';
				if ( $canEditPrivateInfo && $wgAuth->allowPropChange( 'emailaddress' ) ) {
					$link = Linker::link(
						SpecialPage::getTitleFor( 'ChangeEmail' ),
						$context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->escaped(),
						array(),
						array( 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ) );

					$emailAddress .= $emailAddress == '' ? $link : (
						$context->msg( 'word-separator' )->plain()
						. $context->msg( 'parentheses' )->rawParams( $link )->plain()
					);
				}

				$defaultPreferences['emailaddress'] = array(
					'type' => 'info',
					'raw' => true,
					'default' => $emailAddress,
					'label-message' => 'youremail',
					'section' => 'personal/email',
					'help-messages' => $helpMessages,
					# 'cssclass' chosen below
				);
			}

			$disableEmailPrefs = false;

			if ( $wgEmailAuthentication ) {
				$emailauthenticationclass = 'mw-email-not-authenticated';
				if ( $user->getEmail() ) {
					if ( $user->getEmailAuthenticationTimestamp() ) {
						// date and time are separate parameters to facilitate localisation.
						// $time is kept for backward compat reasons.
						// 'emailauthenticated' is also used in SpecialConfirmemail.php
						$displayUser = $context->getUser();
						$emailTimestamp = $user->getEmailAuthenticationTimestamp();
						$time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
						$d = $lang->userDate( $emailTimestamp, $displayUser );
						$t = $lang->userTime( $emailTimestamp, $displayUser );
						$emailauthenticated = $context->msg( 'emailauthenticated',
							$time, $d, $t )->parse() . '<br />';
						$disableEmailPrefs = false;
						$emailauthenticationclass = 'mw-email-authenticated';
					} else {
						$disableEmailPrefs = true;
						$emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
							Linker::linkKnown(
								SpecialPage::getTitleFor( 'Confirmemail' ),
								$context->msg( 'emailconfirmlink' )->escaped()
							) . '<br />';
						$emailauthenticationclass = "mw-email-not-authenticated";
					}
				} else {
					$disableEmailPrefs = true;
					$emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
					$emailauthenticationclass = 'mw-email-none';
				}

				if ( $canViewPrivateInfo ) {
					$defaultPreferences['emailauthentication'] = array(
						'type' => 'info',
						'raw' => true,
						'section' => 'personal/email',
						'label-message' => 'prefs-emailconfirm-label',
						'default' => $emailauthenticated,
						# Apply the same CSS class used on the input to the message:
						'cssclass' => $emailauthenticationclass,
					);
					$defaultPreferences['emailaddress']['cssclass'] = $emailauthenticationclass;
				}
			}

			if ( $wgEnableUserEmail && $user->isAllowed( 'sendemail' ) ) {
				$defaultPreferences['disablemail'] = array(
					'type' => 'toggle',
					'invert' => true,
					'section' => 'personal/email',
					'label-message' => 'allowemail',
					'disabled' => $disableEmailPrefs,
				);
				$defaultPreferences['ccmeonemails'] = array(
					'type' => 'toggle',
					'section' => 'personal/email',
					'label-message' => 'tog-ccmeonemails',
					'disabled' => $disableEmailPrefs,
				);
			}

			if ( $wgEnotifWatchlist ) {
				$defaultPreferences['enotifwatchlistpages'] = array(
					'type' => 'toggle',
					'section' => 'personal/email',
					'label-message' => 'tog-enotifwatchlistpages',
					'disabled' => $disableEmailPrefs,
				);
			}
			if ( $wgEnotifUserTalk ) {
				$defaultPreferences['enotifusertalkpages'] = array(
					'type' => 'toggle',
					'section' => 'personal/email',
					'label-message' => 'tog-enotifusertalkpages',
					'disabled' => $disableEmailPrefs,
				);
			}
			if ( $wgEnotifUserTalk || $wgEnotifWatchlist ) {
				$defaultPreferences['enotifminoredits'] = array(
					'type' => 'toggle',
					'section' => 'personal/email',
					'label-message' => 'tog-enotifminoredits',
					'disabled' => $disableEmailPrefs,
				);

				if ( $wgEnotifRevealEditorAddress ) {
					$defaultPreferences['enotifrevealaddr'] = array(
						'type' => 'toggle',
						'section' => 'personal/email',
						'label-message' => 'tog-enotifrevealaddr',
						'disabled' => $disableEmailPrefs,
					);
				}
			}
		}
	}
Ejemplo n.º 3
0
 /**
  * Determine based on the wiki configuration and the user's options,
  * whether this user must be over HTTPS no matter what.
  *
  * @return bool
  */
 public function requiresHTTPS()
 {
     global $wgSecureLogin;
     if (!$wgSecureLogin) {
         return false;
     } else {
         $https = $this->getBoolOption('prefershttps');
         Hooks::run('UserRequiresHTTPS', array($this, &$https));
         if ($https) {
             $https = wfCanIPUseHTTPS($this->getRequest()->getIP());
         }
         return $https;
     }
 }
Ejemplo n.º 4
0
 /**
  * @param string|null $subPage
  */
 public function execute($subPage)
 {
     if (session_id() == '') {
         wfSetupSession();
     }
     $this->load();
     // Check for [[Special:Userlogin/signup]]. This affects form display and
     // page title.
     if ($subPage == 'signup') {
         $this->mType = 'signup';
     }
     $this->setHeaders();
     // In the case where the user is already logged in, and was redirected to the login form from a
     // page that requires login, do not show the login page. The use case scenario for this is when
     // a user opens a large number of tabs, is redirected to the login page on all of them, and then
     // logs in on one, expecting all the others to work properly.
     //
     // However, do show the form if it was visited intentionally (no 'returnto' is present). People
     // who often switch between several accounts have grown accustomed to this behavior.
     if ($this->mType !== 'signup' && !$this->mPosted && $this->getUser()->isLoggedIn() && ($this->mReturnTo !== '' || $this->mReturnToQuery !== '')) {
         $this->successfulLogin();
     }
     // If logging in and not on HTTPS, either redirect to it or offer a link.
     global $wgSecureLogin;
     if ($this->mRequest->getProtocol() !== 'https') {
         $title = $this->getFullTitle();
         $query = array('returnto' => $this->mReturnTo !== '' ? $this->mReturnTo : null, 'returntoquery' => $this->mReturnToQuery !== '' ? $this->mReturnToQuery : null, 'title' => null, $this->mEntryErrorType === 'error' ? 'error' : 'warning' => $this->mEntryError) + $this->mRequest->getQueryValues();
         $url = $title->getFullURL($query, false, PROTO_HTTPS);
         if ($wgSecureLogin && wfCanIPUseHTTPS($this->getRequest()->getIP()) && !$this->mFromHTTP) {
             $url = wfAppendQuery($url, 'fromhttp=1');
             $this->getOutput()->redirect($url);
             // Since we only do this redir to change proto, always vary
             $this->getOutput()->addVaryHeader('X-Forwarded-Proto');
             return;
         } else {
             // A wiki without HTTPS login support should set $wgServer to
             // http://somehost, in which case the secure URL generated
             // above won't actually start with https://
             if (substr($url, 0, 8) === 'https://') {
                 $this->mSecureLoginUrl = $url;
             }
         }
     }
     if (!is_null($this->mCookieCheck)) {
         $this->onCookieRedirectCheck($this->mCookieCheck);
         return;
     } elseif ($this->mPosted) {
         if ($this->mCreateaccount) {
             $this->addNewAccount();
             return;
         } elseif ($this->mCreateaccountMail) {
             $this->addNewAccountMailPassword();
             return;
         } elseif ('submitlogin' == $this->mAction || $this->mLoginattempt) {
             $this->processLogin();
             return;
         }
     }
     $this->mainLoginForm($this->mEntryError, $this->mEntryErrorType);
 }
 /**
  * @param User $user
  * @param CentralAuthUser $centralUser
  * @param string $inject_html
  * @return bool
  */
 protected static function doCentralLoginRedirect(User $user, CentralAuthUser $centralUser, &$inject_html)
 {
     global $wgCentralAuthLoginWiki, $wgMemc, $wgSecureLogin;
     $context = RequestContext::getMain();
     $request = $context->getRequest();
     if (!$wgCentralAuthLoginWiki || defined('MW_API')) {
         // Mark the session to include edge login imgs on the next pageview
         $request->setSessionData('CentralAuthDoEdgeLogin', true);
         return true;
     }
     // Check that this is actually for a special login page view
     if ($context->getTitle()->isSpecial('Userlogin') && $request->wasPosted()) {
         // User will be redirected to Special:CentralLogin/start (central wiki),
         // then redirected back to Special:CentralLogin/complete (this wiki).
         // Sanity check that "returnto" is not one of the central login pages. If it
         // is, then clear the "returnto" options (LoginForm will use the main page).
         $returnTo = $request->getVal('returnto', '');
         $returnToQuery = $request->getVal('returntoquery', '');
         $returnToTitle = Title::newFromText($returnTo);
         if ($returnToTitle && $returnToTitle->isSpecial('CentralLogin')) {
             $returnTo = '';
             $returnToQuery = '';
         }
         // Determine the final protocol of page, after login
         $finalProto = $request->detectProtocol();
         $secureCookies = $finalProto === 'https';
         if ($wgSecureLogin) {
             $finalProto = 'http';
             if ($request->getBool('wpForceHttps', false) || $user->getBoolOption('prefershttps') && wfCanIPUseHTTPS($request->getIP())) {
                 $finalProto = 'https';
             }
             $secureCookies = $finalProto === 'https' && $user->getBoolOption('prefershttps');
         }
         // When POSTs triggered from Special:CentralLogin/start are sent back to
         // this wiki, the token will be checked to see if it was signed with this.
         // This is needed as Special:CentralLogin/start only takes a token argument
         // and we need to make sure an agent requesting such a URL actually initiated
         // the login request that spawned that token server-side.
         $secret = MWCryptRand::generateHex(32);
         $_SESSION['CentralAuth:autologin:current-attempt'] = array('secret' => $secret, 'remember' => $request->getCheck('wpRemember'), 'returnTo' => $returnTo, 'returnToQuery' => $returnToQuery, 'stickHTTPS' => $secureCookies, 'finalProto' => $finalProto, 'type' => $request->getText('type'));
         // Create a new token to pass to Special:CentralLogin/start (central wiki)
         $token = MWCryptRand::generateHex(32);
         $key = CentralAuthUser::memcKey('central-login-start-token', $token);
         $data = array('secret' => $secret, 'name' => $centralUser->getName(), 'guid' => $centralUser->getId(), 'wikiId' => wfWikiId(), 'secureCookies' => $secureCookies, 'finalProto' => $finalProto, 'currentProto' => $request->detectProtocol());
         Hooks::run('CentralAuthLoginRedirectData', array($centralUser, &$data));
         $wgMemc->set($key, $data, 60);
         $wiki = WikiMap::getWiki($wgCentralAuthLoginWiki);
         // Use WikiReference::getFullUrl(), returns a protocol-relative URL if needed
         $context->getOutput()->redirect(wfAppendQuery($wiki->getFullUrl('Special:CentralLogin/start'), "token={$token}"));
         // Set $inject_html to some text to bypass the LoginForm redirection
         $inject_html .= '<!-- do CentralAuth redirect -->';
     } else {
         // Mark the session to include edge login imgs on the next pageview
         $request->setSessionData('CentralAuthDoEdgeLogin', true);
     }
     return true;
 }
Ejemplo n.º 6
0
 public function execute($subPage)
 {
     if (session_id() == '') {
         wfSetupSession();
     }
     $this->load();
     // Check for [[Special:Userlogin/signup]]. This affects form display and
     // page title.
     if ($subPage == 'signup') {
         $this->mType = 'signup';
     }
     $this->setHeaders();
     // If logging in and not on HTTPS, either redirect to it or offer a link.
     global $wgSecureLogin;
     if ($this->mRequest->getProtocol() !== 'https') {
         $title = $this->getFullTitle();
         $query = array('returnto' => $this->mReturnTo, 'returntoquery' => $this->mReturnToQuery, 'title' => null) + $this->mRequest->getQueryValues();
         $url = $title->getFullURL($query, false, PROTO_HTTPS);
         if ($wgSecureLogin && wfCanIPUseHTTPS($this->getRequest()->getIP())) {
             $url = wfAppendQuery($url, 'fromhttp=1');
             $this->getOutput()->redirect($url);
             // Since we only do this redir to change proto, always vary
             $this->getOutput()->addVaryHeader('X-Forwarded-Proto');
             return;
         } else {
             // A wiki without HTTPS login support should set $wgServer to
             // http://somehost, in which case the secure URL generated
             // above won't actually start with https://
             if (substr($url, 0, 8) === 'https://') {
                 $this->mSecureLoginUrl = $url;
             }
         }
     }
     if (!is_null($this->mCookieCheck)) {
         $this->onCookieRedirectCheck($this->mCookieCheck);
         return;
     } elseif ($this->mPosted) {
         if ($this->mCreateaccount) {
             $this->addNewAccount();
             return;
         } elseif ($this->mCreateaccountMail) {
             $this->addNewAccountMailPassword();
             return;
         } elseif ('submitlogin' == $this->mAction || $this->mLoginattempt) {
             $this->processLogin();
             return;
         }
     }
     $this->mainLoginForm('');
 }
 /**
  * @param CentralAuthUser $centralUser
  * @param User $user
  * @return array
  */
 private function getCentralSession($centralUser, $user)
 {
     $centralSession = $centralUser->getSession();
     $request = $this->getRequest();
     // If there's no "finalProto", check if one was passed, and otherwise
     // assume the current.
     if (!isset($centralSession['finalProto'])) {
         $centralSession['finalProto'] = $request->getVal('proto', $request->detectProtocol());
     }
     // If there's no "remember", pull from the user preference.
     if (!isset($centralSession['remember'])) {
         $centralSession['remember'] = $user->getBoolOption('rememberpassword');
     }
     // Make sure there's a value for secureCookies
     if (!isset($centralSession['secureCookies'])) {
         $centralSession['secureCookies'] = $user->getBoolOption('prefershttps') && wfCanIPUseHTTPS($request->getIP());
     }
     // Make sure there's a session id by creating a session if necessary.
     if (!isset($centralSession['sessionId'])) {
         $centralSession['sessionId'] = $centralUser->setSession($centralSession);
     }
     return $centralSession;
 }