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

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

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


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