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

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

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


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