<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def confirm_email(self, token):
 """ View function to confirm a user's token from the confirmation email send to them. Supports html and json requests. """

        expired, invalid, user = \
            self.security_utils_service.confirm_email_token_status(token)
        if not user or invalid:
            invalid = True
            self.flash(
                _('flask_unchained.bundles.security:flash.invalid_confirmation_token'),
                category='error')

        already_confirmed = user is not None and user.confirmed_at is not None
        if expired and not already_confirmed:
            self.security_service.send_email_confirmation_instructions(user)
            self.flash(_('flask_unchained.bundles.security:flash.confirmation_expired',
                         email=user.email,
                         within=app.config.SECURITY_CONFIRM_EMAIL_WITHIN),
                       category='error')

        if invalid or (expired and not already_confirmed):
            return self.redirect('SECURITY_CONFIRM_ERROR_REDIRECT_ENDPOINT',
                                 'security_controller.send_confirmation_email')

        if self.security_service.confirm_user(user):
            self.after_this_request(self._commit)
            self.flash(_('flask_unchained.bundles.security:flash.email_confirmed'),
                       category='success')
        else:
            self.flash(_('flask_unchained.bundles.security:flash.already_confirmed'),
                       category='info')

        if user != current_user:
            self.security_service.logout_user()
            self.security_service.login_user(user)

        return self.redirect('SECURITY_POST_CONFIRM_REDIRECT_ENDPOINT',
                             'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT')