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

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

Removed from v.1.121.2.24.2.4  
changed lines
  Added in v.1.159


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