Diff for /loncom/auth/lonauth.pm between versions 1.121.2.24.2.4 and 1.175

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


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