Diff for /loncom/auth/lonauth.pm between versions 1.121.2.24.2.2 and 1.176

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


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