Diff for /loncom/auth/lonauth.pm between versions 1.121.2.21 and 1.179

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


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