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

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

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


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