Diff for /loncom/auth/lonauth.pm between versions 1.121.2.24.2.7 and 1.169

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

Removed from v.1.121.2.24.2.7  
changed lines
  Added in v.1.169


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