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

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

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


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