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

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

Removed from v.1.121.2.24.2.2  
changed lines
  Added in v.1.178


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