Diff for /loncom/auth/lonauth.pm between versions 1.121.2.26 and 1.170

version 1.121.2.26, 2022/02/28 01:07:15 version 1.170, 2021/11/17 00:44:47
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # User Authentication Module  # User Authentication Module
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::lonauth;  package Apache::lonauth;
   
 use strict;  use strict;
 use LONCAPA qw(:DEFAULT :match);  use LONCAPA qw(:DEFAULT :match);
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use CGI qw(:standard);  use CGI qw(:standard);
 use Apache::loncommon();  use Apache::loncommon();
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::lonmenu();  use Apache::lonmenu();
 use Apache::createaccount;  use Apache::createaccount;
 use Fcntl qw(:flock);  use Apache::ltiauth;
 use Apache::lonlocal;  use Fcntl qw(:flock);
 use Apache::File();  use Apache::lonlocal;
 use HTML::Entities;  use Apache::File();
 use Digest::MD5;  use HTML::Entities;
 use CGI::Cookie();  use Digest::MD5;
    use CGI::Cookie();
 # ------------------------------------------------------------ Successful login   
 sub success {  # ------------------------------------------------------------ Successful login
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,  sub success {
  $form,$cid,$expirepub) = @_;      my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
    $form,$skipcritical,$cid,$expirepub) = @_;
 # ------------------------------------------------------------ Get cookie ready  
     my $cookie =  # ------------------------------------------------------------ Get cookie ready
  &Apache::loncommon::init_user_environment($r, $username, $domain,      my $cookie =
   $authhost, $form,   &Apache::loncommon::init_user_environment($r, $username, $domain,
   {'extra_env' => $extra_env,});    $authhost, $form,
     {'extra_env' => $extra_env,});
     my $public=($username eq 'public' && $domain eq 'public');  
       my $public=($username eq 'public' && $domain eq 'public');
     if ($public or $lowerurl eq 'noredirect') { return $cookie; }  
       if ($public or $lowerurl eq 'noredirect') { return $cookie; }
 # -------------------------------------------------------------------- Log this  
   # -------------------------------------------------------------------- Log this
     my $ip = &Apache::lonnet::get_requestor_ip();  
     &Apache::lonnet::log($domain,$username,$authhost,      my $ip = &Apache::lonnet::get_requestor_ip();
                          "Login $ip");      &Apache::lonnet::log($domain,$username,$authhost,
                            "Login $ip");
 # ------------------------------------------------- Check for critical messages  
   # ------------------------------------------------- Check for critical messages
     my @what=&Apache::lonnet::dump('critical',$domain,$username);  
     if ($what[0]) {      unless ($skipcritical) {
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {          my @what=&Apache::lonnet::dump('critical',$domain,$username);
     $lowerurl='/adm/email?critical=display';          if ($what[0]) {
         }      if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
     }          $lowerurl='/adm/email?critical=display';
               }
 # ------------------------------------------------------------ Get cookies ready          }
     my ($securecookie,$defaultcookie);      }
     my $ssl = $r->subprocess_env('https');  
     if ($ssl) {  # ----------------------------------------------------------- Get cookies ready
         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";      my ($securecookie,$defaultcookie);
         my $lonidsdir=$r->dir_config('lonIDsDir');      my $ssl = $r->subprocess_env('https');
         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {      if ($ssl) {
             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';          $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";
             if (-e "$lonidsdir/$linkname.id") {          my $lonidsdir=$r->dir_config('lonIDsDir');
                 unlink("$lonidsdir/$linkname.id");          if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
             }              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",              if (-e "$lonidsdir/$linkname.id") {
                                               "$lonidsdir/$linkname.id"); 1 };                  unlink("$lonidsdir/$linkname.id");
             if ($made_symlink) {              }
                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});                                                "$lonidsdir/$linkname.id"); 1 };
             }              if ($made_symlink) {
         }                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
     } else {                  &Apache::lonnet::appenv({'user.linkedenv' => $linkname});
         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";              }
     }          }
 # -------------------------------------------------------- Menu script and info      } else {
     my $destination = $lowerurl;          $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
       }
     if (defined($form->{role})) {  # -------------------------------------------------------- Menu script and info
         my $envkey = 'user.role.'.$form->{role};      my $destination = $lowerurl;
         my $now=time;      if ($env{'request.lti.login'}) {
         my $then=$env{'user.login.time'};          if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
         my $refresh=$env{'user.refresh.time'};              &Apache::loncommon::content_type($r,'text/html');
         my $update=$env{'user.update.time'};              if ($securecookie) {
         if (!$update) {                  $r->headers_out->add('Set-cookie' => $securecookie);
             $update = $then;              }
         }              if ($defaultcookie) {
         if (exists($env{$envkey})) {                  $r->headers_out->add('Set-cookie' => $defaultcookie);
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);              }
             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,              $r->send_http_header;
                                          \$trolecode,\$tstatus,\$tstart,\$tend);              if (ref($form) eq 'HASH') {
             if ($tstatus eq 'is') {                  $form->{'lti.login'} = $env{'request.lti.login'};
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';                  $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');                  $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
                 $destination .= 'selectrole=1&'.$newrole.'=1';                  $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
             }              }
         }              &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
     }              return;
     if (defined($form->{symb})) {          }
         my $destsymb = $form->{symb};          if ($env{'request.lti.selfenrollrole'}) {
         my $encrypted;              if (&Apache::ltiauth::lti_enroll($username,$domain,
         if ($destsymb =~ m{^/enc/}) {                                               $env{'request.lti.selfenrollrole'}) eq 'ok') {
             $encrypted = 1;                  $form->{'role'} = $env{'request.lti.selfenrollrole'};
             if ($cid) {                  &Apache::lonnet::delenv('request.lti.selfenrollrole');
                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);              } else {
             }                  &Apache::ltiauth::invalid_request($r,24);
         }              }
         $destination  .= ($destination =~ /\?/) ? '&' : '?';          }
         if ($destsymb =~ /___/) {      }
             my ($map,$resid,$desturl)=split(/___/,$destsymb);      if (defined($form->{role})) {
             $desturl = &Apache::lonnet::clutter($desturl);          my $envkey = 'user.role.'.$form->{role};
             if ($encrypted) {          my $now=time;
                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);          my $then=$env{'user.login.time'};
                 $destsymb = $form->{symb};          my $refresh=$env{'user.refresh.time'};
             }          my $update=$env{'user.update.time'};
             $desturl = &HTML::Entities::encode($desturl,'"<>&');          if (!$update) {
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              $update = $then;
             $destination .= 'destinationurl='.$desturl.          }
                             '&destsymb='.$destsymb;          if (exists($env{$envkey})) {
         } elsif (!$encrypted) {              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
             $destination .= 'destinationurl='.$destsymb;                                           \$trolecode,\$tstatus,\$tstart,\$tend);
         }              if ($tstatus eq 'is') {
     }                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
     if ($destination =~ m{^/adm/roles}) {                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
         $destination  .= ($destination =~ /\?/) ? '&' : '?';                  $destination .= 'selectrole=1&'.$newrole.'=1';
         $destination .= 'source=login';              }
     }          }
       }
     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});      if (defined($form->{symb})) {
     my $startupremote=&Apache::lonmenu::startupremote($destination);          my $destsymb = $form->{symb};
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);          my $encrypted;
     my $setflags=&Apache::lonmenu::setflags();          if ($destsymb =~ m{^/enc/}) {
     my $maincall=&Apache::lonmenu::maincall();              $encrypted = 1;
     my $brcrum = [{'href' => '',              if ($cid) {
                    'text' => 'Successful Login'},];                  $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);
     my $start_page=&Apache::loncommon::start_page('Successful Login',              }
                                                   $startupremote,          }
                                                   {'no_inline_link' => 1,          $destination  .= ($destination =~ /\?/) ? '&' : '?';
                                                    'bread_crumbs' => $brcrum,});          if ($destsymb =~ /___/) {
     my $end_page  =&Apache::loncommon::end_page();              my ($map,$resid,$desturl)=split(/___/,$destsymb);
               $desturl = &Apache::lonnet::clutter($desturl);
     my $continuelink;              if ($encrypted) {
     if ($env{'environment.remote'} eq 'off') {                  $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);
  $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';                  $destsymb = $form->{symb};
     }              }
 # ------------------------------------------------- Output for successful login              $desturl = &HTML::Entities::encode($desturl,'"<>&');
               $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     &Apache::loncommon::content_type($r,'text/html');              $destination .= 'destinationurl='.$desturl.
     if ($securecookie) {                              '&destsymb='.$destsymb;
         $r->headers_out->add('Set-cookie' => $securecookie);          } elsif (!$encrypted) {
     }              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     if ($defaultcookie) {              $destination .= 'destinationurl='.$destsymb;
         $r->headers_out->add('Set-cookie' => $defaultcookie);          }
     }      }
     if ($expirepub) {      if ($destination =~ m{^/adm/roles}) {
         my $c = new CGI::Cookie(-name    => 'lonPubID',          $destination  .= ($destination =~ /\?/) ? '&' : '?';
                                 -value   => '',          $destination .= 'source=login';
                                 -expires => '-10y',);      }
         $r->headers_out->add('Set-cookie' => $c);  
     }      if (($env{'request.deeplink.login'} eq $lowerurl) &&
     $r->send_http_header;          (($env{'request.linkprot'}) || ($env{'request.linkkey'} ne ''))) {
           my %info;
     my %lt=&Apache::lonlocal::texthash(          if ($env{'request.linkprot'}) {
        'wel' => 'Welcome',              $info{'linkprot'} = $env{'request.linkprot'};
        'pro' => 'Login problems?',          } elsif ($env{'request.linkkey'} ne '') {
        );              $info{'linkkey'} = $env{'request.linkkey'};
     my $loginhelp = &loginhelpdisplay($domain);          }
     if ($loginhelp) {          $info{'origurl'} = $lowerurl;
         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';          my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
     }          unless (($token eq 'con_lost') || ($token eq 'refused') ||
                   ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');               $destination .= (($destination =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
     $r->print(<<ENDSUCCESS);          }
 $start_page      }
 $setflags  
 $windowinfo      my $windowname = 'loncapaclient';
 <h1>$lt{'wel'}</h1>      if ($env{'request.lti.login'}) {
 $welcome          $windowname .= 'lti';
 $loginhelp      }
 $remoteinfo      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
 $maincall      my $brcrum = [{'href' => '',
 $continuelink                     'text' => 'Successful Login'},];
 $end_page      my $args = {'bread_crumbs' => $brcrum,};
 ENDSUCCESS      unless ((defined($form->{role})) || (defined($form->{symb}))) {
     return;          my $update=$env{'user.update.time'};
 }          if (!$update) {
               $update = $env{'user.login.time'};
 # --------------------------------------------------------------- Failed login!          }
           my %roles_in_env;
 sub failed {          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
     my ($r,$message,$form,$authhost) = @_;          if ($showcount == 1) {
     (undef,undef,undef,my $clientmathml,my $clientunicode) =              foreach my $rolecode (keys(%roles_in_env)) {
         &Apache::loncommon::decode_user_agent();                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
     my $args = {};                  if ($cid) {
     if ($clientunicode && !$clientmathml) {                      my %coursedescription =
         $args = {'browser.unicode' => 1};                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
     }                      if ($coursedescription{'type'} eq 'Placement') {
                           $args->{'crstype'} = 'Placement';
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);                      }
     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});                      last;
     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});                  }
     if (&Apache::lonnet::domain($udom,'description') eq '') {              }
         undef($udom);          }
     }      }
     my $retry = '/adm/login';  
     if ($uname eq $form->{'uname'}) {  # ------------------------------------------------- Output for successful login
         $retry .= '?username='.$uname;  
     }      &Apache::loncommon::content_type($r,'text/html');
     if ($udom) {      if ($securecookie) {
         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;          $r->headers_out->add('Set-cookie' => $securecookie);
     }      }
     my $lonhost = $r->dir_config('lonHostID');      if ($defaultcookie) {
     my $querystr;          $r->headers_out->add('Set-cookie' => $defaultcookie);
     my $result = &set_retry_token($form,$lonhost,\$querystr);      }
     if ($result eq 'fail') {      if ($expirepub) {
         if (exists($form->{role})) {          my $c = new CGI::Cookie(-name    => 'lonPubID',
             my $role = &Apache::loncommon::cleanup_html($form->{role});                                  -value   => '',
             if ($role ne '') {                                  -expires => '-10y',);
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;          $r->headers_out->add('Set-cookie' => $c);
             }      }
         }      $r->send_http_header;
         if (exists($form->{symb})) {  
             my $symb = &Apache::loncommon::cleanup_html($form->{symb});      my ($start_page,$js,$pagebody,$end_page);
             if ($symb ne '') {      if ($env{'request.lti.login'}) {
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;          $args = {'only_body' => 1};
             }          if ($env{'request.lti.target'} eq '') {
         }              my $ltitarget = (($destination =~ /\?/) ? '&' : '?').
         if (exists($form->{firsturl})) {                              'ltitarget=iframe';
             my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});              $js = <<"ENDJS";
             if ($firsturl ne '') {  
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;  <script type="text/javascript">
             }  // <![CDATA[
         }  function setLTItarget() {
     } elsif ($querystr ne '') {      var newloc = '$destination';
         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;      if (parent !== window) {
     }          newloc += '$ltitarget';
     my $end_page = &Apache::loncommon::end_page();      }
     &Apache::loncommon::content_type($r,'text/html');      window.location.href=newloc;
     $r->send_http_header;  }
     my @actions =  // ]]>
          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));  </script>
     my $loginhelp = &loginhelpdisplay($udom);  
     if ($loginhelp) {  ENDJS
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');              $args->{'add_entries'} = {'onload' => "javascript:setLTItarget();"};
     }              $pagebody =  '<noscript><span class="LC_warning">'
     #FIXME: link to helpdesk might be added here                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
                           .'</span></noscript>';
     $r->print(          } else {
        $start_page              $args->{'redirect'} = [0,$destination,1];
       .'<h2>'.&mt('Sorry ...').'</h2>'          }
       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'          $start_page=&Apache::loncommon::start_page('',$js,$args);
       .&Apache::lonhtmlcommon::actionbox(\@actions)      } else {
       .$end_page          $args->{'redirect'} = [0,$destination];
     );          $start_page=&Apache::loncommon::start_page('Successful Login',
  }                                                     $js,$args);
   
 # ------------------------------------------------------------------ Rerouting!          my %lt=&Apache::lonlocal::texthash(
              'wel' => 'Welcome',
 sub reroute {             'pro' => 'Login problems?',
     my ($r) = @_;            );
     &Apache::loncommon::content_type($r,'text/html');          $pagebody = "<h1>$lt{'wel'}</h1>\n".
     $r->send_http_header;                      &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'          my $loginhelp = &loginhelpdisplay($domain);
            .&mt('Please [_1]log in again[_2].');          if ($loginhelp) {
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});              $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
 }          }
       }
 # ---------------------------------------------------------------- Main handler      $end_page = &Apache::loncommon::end_page();
       $r->print(<<ENDSUCCESS);
 sub handler {  $start_page
     my $r = shift;  $windowinfo
     my $londocroot = $r->dir_config('lonDocRoot');  $pagebody
 # Are we re-routing?  $end_page
     if (-e "$londocroot/lon-status/reroute.txt") {  ENDSUCCESS
  &reroute($r);      return;
  return OK;  }
     }  
   # --------------------------------------------------------------- Failed login!
     &Apache::lonlocal::get_language_handle($r);  
   sub failed {
 # -------------------------------- Prevent users from attempting to login twice      my ($r,$message,$form) = @_;
     my $handle = &Apache::lonnet::check_for_valid_session($r);      (undef,undef,undef,my $clientmathml,my $clientunicode) =
     if ($handle ne '') {          &Apache::loncommon::decode_user_agent();
         my $lonidsdir=$r->dir_config('lonIDsDir');      my $args = {};
         if ($handle=~/^publicuser\_/) {      if ($clientunicode && !$clientmathml) {
 # For "public user" - remove it, we apparently really want to login          $args = {'browser.unicode' => 1};
             unlink($r->dir_config('lonIDsDir')."/$handle.id");      }
         } else {  
 # Indeed, a valid token is found      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
     &Apache::loncommon::content_type($r,'text/html');      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
     $r->send_http_header;      if (&Apache::lonnet::domain($udom,'description') eq '') {
     my $start_page =           undef($udom);
         &Apache::loncommon::start_page('Already logged in');      }
     my $end_page =       my $retry = '/adm/login';
         &Apache::loncommon::end_page();      if ($uname eq $form->{'uname'}) {
             my $dest = '/adm/roles';          $retry .= '?username='.$uname;
             my %form = &get_form_items($r);      }
             if ($form{'logtoken'}) {      if ($udom) {
                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
                                                      $form{'serverid'});      }
                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||      my $lonhost = $r->dir_config('lonHostID');
                         ($tmpinfo eq 'no_such_host')) {      my $querystr;
                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);      my $result = &set_retry_token($form,$lonhost,\$querystr);
                     $firsturl = &unescape($firsturl);      if ($result eq 'fail') {
                     my %info;          if (exists($form->{role})) {
                     foreach my $item (@rest) {              my $role = &Apache::loncommon::cleanup_html($form->{role});
                         my ($key,$value) = split(/=/,$item);              if ($role ne '') {
                         $info{$key} = &unescape($value);                  $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
                     }              }
                     if ($firsturl ne '') {          }
                         $info{'firsturl'} = $firsturl;          if (exists($form->{symb})) {
                         $dest = $firsturl;              my $symb = &Apache::loncommon::cleanup_html($form->{symb});
                     }              if ($symb ne '') {
                 }                  $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
             }              }
             $r->print(          }
                $start_page          if (exists($form->{firsturl})) {
               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'              my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'              if ($firsturl ne '') {
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')                  $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
               .'</p>'                  if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
               .$end_page                      unless (exists($form->{linkprot})) {
             );                          if (exists($form->{linkkey})) {
             return OK;                              $retry .= 'linkkey='.$form->{linkkey};
         }                          }
     }                      }
                   }
 # ---------------------------------------------------- No valid token, continue              }
           }
     my %form = &get_form_items($r);          if (exists($form->{linkprot})) {
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {              my $ltoken = &Apache::lonnet::tmpput({linkprot => $form->{'linkprot'}},
  &failed($r,'Username, password and domain need to be specified.',                                                   $r->dir_config('lonHostID'),'retry');
  \%form);              if ($ltoken) {
         return OK;                  $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
     }              }
           }
 # split user logging in and "su"-user      } elsif ($querystr ne '') {
           $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;
     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});      }
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});      my $end_page = &Apache::loncommon::end_page();
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});      &Apache::loncommon::content_type($r,'text/html');
     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});      $r->send_http_header;
     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});      my @actions =
            (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
     my $role   = $r->dir_config('lonRole');      my $loginhelp = &loginhelpdisplay($udom);
     my $domain = $r->dir_config('lonDefDomain');      if ($loginhelp) {
     my $prodir = $r->dir_config('lonUsersDir');          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
     my $contact_name = &mt('LON-CAPA helpdesk');      }
       #FIXME: link to helpdesk might be added here
 # ---------------------------------------- Get the information from login token  
       $r->print(
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},         $start_page
                                       $form{'serverid'});        .'<h2>'.&mt('Sorry ...').'</h2>'
         .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||         .&Apache::lonhtmlcommon::actionbox(\@actions)
         ($tmpinfo eq 'no_such_host')) {        .$end_page
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);      );
         return OK;   }
     } else {  
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},  # ------------------------------------------------------------------ Rerouting!
    $form{'serverid'});  
         if ( $reply ne 'ok' ) {  sub reroute {
             &failed($r,'Session could not be opened.',\%form);      my ($r) = @_;
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");      &Apache::loncommon::content_type($r,'text/html');
     return OK;      $r->send_http_header;
  }      my $msg='<b>'.&mt('Sorry ...').'</b><br />'
     }             .&mt('Please [_1]log in again[_2].');
       &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
     if (!&Apache::lonnet::domain($form{'udom'})) {  }
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);  
         return OK;  # ---------------------------------------------------------------- Main handler
     }  
   sub handler {
     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);      my $r = shift;
     $firsturl = &unescape($firsturl);      my $londocroot = $r->dir_config('lonDocRoot');
     foreach my $item (@rest) {  # Are we re-routing?
         my ($key,$value) = split(/=/,$item);      if (-e "$londocroot/lon-status/reroute.txt") {
         $form{$key} = &unescape($value);   &reroute($r);
     }   return OK;
     my $upass = &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});      }
   
 # ---------------------------------------------------------------- Authenticate      &Apache::lonlocal::get_language_handle($r);
   
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});  # -------------------------------- Prevent users from attempting to login twice
     my ($cancreate,$statustocreate) =      my $handle = &Apache::lonnet::check_for_valid_session($r);
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});      if ($handle ne '') {
     my $defaultauth;          my $lonidsdir=$r->dir_config('lonIDsDir');
     if (ref($cancreate) eq 'ARRAY') {          if ($handle=~/^publicuser\_/) {
         if (grep(/^login$/,@{$cancreate})) {  # For "public user" - remove it, we apparently really want to login
             $defaultauth = 1;              unlink($r->dir_config('lonIDsDir')."/$handle.id");
         }          } else {
     }  # Indeed, a valid token is found
     my $clientcancheckhost = 1;              &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,      &Apache::loncommon::content_type($r,'text/html');
                                               $form{'udom'},$defaultauth,      $r->send_http_header;
                                               $clientcancheckhost);      my $start_page =
               &Apache::loncommon::start_page('Already logged in');
 # --------------------------------------------------------------------- Failed?      my $end_page =
           &Apache::loncommon::end_page();
     if ($authhost eq 'no_host') {              my $dest = '/adm/roles';
         my $pwdverify;              my %form = &get_form_items($r);
         if (&Apache::lonnet::homeserver($form{'uname'},$form{'udom'}) eq 'no_host') {              if ($form{'logtoken'}) {
             my %possunames = &alternate_unames_check($form{'uname'},$form{'udom'});                  my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
             if (keys(%possunames) > 0) {                                                       $form{'serverid'});
                 foreach my $rulematch (keys(%possunames)) {                  unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
                     my $possuname = $possunames{$rulematch};                          ($tmpinfo eq 'no_such_host')) {
                     if (($possuname ne '') && ($possuname =~ /^$match_username$/)) {                      my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
                         $authhost=Apache::lonnet::authenticate($possuname,$upass,                      $firsturl = &unescape($firsturl);
                                                                $form{'udom'},undef,                      my %info;
                                                                $clientcancheckhost);                      foreach my $item (@rest) {
                         if (($authhost eq 'no_host') || ($authhost eq 'no_account_on_host')) {                          my ($key,$value) = split(/=/,$item);
                             next;                          $info{$key} = &unescape($value);
                         } elsif (($authhost ne '') && (&Apache::lonnet::hostname($authhost) ne '')) {                      }
                             $pwdverify = 1;                      if ($firsturl ne '') {
                             &Apache::lonnet::logthis("Authenticated user: $possuname was submitted as: $form{'uname'}");                          $info{'firsturl'} = $firsturl;
                             $form{'uname'} = $possuname;                          $dest = $firsturl;
                             last;                          my $relogin;
                         }                          if ($dest =~ m{^/tiny/$match_domain/\w+$}) {
                     }                              if ($env{'request.course.id'}) {
                 }                                  my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
             }                                  my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
         }                                  my $symb = &Apache::loncommon::symb_from_tinyurl($dest,$cnum,$cdom);
         unless ($pwdverify) {                                  if ($symb) {
             &failed($r,'Username and/or password could not be authenticated.',                                      unless (&set_deeplink_login(%info) eq 'ok') {
                     \%form);                                          $relogin = 1;
             return OK;                                      }
         }                                  }
     } elsif ($authhost eq 'no_account_on_host') {                              }
         if ($defaultauth) {                              if ($relogin) {
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');                                  $r->print(
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {                                        $start_page
                 return OK;                                       .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
             }                                       .'<p>'.&mt('Please [_1]log out[_2] first, and then try your access again',
             my $start_page =                                                   '<a href="/adm/logout">','</a>')
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',                                       .'</p>'
                                                '',{'no_inline_link'   => 1,});                                       .$end_page);
             my $lonhost = $r->dir_config('lonHostID');                              } else {
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};                                  if (($info{'linkprot'}) || ($info{'linkkey'} ne '')) {
             my $contacts =                                       my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',                                      unless (($token eq 'con_lost') || ($token eq 'refused') ||
                                                         $form{'udom'},$origmail);                                              ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
             my ($contact_email) = split(',',$contacts);                                           $dest .= (($dest =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
             my $output =                                       }
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},                                  }
                                                        $domdesc,'',$lonhost,                                  $r->print(
                                                        $contact_email,$contact_name,                                        $start_page
                                                        undef,$statustocreate);                                       .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
             &Apache::loncommon::content_type($r,'text/html');                                       .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4] first, and then try your access again',
             $r->send_http_header;                                                  '<a href="'.$dest.'">','</a>',
             &Apache::createaccount::print_header($r,$start_page);                                                  '<a href="/adm/logout">','</a>')
             $r->print('<h3>'.&mt('Account creation').'</h3>'.                                       .'</p>'
                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.                                       .$end_page);
                       $output.&Apache::loncommon::end_page());                              }
             return OK;                              return OK;
         } else {                          }
             &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);                      }
             return OK;                  }
         }              }
     }              $r->print(
                     $start_page
     if (($firsturl eq '') ||                    .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  ($firsturl=~/^\/adm\/(logout|remote)/)) {                   .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
  $firsturl='/adm/roles';                            ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
     }                   .'</p>'
                    .$end_page
     my ($hosthere,%sessiondata);              );
     if ($form{'iptoken'}) {              return OK;
         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});          }
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});      }
         if (($sessiondata{'domain'} eq $form{'udom'}) &&  
             ($sessiondata{'username'} eq $form{'uname'})) {  # ---------------------------------------------------- No valid token, continue
             $hosthere = 1;  
         }      my %form = &get_form_items($r);
     }      if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
    &failed($r,'Username, password and domain need to be specified.',
 # --------------------------------- Are we attempting to login as somebody else?   \%form);
     if ($form{'suname'}) {          return OK;
         my ($suname,$sudom,$sudomref);      }
         $suname = $form{'suname'};  
         $sudom = $form{'udom'};  # split user logging in and "su"-user
         if ($form{'sudom'}) {  
             unless ($sudom eq $form{'sudom'}) {      ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
                 if (&Apache::lonnet::domain($form{'sudom'})) {      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
                     $sudomref = [$form{'sudom'}];      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
                     $sudom = $form{'sudom'};      $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
                 }      $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
             }  
         }      my $role   = $r->dir_config('lonRole');
 # ------------ see if the original user has enough privileges to pull this stunt      my $domain = $r->dir_config('lonDefDomain');
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {      my $prodir = $r->dir_config('lonUsersDir');
 # ---------------------------------------------------- see if the su-user exists      my $contact_name = &mt('LON-CAPA helpdesk');
     unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {  
 # ------------------------------ see if the su-user is not too highly privileged  # ---------------------------------------- Get the information from login token
  if (&Apache::lonnet::privileged($suname,$sudom)) {  
                     &Apache::lonnet::logthis('Attempted switch user to privileged user');      my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
                 } else {                                        $form{'serverid'});
                     my $noprivswitch;  
 #      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
 # su-user's home server and user's home server must have one of:          ($tmpinfo eq 'no_such_host')) {
 # (a) same domain   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
 # (b) same primary library server for the two domains          return OK;
 # (c) same "internet domain" for primary library server(s) for home servers' domains      } else {
 #   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
                     my $suprim = &Apache::lonnet::domain($sudom,'primary');     $form{'serverid'});
                     my $suintdom = &Apache::lonnet::internet_dom($suprim);          if ( $reply ne 'ok' ) {
                     unless ($sudom eq $form{'udom'}) {              &failed($r,'Session could not be opened.',\%form);
                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');      &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
                         my $uintdom = &Apache::lonnet::internet_dom($uprim);      return OK;
                         unless ($suprim eq $uprim) {   }
                             unless ($suintdom eq $uintdom) {      }
                                 &Apache::lonnet::logthis('Attempted switch user '  
                                    .'to user with different "internet domain".');      if (!&Apache::lonnet::domain($form{'udom'})) {
                                 $noprivswitch = 1;          &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
                             }          return OK;
                         }      }
                     }  
       my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
                     unless ($noprivswitch) {      $firsturl = &unescape($firsturl);
 #      foreach my $item (@rest) {
 # server where log-in occurs must have same "internet domain" as su-user's home          my ($key,$value) = split(/=/,$item);
 # server          $form{$key} = &unescape($value);
 #      }
                         my $lonhost = $r->dir_config('lonHostID');      if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);          $form{'firsturl'} = $firsturl;
                         if ($hostintdom ne $suintdom) {      }
                             &Apache::lonnet::logthis('Attempted switch user on a '      my $upass = $ENV{HTTPS} ? $form{'upass0'}
                                 .'server with a different "internet domain".');          : &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});
                         } else {  
   # ---------------------------------------------------------------- Authenticate
 # -------------------------------------------------------- actually switch users  
       my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.      my ($cancreate,$statustocreate) =
  $form{'udom'}.' logging in as '.$suname.':'.$sudom);          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
     $form{'uname'}=$suname;      my $defaultauth;
                             if ($form{'udom'} ne $sudom) {      if (ref($cancreate) eq 'ARRAY') {
                                 $form{'udom'}=$sudom;          if (grep(/^login$/,@{$cancreate})) {
                             }              $defaultauth = 1;
                         }          }
                     }      }
  }      my $clientcancheckhost = 1;
     }      my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  } else {                                                $form{'udom'},$defaultauth,
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');                                                $clientcancheckhost);
  }  
     }  # --------------------------------------------------------------------- Failed?
   
     my ($is_balancer,$otherserver);      if ($authhost eq 'no_host') {
    &failed($r,'Username and/or password could not be authenticated.',
     unless ($hosthere) {   \%form);
         ($is_balancer,$otherserver) =          return OK;
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');      } elsif ($authhost eq 'no_account_on_host') {
         if ($is_balancer) {          if ($defaultauth) {
             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {                  return OK;
                 $otherserver = $found_server;              }
             }              my $start_page =
             if ($otherserver eq '') {                  &Apache::loncommon::start_page('Create a user account in LON-CAPA',
                 my $lowest_load;                                                 '',{'no_inline_link'   => 1,});
                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});              my $lonhost = $r->dir_config('lonHostID');
                 if ($lowest_load > 100) {              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});              my $contacts =
                 }                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
             }                                                          $form{'udom'},$origmail);
             if ($otherserver ne '') {              my ($contact_email) = split(',',$contacts);
                 my @hosts = &Apache::lonnet::current_machine_ids();              my $output =
                 if (grep(/^\Q$otherserver\E$/,@hosts)) {                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
                     $hosthere = $otherserver;                                                         $domdesc,'',$lonhost,
                 }                                                         $contact_email,$contact_name,
             }                                                         undef,$statustocreate);
         }              &Apache::loncommon::content_type($r,'text/html');
     }              $r->send_http_header;
               &Apache::createaccount::print_header($r,$start_page);
     if (($is_balancer) && (!$hosthere)) {              $r->print('<h3>'.&mt('Account creation').'</h3>'.
         if ($otherserver) {                        &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                        $output.&Apache::loncommon::end_page());
                      \%form);              return OK;
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;          } else {
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {              &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);
                 $switchto .= '&origurl='.$firsturl;              return OK;
             }          }
             if ($form{'role'}) {      }
                 $switchto .= '&role='.$form{'role'};  
             }      if (($firsturl eq '') ||
             if ($form{'symb'}) {   ($firsturl=~/^\/adm\/(logout|remote)/)) {
                 $switchto .= '&symb='.$form{'symb'};   $firsturl='/adm/roles';
             }      }
             $r->internal_redirect($switchto);  
         } else {      my ($hosthere,%sessiondata);
             &Apache::loncommon::content_type($r,'text/html');      if ($form{'iptoken'}) {
             $r->send_http_header;          %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
             $r->print(&noswitch());          my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
         }          if (($sessiondata{'domain'} eq $form{'udom'}) &&
         return OK;              ($sessiondata{'username'} eq $form{'uname'})) {
     } else {              $hosthere = 1;
         if (!&check_can_host($r,\%form,$authhost)) {          }
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});      }
             if ($otherserver) {  
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,  # --------------------------------- Are we attempting to login as somebody else?
                          \%form);      if ($form{'suname'}) {
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;          my ($suname,$sudom,$sudomref);
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {          $suname = $form{'suname'};
                     $switchto .= '&origurl='.$firsturl;          $sudom = $form{'udom'};
                 }          if ($form{'sudom'}) {
                 if ($form{'role'}) {              unless ($sudom eq $form{'sudom'}) {
                     $switchto .= '&role='.$form{'role'};                  if (&Apache::lonnet::domain($form{'sudom'})) {
                 }                      $sudomref = [$form{'sudom'}];
                 if ($form{'symb'}) {                      $sudom = $form{'sudom'};
                     $switchto .= '&symb='.$form{'symb'};                  }
                 }              }
                 $r->internal_redirect($switchto);          }
             } else {  # ------------ see if the original user has enough privileges to pull this stunt
                 &Apache::loncommon::content_type($r,'text/html');   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
                 $r->send_http_header;  # ---------------------------------------------------- see if the su-user exists
                 $r->print(&noswitch());      unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
             }  # ------------------------------ see if the su-user is not too highly privileged
             return OK;   if (&Apache::lonnet::privileged($suname,$sudom)) {
         }                      &Apache::lonnet::logthis('Attempted switch user to privileged user');
                   } else {
 # ------------------------------------------------------- Do the load balancing                      my $noprivswitch;
   #
 # ---------------------------------------------------------- Determine own load  # su-user's home server and user's home server must have one of:
         my $loadlim = $r->dir_config('lonLoadLim');  # (a) same domain
         my $loadavg;  # (b) same primary library server for the two domains
         {  # (c) same "internet domain" for primary library server(s) for home servers' domains
             my $loadfile=Apache::File->new('/proc/loadavg');  #
             $loadavg=<$loadfile>;                      my $suprim = &Apache::lonnet::domain($sudom,'primary');
         }                      my $suintdom = &Apache::lonnet::internet_dom($suprim);
         $loadavg =~ s/\s.*//g;                      unless ($sudom eq $form{'udom'}) {
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);                          my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
         my $userloadpercent=&Apache::lonnet::userload();                          my $uintdom = &Apache::lonnet::internet_dom($uprim);
                           unless ($suprim eq $uprim) {
 # ---------------------------------------------------------- Are we overloaded?                              unless ($suintdom eq $uintdom) {
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {                                  &Apache::lonnet::logthis('Attempted switch user '
             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});                                     .'to user with different "internet domain".');
             if (!$unloaded) {                                  $noprivswitch = 1;
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});                              }
             }                          }
             if ($unloaded) {                      }
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',  
                          undef,\%form);                      unless ($noprivswitch) {
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);  #
                 return OK;  # server where log-in occurs must have same "internet domain" as su-user's home
             }  # server
         }  #
         if (($is_balancer) && ($hosthere)) {                          my $lonhost = $r->dir_config('lonHostID');
             $form{'noloadbalance'} = $hosthere;                          my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
         }                          if ($hostintdom ne $suintdom) {
         my $extra_env;                              &Apache::lonnet::logthis('Attempted switch user on a '
         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {                                  .'server with a different "internet domain".');
             if ($sessiondata{'origurl'} ne '') {                          } else {
                 $firsturl = $sessiondata{'origurl'};  
                 $form{'firsturl'} = $sessiondata{'origurl'};  # -------------------------------------------------------- actually switch users
                 my @names = ('role','symb','linkprot','linkkey');  
                 foreach my $item (@names) {              &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
                     if ($sessiondata{$item} ne '') {                                $form{'udom'}.' logging in as '.$suname.':'.$sudom);
                         $form{$item} = $sessiondata{$item};              $form{'uname'}=$suname;
                     }                              if ($form{'udom'} ne $sudom) {
                 }                                  $form{'udom'}=$sudom;
             }                              }
         }                          }
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,                      }
                  \%form);   }
         return OK;      }
     }   } else {
 }      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
    }
 sub get_form_items {      }
     my ($r) = @_;  
     my $buffer;      my ($is_balancer,$otherserver);
     if ($r->header_in('Content-length') > 0) {  
         $r->read($buffer,$r->header_in('Content-length'),0);      unless ($hosthere) {
     }          ($is_balancer,$otherserver) =
     my %form;              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
     foreach my $pair (split(/&/,$buffer)) {          if ($is_balancer) {
        my ($name,$value) = split(/=/,$pair);              # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
        $value =~ tr/+/ /;              my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;              if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {
        $form{$name}=$value;                  $otherserver = $found_server;
     }              }
     return %form;              if ($otherserver eq '') {
 }                  my $lowest_load;
                   ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
 sub set_retry_token {                  if ($lowest_load > 100) {
     my ($form,$lonhost,$querystr) = @_;                      $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});
     if (ref($form) eq 'HASH') {                  }
         my ($firsturl,$token,$extras,@names);              }
         @names = ('role','symb','iptoken');              if ($otherserver ne '') {
         foreach my $name (@names) {                  my @hosts = &Apache::lonnet::current_machine_ids();
             if ($form->{$name} ne '') {                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
                 $extras .= '&'.$name.'='.&escape($form->{$name});                      $hosthere = $otherserver;
                 last if ($name eq 'linkprot');                  }
             }              }
         }          }
         my $firsturl = $form->{'firsturl'};      }
         if (($firsturl ne '') || ($extras ne '')) {  
             $extras .= ':retry';      if (($is_balancer) && (!$hosthere)) {
             $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).          if ($otherserver) {
                                             $extras,$lonhost);              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
             if (($token eq 'con_lost') || ($token eq 'no_such_host')) {                       \%form);
                 return 'fail';              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
             } else {              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                 if (ref($querystr)) {                  $switchto .= '&origurl='.$firsturl;
                     $$querystr = 'retry='.$token;              }
                 }              if ($form{'role'}) {
                 return 'ok';                  $switchto .= '&role='.$form{'role'};
             }              }
         }              if ($form{'symb'}) {
     }                  $switchto .= '&symb='.$form{'symb'};
     return;              }
 }              if ($form{'linkprot'}) {
                   $env{'request.linkprot'} = $form{'linkprot'};
 sub check_can_host {              } elsif ($form{'linkkey'} ne '') {
     my ($r,$form,$authhost,$domdesc) = @_;                  $env{'request.linkkey'} = $form{'linkkey'};
     return unless (ref($form) eq 'HASH');              }
     my $canhost = 1;              if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
     my $lonhost = $r->dir_config('lonHostID');                  &set_deeplink_login(%form);
     my $udom = $form->{'udom'};              }
     my @intdoms;              $r->internal_redirect($switchto);
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);          } else {
     if (ref($internet_names) eq 'ARRAY') {              &Apache::loncommon::content_type($r,'text/html');
         @intdoms = @{$internet_names};              $r->send_http_header;
     }              $r->print(&noswitch());
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');          }
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);          return OK;
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {      } else {
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);          if (!&check_can_host($r,\%form,$authhost)) {
         my $hostname = &Apache::lonnet::hostname($lonhost);              my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);              if ($otherserver) {
         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);                           \%form);
         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);                  my $switchto = '/adm/switchserver?otherserver='.$otherserver;
         my $loncaparev;                  if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
         if ($authhost eq 'no_account_on_host') {                      $switchto .= '&origurl='.$firsturl;
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);                  }
         } else {                  if ($form{'role'}) {
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);                      $switchto .= '&role='.$form{'role'};
         }                  }
         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,                  if ($form{'symb'}) {
                                                      $udomdefaults{'remotesessions'},                      $switchto .= '&symb='.$form{'symb'};
                                                      $defdomdefaults{'hostedsessions'});                  }
     }                  if ($form{'linkprot'}) {
     unless ($canhost) {                      $env{'request.linkprot'} = $form{'linkprot'};
         if ($authhost eq 'no_account_on_host') {                  } elsif ($form{'linkkey'} ne '') {
             my $checkloginvia = 1;                      $env{'request.linkkey'} = $form{'linkkey'};
             my ($login_host,$hostname) =                   }
                 &Apache::lonnet::choose_server($udom,$checkloginvia);                  if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
             &Apache::loncommon::content_type($r,'text/html');                      &set_deeplink_login(%form);
             $r->send_http_header;                  }
             if ($login_host ne '') {                  $r->internal_redirect($switchto);
                 my $protocol = $Apache::lonnet::protocol{$login_host};              } else {
                 $protocol = 'http' if ($protocol ne 'https');                  &Apache::loncommon::content_type($r,'text/html');
                 my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);                  $r->send_http_header;
                 $hostname = $alias if ($alias ne '');                  $r->print(&noswitch());
                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';              }
                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').              return OK;
                           '<h3>'.&mt('Account creation').'</h3>'.          }
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.  
                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.  # ------------------------------------------------------- Do the load balancing
                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').  
                           &Apache::loncommon::end_page());  # ---------------------------------------------------------- Determine own load
             } else {          my $loadlim = $r->dir_config('lonLoadLim');
                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').          my $loadavg;
                           '<h3>'.&mt('Account creation unavailable').'</h3>'.          {
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.              my $loadfile=Apache::File->new('/proc/loadavg');
                           '<p>'.&mt('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.              $loadavg=<$loadfile>;
                           &Apache::loncommon::end_page());          }
             }          $loadavg =~ s/\s.*//g;
         } else {          my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,          my $userloadpercent=&Apache::lonnet::userload();
                      $form);  
             my ($otherserver) = &Apache::lonnet::choose_server($udom);  # ---------------------------------------------------------- Are we overloaded?
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);          if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
         }              my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});
     }              if (!$unloaded) {
     return $canhost;                  ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
 }              }
               if ($unloaded) {
 sub noswitch {                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').                           undef,\%form);
                  '<h3>'.&mt('Session unavailable').'</h3>'.                  if ($form{'linkprot'}) {
                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.                      $env{'request.linkprot'} = $form{'linkprot'};
                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.                  } elsif ($form{'linkkey'} ne '') {
                  &Apache::loncommon::end_page();                      $env{'request.linkkey'} = $form{'linkkey'};
     return $result;                  }
 }                  if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                       &set_deeplink_login(%form);
 sub loginhelpdisplay {                  }
     my ($authdomain) = @_;                  $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
     my $login_help = 1;                  return OK;
     my $lang = &Apache::lonlocal::current_language();              }
     if ($login_help) {          }
         my $dom = $authdomain;          if (($is_balancer) && ($hosthere)) {
         if ($dom eq '') {              $form{'noloadbalance'} = $hosthere;
             $dom = &Apache::lonnet::default_login_domain();          }
         }          my $extra_env;
         my %domconfhash = &Apache::loncommon::get_domainconf($dom);          if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {
         my $loginhelp_url;              if ($sessiondata{'origurl'} ne '') {
         if ($lang) {                  $firsturl = $sessiondata{'origurl'};
             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};                  $form{'firsturl'} = $sessiondata{'origurl'};
             if ($loginhelp_url ne '') {                  my @names = ('role','symb','linkprot','linkkey');
                 return $loginhelp_url;                  foreach my $item (@names) {
             }                      if ($sessiondata{$item} ne '') {
         }                          $form{$item} = $sessiondata{$item};
         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};                      }
         if ($loginhelp_url ne '') {                  }
             return $loginhelp_url;              }
         } else {          }
             return '/adm/loginproblems.html';          if ($form{'linkprot'}) {
         }              my ($linkprotector,$uri) = split(/:/,$form{'linkprot'},2);
     }              if ($linkprotector) {
     return;                  $extra_env = {'user.linkprotector' => $linkprotector,
 }                                'user.linkproturi'   => $uri};
               }
 sub alternate_unames_check {          } elsif ($form{'linkkey'} ne '') {
     my ($uname,$udom) = @_;              $extra_env = {'user.deeplinkkey'  => $form{'linkkey'},
     my %possunames;                            'user.keyedlinkuri' => $form{'firsturl'}};
     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);          }
     if (ref($domdefs{'unamemap_rule'}) eq 'ARRAY') {          if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
         if (@{$domdefs{'unamemap_rule'}} > 0) {              &set_deeplink_login(%form);
             %possunames =              if ($form{'linkprot'}) {
                 &Apache::lonnet::inst_rulecheck($udom,$uname,undef,                  if (ref($extra_env) eq 'HASH') {
                                                 'unamemap',$domdefs{'unamemap_rule'});                      %{$extra_env} = ( %{$extra_env}, 'request.linkprot' => $form{'linkprot'} );
         }                  } else {
     }                      $extra_env = {'request.linkprot' => $form{'linkprot'}};
     return %possunames;                  }
 }              } elsif ($form{'linkkey'} ne '') {
                   if (ref($extra_env) eq 'HASH') {
 1;                      %{$extra_env} = ( %{$extra_env}, 'request.linkkey' => $form{'linkkey'} );
 __END__                  } else {
                       $extra_env = {'request.linkkey' => $form{'linkkey'}};
                   }
               }
               if ($env{'request.deeplink.login'}) {
                   if (ref($extra_env) eq 'HASH') {
                       %{$extra_env} = ( %{$extra_env}, 'request.deeplink.login' => $form{'firsturl'} );
                   } else {
                       $extra_env = {'request.deeplink.login' => $form{'firsturl'}};
                   }
               }
           }
           &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,$extra_env,
                    \%form);
           return OK;
       }
   }
   
   sub get_form_items {
       my ($r) = @_;
       my $buffer;
       if ($r->header_in('Content-length') > 0) {
           $r->read($buffer,$r->header_in('Content-length'),0);
       }
       my %form;
       foreach my $pair (split(/&/,$buffer)) {
          my ($name,$value) = split(/=/,$pair);
          $value =~ tr/+/ /;
          $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
          $form{$name}=$value;
       }
       return %form;
   }
   
   sub set_deeplink_login {
       my (%form) = @_;
       my $disallow;
       if ($form{'firsturl'} =~ m{^/tiny/($match_domain)/\w+$}) {
           my $cdom = $1;
           my ($cnum,$symb) = &Apache::loncommon::symb_from_tinyurl($form{'firsturl'},'',$cdom);
           if ($symb) {
               if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   my $deeplink;
                   if ($symb =~ /\.(page|sequence)$/) {
                       my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($symb))[2]);
                       my $navmap = Apache::lonnavmaps::navmap->new();
                       if (ref($navmap)) {
                           $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                       }
                   } else {
                       $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   }
                   if ($deeplink ne '') {
                       my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                       if (($protect ne 'none') && ($protect ne '')) {
                           my ($acctype,$item) = split(/:/,$protect);
                           if ($acctype =~ /lti(c|d)$/) {
                               unless ($form{'linkprot'} eq $item.$1.':'.$env{'request.deeplink.login'}) {
                                   $disallow = 1;
                               }
                           } elsif ($acctype eq 'key') {
                               unless ($form{'linkkey'} eq $item) {
                                   $disallow = 1;
                               }
                           }
                       }
                   }
                   unless ($disallow) {
                       $env{'request.deeplink.login'} = $form{'firsturl'};
                   }
               } else {
                   $env{'request.deeplink.login'} = $form{'firsturl'};
               }
           }
       }
       if ($disallow) {
           return;
       }
       return 'ok';
   }
   
   sub set_retry_token {
       my ($form,$lonhost,$querystr) = @_;
       if (ref($form) eq 'HASH') {
           my ($firsturl,$token,$extras,@names);
           @names = ('role','symb','linkprot','linkkey','iptoken');
           foreach my $name (@names) {
               if ($form->{$name} ne '') {
                   $extras .= '&'.$name.'='.&escape($form->{$name});
                   last if ($name eq 'linkprot');
               }
           }
           my $firsturl = $form->{'firsturl'};
           if (($firsturl ne '') || ($extras ne '')) {
               $extras .= ':retry';
               $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).
                                               $extras,$lonhost);
               if (($token eq 'con_lost') || ($token eq 'no_such_host')) {
                   return 'fail';
               } else {
                   if (ref($querystr)) {
                       $$querystr = 'retry='.$token;
                   }
                   return 'ok';
               }
           }
       }
       return;
   }
   
   sub check_can_host {
       my ($r,$form,$authhost,$domdesc) = @_;
       return unless (ref($form) eq 'HASH');
       my $canhost = 1;
       my $lonhost = $r->dir_config('lonHostID');
       my $udom = $form->{'udom'};
       my @intdoms;
       my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
       if (ref($internet_names) eq 'ARRAY') {
           @intdoms = @{$internet_names};
       }
       my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
       my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
       unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
           my $machine_dom = &Apache::lonnet::host_domain($lonhost);
           my $hostname = &Apache::lonnet::hostname($lonhost);
           my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
           my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
           my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
           my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
           my $loncaparev;
           if ($authhost eq 'no_account_on_host') {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
           } else {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
           }
           $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
                                                        $udomdefaults{'remotesessions'},
                                                        $defdomdefaults{'hostedsessions'});
       }
       unless ($canhost) {
           if ($authhost eq 'no_account_on_host') {
               my $checkloginvia = 1;
               my ($login_host,$hostname) =
                   &Apache::lonnet::choose_server($udom,$checkloginvia);
               &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
               if ($login_host ne '') {
                   my $protocol = $Apache::lonnet::protocol{$login_host};
                   $protocol = 'http' if ($protocol ne 'https');
                   my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);
                   $hostname = $alias if ($alias ne '');
                   my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
   #FIXME Should preserve where user was going and linkprot by setting ltoken at $login_host
                   $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
                             '<h3>'.&mt('Account creation').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
                             '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
                             &Apache::loncommon::end_page());
               } else {
                   $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                             '<h3>'.&mt('Account creation unavailable').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<p>'.&mt('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.
                             &Apache::loncommon::end_page());
               }
           } else {
               &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
                        $form);
               if ($form->{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                   $env{'request.deeplink.login'} = $form->{'firsturl'};
               }
               if ($form->{'linkprot'}) {
                   $env{'request.linkprot'} = $form->{'linkprot'};
               } elsif ($form->{'linkkey'} ne '') {
                   $env{'request.linkkey'} = $form->{'linkkey'};
               }
               my ($otherserver) = &Apache::lonnet::choose_server($udom);
               $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
           }
       }
       return $canhost;
   }
   
   sub noswitch {
       my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                    '<h3>'.&mt('Session unavailable').'</h3>'.
                    &mt('This LON-CAPA server is unable to host your session.').'<br />'.
                    '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
                    &Apache::loncommon::end_page();
       return $result;
   }
   
   sub loginhelpdisplay {
       my ($authdomain) = @_;
       my $login_help = 1;
       my $lang = &Apache::lonlocal::current_language();
       if ($login_help) {
           my $dom = $authdomain;
           if ($dom eq '') {
               $dom = &Apache::lonnet::default_login_domain();
           }
           my %domconfhash = &Apache::loncommon::get_domainconf($dom);
           my $loginhelp_url;
           if ($lang) {
               $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
               if ($loginhelp_url ne '') {
                   return $loginhelp_url;
               }
           }
           $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
           if ($loginhelp_url ne '') {
               return $loginhelp_url;
           } else {
               return '/adm/loginproblems.html';
           }
       }
       return;
   }
   
   1;
   __END__
   
   

Removed from v.1.121.2.26  
changed lines
  Added in v.1.170


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>