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

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


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