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

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


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