Diff for /loncom/auth/lonauth.pm between versions 1.121.2.24.2.7 and 1.142

version 1.121.2.24.2.7, 2023/07/05 17:33:03 version 1.142, 2017/02/17 14:34:21
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 DynaLoader; # for Crypt::DES version
 use Apache::lonnet;  use Crypt::DES;
 use Apache::lonmenu();  use Apache::loncommon();
 use Apache::createaccount;  use Apache::lonnet;
 use Apache::ltiauth;  use Apache::lonmenu();
 use Fcntl qw(:flock);  use Apache::createaccount;
 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();   
    # ------------------------------------------------------------ Successful login
 # ------------------------------------------------------------ Successful login  sub success {
 sub success {      my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,   $form) = @_;
  $form,$skipcritical,$cid,$expirepub,$write_to_opener) = @_;  
   # ------------------------------------------------------------ Get cookie ready
 # ------------------------------------------------------------ Get cookie ready      my $cookie =
     my $cookie =   &Apache::loncommon::init_user_environment($r, $username, $domain,
  &Apache::loncommon::init_user_environment($r, $username, $domain,    $authhost, $form,
   $authhost, $form,    {'extra_env' => $extra_env,});
   {'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  
       &Apache::lonnet::log($domain,$username,$authhost,
     my $ip = &Apache::lonnet::get_requestor_ip();                           "Login $ENV{'REMOTE_ADDR'}");
     &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 cookie ready
         }      $cookie="lonID=$cookie; path=/; HttpOnly";
     }  # -------------------------------------------------------- Menu script and info
       my $destination = $lowerurl;
 # ------------------------------------------------------------ Get cookies ready  
     my ($securecookie,$defaultcookie);      if (defined($form->{role})) {
     my $ssl = $r->subprocess_env('https');          my $envkey = 'user.role.'.$form->{role};
     if ($ssl) {          my $now=time;
         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";          my $then=$env{'user.login.time'};
         my $lonidsdir=$r->dir_config('lonIDsDir');          my $refresh=$env{'user.refresh.time'};
         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {          my $update=$env{'user.update.time'};
             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';          if (!$update) {
             if (-e "$lonidsdir/$linkname.id") {              $update = $then;
                 unlink("$lonidsdir/$linkname.id");          }
             }          if (exists($env{$envkey})) {
             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
                                               "$lonidsdir/$linkname.id"); 1 };              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
             if ($made_symlink) {                                           \$trolecode,\$tstatus,\$tstart,\$tend);
                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";              if ($tstatus eq 'is') {
                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
             }                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
         }                  $destination .= 'selectrole=1&'.$newrole.'=1';
     } else {              }
         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";          }
     }      }
 # -------------------------------------------------------- Menu script and info      if (defined($form->{symb})) {
     my $destination = $lowerurl;          my $destsymb = $form->{symb};
     if ($env{'request.lti.login'}) {          $destination  .= ($destination =~ /\?/) ? '&' : '?';
         if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {          if ($destsymb =~ /___/) {
             &Apache::loncommon::content_type($r,'text/html');              # FIXME Need to deal with encrypted symbs and urls as needed.
             if ($securecookie) {              my ($map,$resid,$desturl)=split(/___/,$destsymb);
                 $r->headers_out->add('Set-cookie' => $securecookie);              $desturl = &Apache::lonnet::clutter($desturl);
             }              $desturl = &HTML::Entities::encode($desturl,'"<>&');
             if ($defaultcookie) {              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
                 $r->headers_out->add('Set-cookie' => $defaultcookie);              $destination .= 'destinationurl='.$desturl.
             }                              '&destsymb='.$destsymb;
             $r->send_http_header;          } else {
             if (ref($form) eq 'HASH') {              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
                 $form->{'lti.login'} = $env{'request.lti.login'};              $destination .= 'destinationurl='.$destsymb;
                 $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};          }
                 $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};      }
                 $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};      if ($destination =~ m{^/adm/roles}) {
             }          $destination  .= ($destination =~ /\?/) ? '&' : '?';
             &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);          $destination .= 'source=login';
             return;      }
         }  
         if ($env{'request.lti.selfenrollrole'}) {      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="loncapaclient";');
             if (&Apache::ltiauth::lti_enroll($username,$domain,      my $header = '<meta HTTP-EQUIV="Refresh" CONTENT="0; url='.$destination.'" />';
                                              $env{'request.lti.selfenrollrole'}) eq 'ok') {      my $brcrum = [{'href' => '',
                 $form->{'role'} = $env{'request.lti.selfenrollrole'};                     'text' => 'Successful Login'},];
                 &Apache::lonnet::delenv('request.lti.selfenrollrole');      my $args = {'bread_crumbs' => $brcrum,};
             } else {      unless ((defined($form->{role})) || (defined($form->{symb}))) {
                 &Apache::ltiauth::invalid_request($r,24);          my $update=$env{'user.update.time'};
             }          if (!$update) {
         }              $update = $env{'user.login.time'};
     }          }
     if (defined($form->{role})) {          my %roles_in_env;
         my $envkey = 'user.role.'.$form->{role};          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
         my $now=time;          if ($showcount == 1) {
         my $then=$env{'user.login.time'};              foreach my $rolecode (keys(%roles_in_env)) {
         my $refresh=$env{'user.refresh.time'};                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
         my $update=$env{'user.update.time'};                  if ($cid) {
         if (!$update) {                      my %coursedescription =
             $update = $then;                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
         }                      if ($coursedescription{'type'} eq 'Placement') {
         if (exists($env{$envkey})) {                          $args->{'crstype'} = 'Placement';
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);                      }
             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,                      last;
                                          \$trolecode,\$tstatus,\$tstart,\$tend);                  }
             if ($tstatus eq 'is') {              }
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';          }
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');      }
                 $destination .= 'selectrole=1&'.$newrole.'=1';      my $start_page=&Apache::loncommon::start_page('Successful Login',
             }                                                    $header,$args);
         }      my $end_page  =&Apache::loncommon::end_page();
     } elsif (defined($form->{display})) {  
         if ($destination =~ m{^/adm/email($|\?)}) {   my $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
             $destination  .= ($destination =~ /\?/) ? '&' : '?' .'display='.&escape($form->{display});  # ------------------------------------------------- Output for successful login
         }  
     }      &Apache::loncommon::content_type($r,'text/html');
     if (defined($form->{symb})) {      $r->header_out('Set-cookie' => $cookie);
         my $destsymb = $form->{symb};      $r->send_http_header;
         my $encrypted;  
         if ($destsymb =~ m{^/enc/}) {      my %lt=&Apache::lonlocal::texthash(
             $encrypted = 1;         'wel' => 'Welcome',
             if ($cid) {         'pro' => 'Login problems?',
                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);         );
             }      my $loginhelp = &loginhelpdisplay($domain);
         }      if ($loginhelp) {
         $destination  .= ($destination =~ /\?/) ? '&' : '?';          $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
         if ($destsymb =~ /___/) {      }
             my ($map,$resid,$desturl)=split(/___/,$destsymb);  
             $desturl = &Apache::lonnet::clutter($desturl);      my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
             if ($encrypted) {      $r->print(<<ENDSUCCESS);
                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);  $start_page
                 $destsymb = $form->{symb};  $windowinfo
             }  <h1>$lt{'wel'}</h1>
             $desturl = &HTML::Entities::encode($desturl,'"<>&');  $welcome
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');  $loginhelp
             $destination .= 'destinationurl='.$desturl.  $continuelink
                             '&destsymb='.$destsymb;  $end_page
         } elsif (!$encrypted) {  ENDSUCCESS
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');      return;
             $destination .= 'destinationurl='.$destsymb;  }
         }  
     }  # --------------------------------------------------------------- Failed login!
     if ($destination =~ m{^/adm/roles}) {  
         $destination  .= ($destination =~ /\?/) ? '&' : '?';  sub failed {
         $destination .= 'source=login';      my ($r,$message,$form) = @_;
     }      (undef,undef,undef,my $clientmathml,my $clientunicode) =
           &Apache::loncommon::decode_user_agent();
     my $brcrum = [{'href' => '',      my $args = {};
                    'text' => 'Successful Login'},];      if ($clientunicode && !$clientmathml) {
     my $args = {'no_inline_link' => 1,          $args = {'browser.unicode' => 1};
                 'bread_crumbs' => $brcrum,};      }
     if (($env{'request.deeplink.login'} eq $lowerurl) &&  
         (($env{'request.linkprot'}) || ($env{'request.linkkey'} ne ''))) {      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
         my %info;      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
         if ($env{'request.linkprot'}) {      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
             $info{'linkprot'} = $env{'request.linkprot'};      if (&Apache::lonnet::domain($udom,'description') eq '') {
             foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {          undef($udom);
                 if ($form->{$item}) {      }
                     $info{$item} = $form->{$item};      my $retry = '/adm/login';
                 }      if ($uname eq $form->{'uname'}) {
             }          $retry .= '?username='.$uname;
             $args = {'only_body' => 1,};      }
         } elsif ($env{'request.linkkey'} ne '') {      if ($udom) {
             $info{'linkkey'} = $env{'request.linkkey'};          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
         }      }
         $info{'origurl'} = $lowerurl;      if (exists($form->{role})) {
         my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');          my $role = &Apache::loncommon::cleanup_html($form->{role});
         unless (($token eq 'con_lost') || ($token eq 'refused') ||          if ($role ne '') {
                 ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {              $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
             $destination .= (($destination =~ /\?/) ? '&' : '?') . 'ttoken='.$token;          }
         }      }
     }      if (exists($form->{symb})) {
     if (($env{'request.deeplink.login'}) || ($env{'request.lti.login'})) {          my $symb = &Apache::loncommon::cleanup_html($form->{symb});
         if ($env{'environment.remote'} eq 'on') {          if ($symb ne '') {
             &Apache::lonnet::appenv({'environment.remote' => 'off'});              $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
         }          }
     }      }
     my $startupremote;      my $end_page = &Apache::loncommon::end_page();
     if ($write_to_opener) {      &Apache::loncommon::content_type($r,'text/html');
         if ($env{'environment.remote'} eq 'on') {      $r->send_http_header;
             &Apache::lonnet::appenv({'environment.remote' => 'off'});      my @actions =
         }           (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
         $args->{'redirect'} = [0,$destination,'',$write_to_opener];      my $loginhelp = &loginhelpdisplay($udom);
     } else {      if ($loginhelp) {
         $startupremote=&Apache::lonmenu::startupremote($destination);          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
     }      }
       #FIXME: link to helpdesk might be added here
     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});  
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);      $r->print(
     my $setflags=&Apache::lonmenu::setflags();         $start_page
     my $maincall=&Apache::lonmenu::maincall();        .'<h2>'.&mt('Sorry ...').'</h2>'
     my $start_page=&Apache::loncommon::start_page('Successful Login',        .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
                                                   $startupremote,$args);        .&Apache::lonhtmlcommon::actionbox(\@actions)
     my $end_page  =&Apache::loncommon::end_page();        .$end_page
       );
     my $continuelink;   }
     if ($env{'environment.remote'} eq 'off') {  
         unless ($write_to_opener) {  # ------------------------------------------------------------------ Rerouting!
     $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';  
         }  sub reroute {
     }      my ($r) = @_;
 # ------------------------------------------------- Output for successful login      &Apache::loncommon::content_type($r,'text/html');
       $r->send_http_header;
     &Apache::loncommon::content_type($r,'text/html');      my $msg='<b>'.&mt('Sorry ...').'</b><br />'
     if ($securecookie) {             .&mt('Please [_1]log in again[_2].');
         $r->headers_out->add('Set-cookie' => $securecookie);      &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
     }  }
     if ($defaultcookie) {  
         $r->headers_out->add('Set-cookie' => $defaultcookie);  # ---------------------------------------------------------------- Main handler
     }  
     if ($expirepub) {  sub handler {
         my $c = new CGI::Cookie(-name    => 'lonPubID',      my $r = shift;
                                 -value   => '',      my $londocroot = $r->dir_config('lonDocRoot');
                                 -expires => '-10y',);  # Are we re-routing?
         $r->headers_out->add('Set-cookie' => $c);      if (-e "$londocroot/lon-status/reroute.txt") {
     }   &reroute($r);
     $r->send_http_header;   return OK;
       }
     if (($env{'request.linkprot'}) || ($env{'request.lti.login'})) {  
         $r->print(<<END);      &Apache::lonlocal::get_language_handle($r);
 $start_page  
 <br />$continuelink  # -------------------------------- Prevent users from attempting to login twice
 $end_page      my $handle = &Apache::lonnet::check_for_valid_session($r);
 END      if ($handle ne '') {
     } else {          my $lonidsdir=$r->dir_config('lonIDsDir');
         my %lt=&Apache::lonlocal::texthash(          if ($handle=~/^publicuser\_/) {
            'wel' => 'Welcome',  # For "public user" - remove it, we apparently really want to login
            'pro' => 'Login problems?',              unlink($r->dir_config('lonIDsDir')."/$handle.id");
           );          } else {
         my $loginhelp = &loginhelpdisplay($domain);  # Indeed, a valid token is found
         if ($loginhelp) {              &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
             $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';      &Apache::loncommon::content_type($r,'text/html');
         }      $r->send_http_header;
       my $start_page =
         my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');           &Apache::loncommon::start_page('Already logged in');
         $r->print(<<ENDSUCCESS);      my $end_page =
 $start_page          &Apache::loncommon::end_page();
 $setflags              my $dest = '/adm/roles';
 $windowinfo              if ($env{'form.firsturl'} ne '') {
 <h1>$lt{'wel'}</h1>                  $dest = $env{'form.firsturl'};
 $welcome              }
 $loginhelp              $r->print(
 $remoteinfo                 $start_page
 $maincall                .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
 $continuelink                .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
 $end_page                      ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
 ENDSUCCESS                .'</p>'
     }                .$end_page
     return;              );
 }              return OK;
           }
 # --------------------------------------------------------------- Failed login!      }
   
 sub failed {  # ---------------------------------------------------- No valid token, continue
     my ($r,$message,$form,$authhost) = @_;  
     (undef,undef,undef,my $clientmathml,my $clientunicode) =  
         &Apache::loncommon::decode_user_agent();      my $buffer;
     my $args = {};      if ($r->header_in('Content-length') > 0) {
     if ($clientunicode && !$clientmathml) {   $r->read($buffer,$r->header_in('Content-length'),0);
         $args = {'browser.unicode' => 1};      }
     }      my %form;
     if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {      foreach my $pair (split(/&/,$buffer)) {
         if ($form->{linkprot}) {         my ($name,$value) = split(/=/,$pair);
             $args->{only_body} = 1;         $value =~ tr/+/ /;
         }         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
     }         $form{$name}=$value;
       }
     my @actions;  
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);      if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});   &failed($r,'Username, password and domain need to be specified.',
     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});   \%form);
     if (&Apache::lonnet::domain($udom,'description') eq '') {          return OK;
         undef($udom);      }
     }  
     my $authtype;  # split user logging in and "su"-user
     if (($udom ne '') && ($uname ne '') && ($authhost eq 'no_host')) {  
         $authtype = &Apache::lonnet::queryauthenticate($uname,$udom);      ($form{'uname'},$form{'suname'})=split(/\:/,$form{'uname'});
     }      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
     my $retry = '/adm/login';      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
     if (($uname eq $form->{'uname'}) && ($authtype !~ /^lti:/)) {      $form{'udom'}  = &LONCAPA::clean_domain(  $form{'udom'});
         $retry .= '?username='.$uname;  
     }      my $role   = $r->dir_config('lonRole');
     if ($udom) {      my $domain = $r->dir_config('lonDefDomain');
         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;      my $prodir = $r->dir_config('lonUsersDir');
     }      my $contact_name = &mt('LON-CAPA helpdesk');
     my $lonhost = $r->dir_config('lonHostID');  
     my $querystr;  # ---------------------------------------- Get the information from login token
     my $result = &set_retry_token($form,$lonhost,\$querystr);  
     if ($result eq 'fail') {      my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
         if (exists($form->{role})) {                                        $form{'serverid'});
             my $role = &Apache::loncommon::cleanup_html($form->{role});  
             if ($role ne '') {      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;          ($tmpinfo eq 'no_such_host')) {
             }   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
         }          return OK;
         if (exists($form->{symb})) {      } else {
             my $symb = &Apache::loncommon::cleanup_html($form->{symb});   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
             if ($symb ne '') {     $form{'serverid'});
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;          if ( $reply ne 'ok' ) {
             }              &failed($r,'Session could not be opened.',\%form);
         }      &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
         if (exists($form->{firsturl})) {      return OK;
             my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});   }
             if ($firsturl ne '') {      }
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;  
                 if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {      if (!&Apache::lonnet::domain($form{'udom'})) {
                     unless (exists($form->{linkprot})) {          &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
                         if (exists($form->{linkkey})) {          return OK;
                             $retry .= 'linkkey='.$form->{linkkey};      }
                         }  
                     }      my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);
                 }      if ($rolestr) {
             }          $rolestr = &unescape($rolestr);
         }      }
         if (exists($form->{linkprot})) {      if ($symbstr) {
             my %info = (          $symbstr= &unescape($symbstr);
                          'linkprot' => $form->{'linkprot'},      }
                        );      if ($iptokenstr) {
             foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {          $iptokenstr = &unescape($iptokenstr);
                 if ($form->{$item} ne '') {      }
                     $info{$item} = $form->{$item};      if ($rolestr =~ /^role=/) {
                 }          (undef,$form{'role'}) = split('=',$rolestr);
             }      }
             my $ltoken = &Apache::lonnet::tmpput(\%info,      if ($symbstr =~ /^symb=/) {
                                                  $r->dir_config('lonHostID'),'retry');          (undef,$form{'symb'}) = split('=',$symbstr);
             if ($ltoken) {      }
                 $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;      if ($iptokenstr =~ /^iptoken=/) {
             }          (undef,$form{'iptoken'}) = split('=',$iptokenstr);
         }      }
     } elsif ($querystr ne '') {  
         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;      my $upass = $ENV{HTTPS} ? $form{'upass0'}
     }          : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
     my $end_page = &Apache::loncommon::end_page();  
     &Apache::loncommon::content_type($r,'text/html');  # ---------------------------------------------------------------- Authenticate
     $r->send_http_header;  
     if ($authtype =~ /^lti:/) {      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
         $message = &mt('Direct login is not supported with the username you entered.').      my ($cancreate,$statustocreate) =
                    '<br /><br />'.          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
                    &mt('You likely need to launch LON-CAPA from within a course in a different Learning Management System.').      my $defaultauth;
                    '<br />'.      if (ref($cancreate) eq 'ARRAY') {
                    &mt('You can also try to log in with a different username.');          if (grep(/^login$/,@{$cancreate})) {
         @actions =              $defaultauth = 1;
             (&mt('Try your [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));          }
     } else {      }
         $message = &mt($message);      my $clientcancheckhost = 1;
         @actions =      my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
             (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));                                                $form{'udom'},$defaultauth,
     }                                                $clientcancheckhost);
     my $loginhelp = &loginhelpdisplay($udom);     
     if ($loginhelp) {  # --------------------------------------------------------------------- Failed?
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');  
     }      if ($authhost eq 'no_host') {
     #FIXME: link to helpdesk might be added here   &failed($r,'Username and/or password could not be authenticated.',
     $r->print(   \%form);
        $start_page          return OK;
       .'<h2>'.&mt('Sorry ...').'</h2>'      } elsif ($authhost eq 'no_account_on_host') {
       .&Apache::lonhtmlcommon::confirm_success($message,1).'<br /><br />'          if ($defaultauth) {
       .&Apache::lonhtmlcommon::actionbox(\@actions)              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
       .$end_page              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
     );                  return OK;
  }              }
               my $start_page =
 # ------------------------------------------------------------------ Rerouting!                  &Apache::loncommon::start_page('Create a user account in LON-CAPA');
               my $lonhost = $r->dir_config('lonHostID');
 sub reroute {              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
     my ($r) = @_;              my $contacts =
     &Apache::loncommon::content_type($r,'text/html');                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
     $r->send_http_header;                                                          $form{'udom'},$origmail);
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'              my ($contact_email) = split(',',$contacts);
            .&mt('Please [_1]log in again[_2].');              my $output =
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
 }                                                         $domdesc,'',$lonhost,
                                                          $contact_email,$contact_name,
 # ---------------------------------------------------------------- Main handler                                                         undef,$statustocreate);
               &Apache::loncommon::content_type($r,'text/html');
 sub handler {              $r->send_http_header;
     my $r = shift;              &Apache::createaccount::print_header($r,$start_page);
     my $londocroot = $r->dir_config('lonDocRoot');              $r->print('<h3>'.&mt('Account creation').'</h3>'.
 # Are we re-routing?                        &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
     if (-e "$londocroot/lon-status/reroute.txt") {                        $output.&Apache::loncommon::end_page());
  &reroute($r);              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;
     &Apache::lonlocal::get_language_handle($r);          }
       }
 # -------------------------------- Prevent users from attempting to login twice  
     my $handle = &Apache::lonnet::check_for_valid_session($r);      if (($firsturl eq '') ||
     if ($handle ne '') {   ($firsturl=~/^\/adm\/(logout|remote)/)) {
         my $lonidsdir=$r->dir_config('lonIDsDir');   $firsturl='/adm/roles';
         if ($handle=~/^publicuser\_/) {      }
 # For "public user" - remove it, we apparently really want to login  
             unlink($r->dir_config('lonIDsDir')."/$handle.id");      my $hosthere;
         } else {      if ($form{'iptoken'}) {
 # Indeed, a valid token is found          my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);          my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
     &Apache::loncommon::content_type($r,'text/html');          if (($sessiondata{'domain'} eq $form{'udom'}) &&
     $r->send_http_header;              ($sessiondata{'username'} eq $form{'uname'})) {
     my $start_page =               $hosthere = 1;
         &Apache::loncommon::start_page('Already logged in');          }
     my $end_page =       }
         &Apache::loncommon::end_page();  
             my $dest = '/adm/roles';  # --------------------------------- Are we attempting to login as somebody else?
             my %form = &get_form_items($r);      if ($form{'suname'}) {
             if ($form{'logtoken'}) {  # ------------ see if the original user has enough privileges to pull this stunt
                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {
                                                      $form{'serverid'});  # ---------------------------------------------------- see if the su-user exists
                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||      unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})
                         ($tmpinfo eq 'no_such_host')) {   eq 'no_host') {
                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);   &Apache::lonnet::logthis(&Apache::lonnet::homeserver($form{'suname'},$form{'udom'}));
                     $firsturl = &unescape($firsturl);  # ------------------------------ see if the su-user is not too highly privileged
                     my %info;   unless (&Apache::lonnet::privileged($form{'suname'},$form{'udom'})) {
                     foreach my $item (@rest) {  # -------------------------------------------------------- actually switch users
                         my ($key,$value) = split(/=/,$item);      &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.
                         $info{$key} = &unescape($value);   ' logging in as '.$form{'suname'});
                     }      $form{'uname'}=$form{'suname'};
                     if ($firsturl ne '') {   } else {
                         $info{'firsturl'} = $firsturl;      &Apache::lonnet::logthis('Attempted switch user to privileged user');
                         $dest = $firsturl;   }
                         my $relogin;      }
                         if ($dest =~ m{^/tiny/$match_domain/\w+$}) {   } else {
                             if ($env{'request.course.id'}) {      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
                                 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);  
                                 if ($symb) {      my ($is_balancer,$otherserver);
                                     unless (&set_deeplink_login(%info) eq 'ok') {  
                                         $relogin = 1;      unless ($hosthere) {
                                     }          ($is_balancer,$otherserver) =
                                 }              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
                             }          if ($is_balancer) {
                             if ($relogin) {              if ($otherserver eq '') {
                                 $r->print(                  my $lowest_load;
                                       $start_page                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
                                      .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'                  if ($lowest_load > 100) {
                                      .'<p>'.&mt('Please [_1]log out[_2] first, and then try your access again',                      $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
                                                 '<a href="/adm/logout">','</a>')                  }
                                      .'</p>'              }
                                      .$end_page);              if ($otherserver ne '') {
                             } else {                  my @hosts = &Apache::lonnet::current_machine_ids();
                                 if (($info{'linkprot'}) || ($info{'linkkey'} ne '')) {                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
                                     if (($info{'linkprot'}) && ($info{'linkprotuser'} ne '')) {                      $hosthere = $otherserver;
                                         unless ($info{'linkprotuser'} eq $env{'user.name'}.':'.$env{'user.domain'}) {                  }
                                             $r->print(              }
                                                       $start_page          }
                                                       .'<p class="LC_warning">'.&mt('You are already logged in, but as a different user from the one expected for the link you followed from another system').'</p>'      }
                                                       .'<p>'.&mt('Please [_1]log out[_2] first, and then try following the link again from the other system',  
                                                                  '<a href="/adm/logout">','</a>')      if (($is_balancer) && (!$hosthere)) {
           if ($otherserver) {
                                                       .'</p>'              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                                                       .$end_page);                       \%form);
                                             return OK;              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                                         }              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                                     }                  $switchto .= '&origurl='.$firsturl;
                                     my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');              }
                                     unless (($token eq 'con_lost') || ($token eq 'refused') ||              if ($form{'role'}) {
                                             ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {                  $switchto .= '&role='.$form{'role'};
                                         $dest .= (($dest =~ /\?/) ? '&' : '?') . 'ttoken='.$token;              }
                                     }              if ($form{'symb'}) {
                                 }                  $switchto .= '&symb='.$form{'symb'};
                                 $r->print(              }
                                       $start_page              $r->internal_redirect($switchto);
                                      .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'          } else {
                                      .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4] first, and then try your access again',              $r->print(&noswitch());
                                                 '<a href="'.$dest.'">','</a>',          }
                                                 '<a href="/adm/logout">','</a>')          return OK;
                                      .'</p>'      } else {
                                      .$end_page);          if (!&check_can_host($r,\%form,$authhost)) {
                             }              my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
                             return OK;              if ($otherserver) {
                         }                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                     }                           \%form);
                 }                  my $switchto = '/adm/switchserver?otherserver='.$otherserver;
             }                  if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
             $r->print(                      $switchto .= '&origurl='.$firsturl;
                $start_page                  }
               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'                  if ($form{'role'}) {
               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'                      $switchto .= '&role='.$form{'role'};
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')                  }
               .'</p>'                  if ($form{'symb'}) {
               .$end_page                      $switchto .= '&symb='.$form{'symb'};
             );                  }
             return OK;                  $r->internal_redirect($switchto);
         }              } else {
     }                  $r->print(&noswitch());
               }
 # ---------------------------------------------------- No valid token, continue              return OK;
           }
     my %form = &get_form_items($r);  
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {  # ------------------------------------------------------- Do the load balancing
  &failed($r,'Username, password and domain need to be specified.',  
  \%form);  # ---------------------------------------------------------- Determine own load
         return OK;          my $loadlim = $r->dir_config('lonLoadLim');
     }          my $loadavg;
           {
 # split user logging in and "su"-user              my $loadfile=Apache::File->new('/proc/loadavg');
               $loadavg=<$loadfile>;
     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});          }
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});          $loadavg =~ s/\s.*//g;
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});          my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});          my $userloadpercent=&Apache::lonnet::userload();
     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});  
   # ---------------------------------------------------------- Are we overloaded?
     my $role   = $r->dir_config('lonRole');          if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
     my $domain = $r->dir_config('lonDefDomain');              my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
     my $prodir = $r->dir_config('lonUsersDir');              if (!$unloaded) {
     my $contact_name = &mt('LON-CAPA helpdesk');                  ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
               }
 # ---------------------------------------- Get the information from login token              if ($unloaded) {
                   &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},                           undef,\%form);
                                       $form{'serverid'});                  $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                   return OK;
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||               }
         ($tmpinfo eq 'no_such_host')) {          }
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);          if (($is_balancer) && ($hosthere)) {
         return OK;              $form{'noloadbalance'} = $hosthere;
     } else {          }
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},          &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
    $form{'serverid'});                   \%form);
         if ( $reply ne 'ok' ) {          return OK;
             &failed($r,'Session could not be opened.',\%form);      }
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");  }
     return OK;  
  }  sub check_can_host {
     }      my ($r,$form,$authhost,$domdesc) = @_;
       return unless (ref($form) eq 'HASH');
     if (!&Apache::lonnet::domain($form{'udom'})) {      my $canhost = 1;
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);      my $lonhost = $r->dir_config('lonHostID');
         return OK;      my $udom = $form->{'udom'};
     }      my @intdoms;
       my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);      if (ref($internet_names) eq 'ARRAY') {
     $firsturl = &unescape($firsturl);          @intdoms = @{$internet_names};
     foreach my $item (@rest) {      }
         my ($key,$value) = split(/=/,$item);      my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
         $form{$key} = &unescape($value);      my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
     }      unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
     if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {          my $machine_dom = &Apache::lonnet::host_domain($lonhost);
         $form{'firsturl'} = $firsturl;          my $hostname = &Apache::lonnet::hostname($lonhost);
     }          my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
     my $upass = &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});          my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
           my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 # ---------------------------------------------------------------- Authenticate          my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
           my $loncaparev;
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});          if ($authhost eq 'no_account_on_host') {
     my ($cancreate,$statustocreate) =              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});          } else {
     my $defaultauth;              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
     if (ref($cancreate) eq 'ARRAY') {          }
         if (grep(/^login$/,@{$cancreate})) {          $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
             $defaultauth = 1;                                                       $udomdefaults{'remotesessions'},
         }                                                       $defdomdefaults{'hostedsessions'});
     }      }
     my $clientcancheckhost = 1;      unless ($canhost) {
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,          if ($authhost eq 'no_account_on_host') {
                                               $form{'udom'},$defaultauth,              my $checkloginvia = 1;
                                               $clientcancheckhost);              my ($login_host,$hostname) =
                       &Apache::lonnet::choose_server($udom,$checkloginvia);
 # --------------------------------------------------------------------- Failed?              &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
     if ($authhost eq 'no_host') {              if ($login_host ne '') {
         my $pwdverify;                  my $protocol = $Apache::lonnet::protocol{$login_host};
         if (&Apache::lonnet::homeserver($form{'uname'},$form{'udom'}) eq 'no_host') {                  $protocol = 'http' if ($protocol ne 'https');
             my %possunames = &alternate_unames_check($form{'uname'},$form{'udom'});                  my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
             if (keys(%possunames) > 0) {                  $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
                 foreach my $rulematch (keys(%possunames)) {                            '<h3>'.&mt('Account creation').'</h3>'.
                     my $possuname = $possunames{$rulematch};                            &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                     if (($possuname ne '') && ($possuname =~ /^$match_username$/)) {                            '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
                         $authhost=Apache::lonnet::authenticate($possuname,$upass,                            '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
                                                                $form{'udom'},undef,                            &Apache::loncommon::end_page());
                                                                $clientcancheckhost);              } else {
                         if (($authhost eq 'no_host') || ($authhost eq 'no_account_on_host')) {                  $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                             next;                            '<h3>'.&mt('Account creation unavailable').'</h3>'.
                         } elsif (($authhost ne '') && (&Apache::lonnet::hostname($authhost) ne '')) {                            &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             $pwdverify = 1;                            '<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::lonnet::logthis("Authenticated user: $possuname was submitted as: $form{'uname'}");                            &Apache::loncommon::end_page());
                             $form{'uname'} = $possuname;              }
                             last;          } else {
                         }              &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
                     }                       $form);
                 }              my ($otherserver) = &Apache::lonnet::choose_server($udom);
             }              $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
         }          }
         unless ($pwdverify) {      }
             &failed($r,'Username and/or password could not be authenticated.',      return $canhost;
                     \%form,$authhost);  }
             return OK;  
         }  sub noswitch {
     } elsif ($authhost eq 'no_account_on_host') {      my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
         if ($defaultauth) {                   '<h3>'.&mt('Session unavailable').'</h3>'.
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');                   &mt('This LON-CAPA server is unable to host your session.').'<br />'.
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {                   '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
                 return OK;                   &Apache::loncommon::end_page();
             }      return $result;
             my $start_page =   }
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',  
                                                '',{'no_inline_link'   => 1,});  sub loginhelpdisplay {
             my $lonhost = $r->dir_config('lonHostID');      my ($authdomain) = @_;
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};      my $login_help = 1;
             my $contacts =       my $lang = &Apache::lonlocal::current_language();
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',      if ($login_help) {
                                                         $form{'udom'},$origmail);          my $dom = $authdomain;
             my ($contact_email) = split(',',$contacts);           if ($dom eq '') {
             my $output =               $dom = &Apache::lonnet::default_login_domain();
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},          }
                                                        $domdesc,'',$lonhost,          my %domconfhash = &Apache::loncommon::get_domainconf($dom);
                                                        $contact_email,$contact_name,          my $loginhelp_url;
                                                        undef,$statustocreate);          if ($lang) {
             &Apache::loncommon::content_type($r,'text/html');              $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
             $r->send_http_header;              if ($loginhelp_url ne '') {
             &Apache::createaccount::print_header($r,$start_page);                  return $loginhelp_url;
             $r->print('<h3>'.&mt('Account creation').'</h3>'.              }
                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.          }
                       $output.&Apache::loncommon::end_page());          $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
             return OK;          if ($loginhelp_url ne '') {
         } else {              return $loginhelp_url;
             &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);          } else {
             return OK;              return '/adm/loginproblems.html';
         }          }
     }      }
       return;
     if (($firsturl eq '') ||   }
  ($firsturl=~/^\/adm\/(logout|remote)/)) {  
  $firsturl='/adm/roles';  1;
     }  __END__
   
     my ($hosthere,%sessiondata);  
     if ($form{'iptoken'}) {  
         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});  
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});  
         if (($sessiondata{'domain'} eq $form{'udom'}) &&  
             ($sessiondata{'username'} eq $form{'uname'})) {  
             $hosthere = 1;  
         }  
     }  
   
 # --------------------------------- Are we attempting to login as somebody else?  
     if ($form{'suname'}) {  
         my ($suname,$sudom,$sudomref);  
         $suname = $form{'suname'};  
         $sudom = $form{'udom'};  
         if ($form{'sudom'}) {  
             unless ($sudom eq $form{'sudom'}) {  
                 if (&Apache::lonnet::domain($form{'sudom'})) {  
                     $sudomref = [$form{'sudom'}];  
                     $sudom = $form{'sudom'};  
                 }  
             }  
         }  
 # ------------ see if the original user has enough privileges to pull this stunt  
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {  
 # ---------------------------------------------------- see if the su-user exists  
     unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {  
 # ------------------------------ see if the su-user is not too highly privileged  
  if (&Apache::lonnet::privileged($suname,$sudom)) {  
                     &Apache::lonnet::logthis('Attempted switch user to privileged user');  
                 } else {  
                     my $noprivswitch;  
 #  
 # su-user's home server and user's home server must have one of:  
 # (a) same domain  
 # (b) same primary library server for the two domains  
 # (c) same "internet domain" for primary library server(s) for home servers' domains  
 #  
                     my $suprim = &Apache::lonnet::domain($sudom,'primary');  
                     my $suintdom = &Apache::lonnet::internet_dom($suprim);  
                     unless ($sudom eq $form{'udom'}) {  
                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');  
                         my $uintdom = &Apache::lonnet::internet_dom($uprim);  
                         unless ($suprim eq $uprim) {  
                             unless ($suintdom eq $uintdom) {  
                                 &Apache::lonnet::logthis('Attempted switch user '  
                                    .'to user with different "internet domain".');  
                                 $noprivswitch = 1;  
                             }  
                         }  
                     }  
   
                     unless ($noprivswitch) {  
 #  
 # server where log-in occurs must have same "internet domain" as su-user's home  
 # server  
 #  
                         my $lonhost = $r->dir_config('lonHostID');  
                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);  
                         if ($hostintdom ne $suintdom) {  
                             &Apache::lonnet::logthis('Attempted switch user on a '  
                                 .'server with a different "internet domain".');  
                         } else {  
   
 # -------------------------------------------------------- actually switch users  
   
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.  
  $form{'udom'}.' logging in as '.$suname.':'.$sudom);  
     $form{'uname'}=$suname;  
                             if ($form{'udom'} ne $sudom) {  
                                 $form{'udom'}=$sudom;  
                             }  
                         }  
                     }  
  }  
     }  
  } else {  
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');  
  }  
     }  
   
     if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {  
         if (($form{'linkprot'}) && ($form{'linkprotuser'} ne '')) {  
             unless($form{'linkprotuser'} eq $form{'uname'}.':'.$form{'udom'}) {  
                 delete($form{'udom'});  
                 delete($form{'uname'});  
                 &failed($r,'Username and/or domain are different to that expected for the link you followed from another system',  
                         \%form,$authhost);  
                 return OK;  
             }  
         }  
     }  
   
     my ($is_balancer,$otherserver);  
   
     unless ($hosthere) {  
         ($is_balancer,$otherserver) =  
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');  
         if ($is_balancer) {  
             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)  
             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);  
             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {  
                 $otherserver = $found_server;  
             }  
             if ($otherserver eq '') {  
                 my $lowest_load;  
                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});  
                 if ($lowest_load > 100) {  
                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});  
                 }  
             }  
             if ($otherserver ne '') {  
                 my @hosts = &Apache::lonnet::current_machine_ids();  
                 if (grep(/^\Q$otherserver\E$/,@hosts)) {  
                     $hosthere = $otherserver;  
                 }  
             }  
         }  
     }  
   
     if (($is_balancer) && (!$hosthere)) {  
         if ($otherserver) {  
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,  
                      \%form);  
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;  
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {  
                 $switchto .= '&origurl='.$firsturl;  
             }  
             if ($form{'role'}) {  
                 $switchto .= '&role='.$form{'role'};  
             }  
             if ($form{'symb'}) {  
                 $switchto .= '&symb='.$form{'symb'};  
             }  
             if ($form{'linkprot'}) {  
                 $env{'request.linkprot'} = $form{'linkprot'};  
                 foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {  
                     if ($form{$item}) {  
                         $env{'request.'.$item} = $form{$item};  
                     }  
                 }  
             } elsif ($form{'linkkey'} ne '') {  
                 $env{'request.linkkey'} = $form{'linkkey'};  
             }  
             if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {  
                 &set_deeplink_login(%form);  
             } elsif ($firsturl eq '/adm/email') {  
                 if ($form{'display'} && ($form{'mailrecip'} eq "$form{'uname'}:$form{'udom'}")) {  
                     $env{'request.display'} = $form{'display'};  
                     $env{'request.mailrecip'} = $form{'mailrecip'};  
                 }  
             }  
             $r->internal_redirect($switchto);  
         } else {  
             &Apache::loncommon::content_type($r,'text/html');  
             $r->send_http_header;  
             $r->print(&noswitch());  
         }  
         return OK;  
     } else {  
         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,  
                          \%form);  
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;  
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {  
                     $switchto .= '&origurl='.$firsturl;  
                 }  
                 if ($form{'role'}) {  
                     $switchto .= '&role='.$form{'role'};  
                 }  
                 if ($form{'symb'}) {  
                     $switchto .= '&symb='.$form{'symb'};  
                 }  
                 if ($form{'linkprot'}) {  
                     $env{'request.linkprot'} = $form{'linkprot'};  
                     foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {  
                         if ($form{$item}) {  
                             $env{'request.'.$item} = $form{$item};  
                         }  
                     }  
                 } elsif ($form{'linkkey'} ne '') {  
                     $env{'request.linkkey'} = $form{'linkkey'};  
                 }  
                 if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {  
                     &set_deeplink_login(%form);  
                 } elsif ($firsturl eq '/adm/email') {  
                     if ($form{'display'} && ($form{'mailrecip'} eq "$form{'uname'}:$form{'udom'}")) {  
                         $env{'request.display'} = $form{'display'};  
                         $env{'request.mailrecip'} = $form{'mailrecip'};  
                     }  
                 }  
                 $r->internal_redirect($switchto);  
             } else {  
                 &Apache::loncommon::content_type($r,'text/html');  
                 $r->send_http_header;  
                 $r->print(&noswitch());  
             }  
             return OK;  
         }  
   
 # ------------------------------------------------------- Do the load balancing  
   
 # ---------------------------------------------------------- Determine own load  
         my $loadlim = $r->dir_config('lonLoadLim');  
         my $loadavg;  
         {  
             my $loadfile=Apache::File->new('/proc/loadavg');  
             $loadavg=<$loadfile>;  
         }  
         $loadavg =~ s/\s.*//g;  
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);  
         my $userloadpercent=&Apache::lonnet::userload();  
   
 # ---------------------------------------------------------- Are we overloaded?  
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {  
             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});  
             if (!$unloaded) {  
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});  
             }  
             if ($unloaded) {  
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',  
                          undef,\%form);  
                 if ($form{'linkprot'}) {  
                     $env{'request.linkprot'} = $form{'linkprot'};  
                 } elsif ($form{'linkkey'} ne '') {  
                     $env{'request.linkkey'} = $form{'linkkey'};  
                 }  
                 if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {  
                     &set_deeplink_login(%form);  
                 } elsif ($firsturl eq '/adm/email') {  
                     if ($form{'display'} && ($form{'mailrecip'} eq "$form{'uname'}:$form{'udom'}")) {  
                         $env{'request.display'} = $form{'display'};  
                         $env{'request.mailrecip'} = $form{'mailrecip'};  
                     }  
                 }  
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);  
                 return OK;  
             }  
         }  
         if (($is_balancer) && ($hosthere)) {  
             $form{'noloadbalance'} = $hosthere;  
         }  
         my $extra_env;  
         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {  
             if ($sessiondata{'origurl'} ne '') {  
                 $firsturl = $sessiondata{'origurl'};  
                 $form{'firsturl'} = $sessiondata{'origurl'};  
                 my @names = ('role','symb','linkprot','linkkey');  
                 foreach my $item (@names) {  
                     if ($sessiondata{$item} ne '') {  
                         $form{$item} = $sessiondata{$item};  
                     }  
                 }  
                 if ($sessiondata{'origurl'} eq '/adm/email') {  
                     if (($sessiondata{'display'}) && ($sessiondata{'mailrecip'})) {  
                         if (&unescape($sessiondata{'mailrecip'}) eq "$form{'uname'}:$form{'udom'}") {  
                             $form{'display'} = &unescape($sessiondata{'display'});  
                             $form{'mailrecip'} = &unescape($sessiondata{'mailrecip'});  
                         }  
                     }  
                 }  
             }  
         }  
         if ($form{'linkprot'}) {  
             my ($linkprotector,$uri) = split(/:/,$form{'linkprot'},2);  
             if ($linkprotector) {  
                 $extra_env = {'user.linkprotector' => $linkprotector,  
                               'user.linkproturi'   => $uri};  
             }  
         } elsif ($form{'linkkey'} ne '') {  
             $extra_env = {'user.deeplinkkey'  => $form{'linkkey'},  
                           'user.keyedlinkuri' => $form{'firsturl'}};  
         }  
         if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {  
             &set_deeplink_login(%form);  
             if ($form{'linkprot'}) {  
                 if (ref($extra_env) eq 'HASH') {  
                     %{$extra_env} = ( %{$extra_env}, 'request.linkprot' => $form{'linkprot'} );  
                 } else {  
                     $extra_env = {'request.linkprot' => $form{'linkprot'}};  
                 }  
                 if ($form{'linkprotexit'}) {  
                     $extra_env->{'request.linkprotexit'} = $form{'linkprotexit'};  
                 }  
                 if ($form{'linkprotpbid'}) {  
                     $extra_env->{'request.linkprotpbid'} = $form{'linkprotpbid'};  
                 }  
                 if ($form{'linkprotpburl'}) {  
                     $extra_env->{'request.linkprotpburl'} = $form{'linkprotpburl'};  
                 }  
             } elsif ($form{'linkkey'} ne '') {  
                 if (ref($extra_env) eq 'HASH') {  
                     %{$extra_env} = ( %{$extra_env}, 'request.linkkey' => $form{'linkkey'} );  
                 } 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','linkprotuser','linkprotexit','linkprot','linkkey','iptoken','linkprotpbid','linkprotpburl');  
         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'};  
             } elsif ($form->{'firsturl'} eq '/adm/email') {  
                 if ($form->{'display'} && ($form->{'mailrecip'} eq $form->{'uname'}.':'.$form->{'udom'})) {  
                     $env{'request.display'} = $form->{'mailrecip'};  
                     $env{'request.mailrecip'} = $form->{'mailrecip'};  
                 }  
             }  
             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;  
 }  
   
 sub alternate_unames_check {  
     my ($uname,$udom) = @_;  
     my %possunames;  
     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);  
     if (ref($domdefs{'unamemap_rule'}) eq 'ARRAY') {  
         if (@{$domdefs{'unamemap_rule'}} > 0) {  
             %possunames =  
                 &Apache::lonnet::inst_rulecheck($udom,$uname,undef,  
                                                 'unamemap',$domdefs{'unamemap_rule'});  
         }  
     }  
     return %possunames;  
 }  
   
 1;  
 __END__  
   
   

Removed from v.1.121.2.24.2.7  
changed lines
  Added in v.1.142


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