Diff for /loncom/auth/lonauth.pm between versions 1.121.2.24.2.6 and 1.163

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

Removed from v.1.121.2.24.2.6  
changed lines
  Added in v.1.163


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