Diff for /loncom/auth/lonauth.pm between versions 1.121.2.17 and 1.168

version 1.121.2.17, 2019/08/01 00:42:34 version 1.168, 2021/10/26 15:52:54
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;  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 HTML::Entities;
 # ------------------------------------------------------------ Successful login  use Digest::MD5;
 sub success {   
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,  # ------------------------------------------------------------ Successful login
  $form) = @_;  sub success {
       my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
 # ------------------------------------------------------------ Get cookie ready   $form,$skipcritical,$cid) = @_;
     my $cookie =  
  &Apache::loncommon::init_user_environment($r, $username, $domain,  # ------------------------------------------------------------ Get cookie ready
   $authhost, $form,      my $cookie =
   {'extra_env' => $extra_env,});   &Apache::loncommon::init_user_environment($r, $username, $domain,
     $authhost, $form,
     my $public=($username eq 'public' && $domain eq 'public');    {'extra_env' => $extra_env,});
   
     if ($public or $lowerurl eq 'noredirect') { return $cookie; }      my $public=($username eq 'public' && $domain eq 'public');
   
 # -------------------------------------------------------------------- Log this      if ($public or $lowerurl eq 'noredirect') { return $cookie; }
   
     &Apache::lonnet::log($domain,$username,$authhost,  # -------------------------------------------------------------------- Log this
                          "Login $ENV{'REMOTE_ADDR'}");  
       my $ip = &Apache::lonnet::get_requestor_ip();
 # ------------------------------------------------- Check for critical messages      &Apache::lonnet::log($domain,$username,$authhost,
                            "Login $ip");
     my @what=&Apache::lonnet::dump('critical',$domain,$username);  
     if ($what[0]) {  # ------------------------------------------------- Check for critical messages
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {  
     $lowerurl='/adm/email?critical=display';      unless ($skipcritical) {
         }          my @what=&Apache::lonnet::dump('critical',$domain,$username);
     }          if ($what[0]) {
       if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
 # ------------------------------------------------------------ Get cookie ready          $lowerurl='/adm/email?critical=display';
     $cookie="lonID=$cookie; path=/; HttpOnly";              }
 # -------------------------------------------------------- Menu script and info          }
     my $destination = $lowerurl;      }
   
     if (defined($form->{role})) {  # ----------------------------------------------------------- Get cookies ready
         my $envkey = 'user.role.'.$form->{role};      my ($securecookie,$defaultcookie);
         my $now=time;      my $ssl = $r->subprocess_env('https');
         my $then=$env{'user.login.time'};      if ($ssl) {
         my $refresh=$env{'user.refresh.time'};          $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";
         my $update=$env{'user.update.time'};          my $lonidsdir=$r->dir_config('lonIDsDir');
         if (!$update) {          if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
             $update = $then;              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
         }              if (-e "$lonidsdir/$linkname.id") {
         if (exists($env{$envkey})) {                  unlink("$lonidsdir/$linkname.id");
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);              }
             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
                                          \$trolecode,\$tstatus,\$tstart,\$tend);                                                "$lonidsdir/$linkname.id"); 1 };
             if ($tstatus eq 'is') {              if ($made_symlink) {
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');                  &Apache::lonnet::appenv({'user.linkedenv' => $linkname});
                 $destination .= 'selectrole=1&'.$newrole.'=1';              }
             }          }
         }      } else {
     }          $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
     if (defined($form->{symb})) {      }
         my $destsymb = $form->{symb};  # -------------------------------------------------------- Menu script and info
         $destination  .= ($destination =~ /\?/) ? '&' : '?';      my $destination = $lowerurl;
         if ($destsymb =~ /___/) {      if ($env{'request.lti.login'}) {
             # FIXME Need to deal with encrypted symbs and urls as needed.          if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
             my ($map,$resid,$desturl)=split(/___/,$destsymb);              &Apache::loncommon::content_type($r,'text/html');
             $desturl = &Apache::lonnet::clutter($desturl);              if ($securecookie) {
             $desturl = &HTML::Entities::encode($desturl,'"<>&');                  $r->headers_out->add('Set-cookie' => $securecookie);
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              }
             $destination .= 'destinationurl='.$desturl.              if ($defaultcookie) {
                             '&destsymb='.$destsymb;                  $r->headers_out->add('Set-cookie' => $defaultcookie);
         } else {              }
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              $r->send_http_header;
             $destination .= 'destinationurl='.$destsymb;              if (ref($form) eq 'HASH') {
         }                  $form->{'lti.login'} = $env{'request.lti.login'};
     }                  $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
     if ($destination =~ m{^/adm/roles}) {                  $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
         $destination  .= ($destination =~ /\?/) ? '&' : '?';                  $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
         $destination .= 'source=login';              }
     }              &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
               return;
     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});          }
     my $startupremote=&Apache::lonmenu::startupremote($destination);          if ($env{'request.lti.selfenrollrole'}) {
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);              if (&Apache::ltiauth::lti_enroll($username,$domain,
     my $setflags=&Apache::lonmenu::setflags();                                               $env{'request.lti.selfenrollrole'}) eq 'ok') {
     my $maincall=&Apache::lonmenu::maincall();                  $form->{'role'} = $env{'request.lti.selfenrollrole'};
     my $brcrum = [{'href' => '',                  &Apache::lonnet::delenv('request.lti.selfenrollrole');
                    'text' => 'Successful Login'},];              } else {
     my $start_page=&Apache::loncommon::start_page('Successful Login',                  &Apache::ltiauth::invalid_request($r,24);
                                                   $startupremote,              }
                                                   {'no_inline_link' => 1,          }
                                                    'bread_crumbs' => $brcrum,});      }
     my $end_page  =&Apache::loncommon::end_page();      if (defined($form->{role})) {
           my $envkey = 'user.role.'.$form->{role};
     my $continuelink;          my $now=time;
     if ($env{'environment.remote'} eq 'off') {          my $then=$env{'user.login.time'};
  $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';          my $refresh=$env{'user.refresh.time'};
     }          my $update=$env{'user.update.time'};
 # ------------------------------------------------- Output for successful login          if (!$update) {
               $update = $then;
     &Apache::loncommon::content_type($r,'text/html');          }
     $r->header_out('Set-cookie' => $cookie);          if (exists($env{$envkey})) {
     $r->send_http_header;              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
               &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
     my %lt=&Apache::lonlocal::texthash(                                           \$trolecode,\$tstatus,\$tstart,\$tend);
        'wel' => 'Welcome',              if ($tstatus eq 'is') {
        'pro' => 'Login problems?',                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
        );                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
     my $loginhelp = &loginhelpdisplay($domain);                  $destination .= 'selectrole=1&'.$newrole.'=1';
     if ($loginhelp) {              }
         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';          }
     }      }
       if (defined($form->{symb})) {
     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');           my $destsymb = $form->{symb};
     $r->print(<<ENDSUCCESS);          my $encrypted;
 $start_page          if ($destsymb =~ m{^/enc/}) {
 $setflags              $encrypted = 1;
 $windowinfo              if ($cid) {
 <h1>$lt{'wel'}</h1>                  $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);
 $welcome              }
 $loginhelp          }
 $remoteinfo          $destination  .= ($destination =~ /\?/) ? '&' : '?';
 $maincall          if ($destsymb =~ /___/) {
 $continuelink              my ($map,$resid,$desturl)=split(/___/,$destsymb);
 $end_page              $desturl = &Apache::lonnet::clutter($desturl);
 ENDSUCCESS              if ($encrypted) {
     return;                  $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);
 }                  $destsymb = $form->{symb};
               }
 # --------------------------------------------------------------- Failed login!              $desturl = &HTML::Entities::encode($desturl,'"<>&');
               $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
 sub failed {              $destination .= 'destinationurl='.$desturl.
     my ($r,$message,$form) = @_;                              '&destsymb='.$destsymb;
     (undef,undef,undef,my $clientmathml,my $clientunicode) =          } elsif (!$encrypted) {
         &Apache::loncommon::decode_user_agent();              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     my $args = {};              $destination .= 'destinationurl='.$destsymb;
     if ($clientunicode && !$clientmathml) {          }
         $args = {'browser.unicode' => 1};      }
     }      if ($destination =~ m{^/adm/roles}) {
           $destination  .= ($destination =~ /\?/) ? '&' : '?';
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);          $destination .= 'source=login';
     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});      }
     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});  
     if (&Apache::lonnet::domain($udom,'description') eq '') {      my $windowname = 'loncapaclient';
         undef($udom);      if ($env{'request.lti.login'}) {
     }          $windowname .= 'lti';
     my $retry = '/adm/login';      }
     if ($uname eq $form->{'uname'}) {      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
         $retry .= '?username='.$uname;      my $brcrum = [{'href' => '',
     }                     'text' => 'Successful Login'},];
     if ($udom) {      my $args = {'bread_crumbs' => $brcrum,};
         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;      unless ((defined($form->{role})) || (defined($form->{symb}))) {
     }          my $update=$env{'user.update.time'};
     if (exists($form->{role})) {          if (!$update) {
         my $role = &Apache::loncommon::cleanup_html($form->{role});              $update = $env{'user.login.time'};
         if ($role ne '') {          }
             $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;          my %roles_in_env;
         }          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
     }          if ($showcount == 1) {
     if (exists($form->{symb})) {              foreach my $rolecode (keys(%roles_in_env)) {
         my $symb = &Apache::loncommon::cleanup_html($form->{symb});                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
         if ($symb ne '') {                  if ($cid) {
             $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;                      my %coursedescription =
         }                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
     }                      if ($coursedescription{'type'} eq 'Placement') {
     my $end_page = &Apache::loncommon::end_page();                          $args->{'crstype'} = 'Placement';
     &Apache::loncommon::content_type($r,'text/html');                      }
     $r->send_http_header;                      last;
     my @actions =                  }
          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));              }
     my $loginhelp = &loginhelpdisplay($udom);          }
     if ($loginhelp) {      }
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');  
     }  # ------------------------------------------------- Output for successful login
     #FIXME: link to helpdesk might be added here  
       &Apache::loncommon::content_type($r,'text/html');
     $r->print(      if ($securecookie) {
        $start_page          $r->headers_out->add('Set-cookie' => $securecookie);
       .'<h2>'.&mt('Sorry ...').'</h2>'      }
       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'      if ($defaultcookie) {
       .&Apache::lonhtmlcommon::actionbox(\@actions)          $r->headers_out->add('Set-cookie' => $defaultcookie);
       .$end_page      }
     );      $r->send_http_header;
  }  
       my ($start_page,$js,$pagebody,$end_page);
 # ------------------------------------------------------------------ Rerouting!      if ($env{'request.lti.login'}) {
           $args = {'only_body' => 1};
 sub reroute {          if ($env{'request.lti.target'} eq '') {
     my ($r) = @_;              my $ltitarget = (($destination =~ /\?/) ? '&' : '?').
     &Apache::loncommon::content_type($r,'text/html');                              'ltitarget=iframe';
     $r->send_http_header;              $js = <<"ENDJS";
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'  
            .&mt('Please [_1]log in again[_2].');  <script type="text/javascript">
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});  // <![CDATA[
 }  function setLTItarget() {
       var newloc = '$destination';
 # ---------------------------------------------------------------- Main handler      if (parent !== window) {
           newloc += '$ltitarget';
 sub handler {      }
     my $r = shift;      window.location.href=newloc;
     my $londocroot = $r->dir_config('lonDocRoot');  }
 # Are we re-routing?  // ]]>
     if (-e "$londocroot/lon-status/reroute.txt") {  </script>
  &reroute($r);  
  return OK;  ENDJS
     }              $args->{'add_entries'} = {'onload' => "javascript:setLTItarget();"};
               $pagebody =  '<noscript><span class="LC_warning">'
     &Apache::lonlocal::get_language_handle($r);                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
                           .'</span></noscript>';
 # -------------------------------- Prevent users from attempting to login twice          } else {
     my $handle = &Apache::lonnet::check_for_valid_session($r);              $args->{'redirect'} = [0,$destination,1];
     if ($handle ne '') {          }
         my $lonidsdir=$r->dir_config('lonIDsDir');          $start_page=&Apache::loncommon::start_page('',$js,$args);
         if ($handle=~/^publicuser\_/) {      } else {
 # For "public user" - remove it, we apparently really want to login          $args->{'redirect'} = [0,$destination];
             unlink($r->dir_config('lonIDsDir')."/$handle.id");          $start_page=&Apache::loncommon::start_page('Successful Login',
         } else {                                                     $js,$args);
 # Indeed, a valid token is found  
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);          my %lt=&Apache::lonlocal::texthash(
     &Apache::loncommon::content_type($r,'text/html');             'wel' => 'Welcome',
     $r->send_http_header;             'pro' => 'Login problems?',
     my $start_page =             );
         &Apache::loncommon::start_page('Already logged in');          $pagebody = "<h1>$lt{'wel'}</h1>\n".
     my $end_page =                       &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
         &Apache::loncommon::end_page();          my $loginhelp = &loginhelpdisplay($domain);
             my $dest = '/adm/roles';          if ($loginhelp) {
             if ($env{'form.firsturl'} ne '') {              $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
                 $dest = $env{'form.firsturl'};          }
             }      }
             $r->print(      $end_page = &Apache::loncommon::end_page();
                $start_page      $r->print(<<ENDSUCCESS);
               .'<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].'  $windowinfo
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')  $pagebody
               .'</p>'  $end_page
               .$end_page  ENDSUCCESS
             );      return;
             return OK;  }
         }  
     }  # --------------------------------------------------------------- Failed login!
   
 # ---------------------------------------------------- No valid token, continue  sub failed {
       my ($r,$message,$form) = @_;
       (undef,undef,undef,my $clientmathml,my $clientunicode) =
     my $buffer;          &Apache::loncommon::decode_user_agent();
     if ($r->header_in('Content-length') > 0) {      my $args = {};
  $r->read($buffer,$r->header_in('Content-length'),0);      if ($clientunicode && !$clientmathml) {
     }          $args = {'browser.unicode' => 1};
     my %form;      }
     foreach my $pair (split(/&/,$buffer)) {  
        my ($name,$value) = split(/=/,$pair);      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
        $value =~ tr/+/ /;      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
        $form{$name}=$value;      if (&Apache::lonnet::domain($udom,'description') eq '') {
     }          undef($udom);
       }
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {      my $retry = '/adm/login';
  &failed($r,'Username, password and domain need to be specified.',      if ($uname eq $form->{'uname'}) {
  \%form);          $retry .= '?username='.$uname;
         return OK;      }
     }      if ($udom) {
           $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
 # split user logging in and "su"-user      }
       my $lonhost = $r->dir_config('lonHostID');
     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});      my $querystr;
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});      my $result = &set_retry_token($form,$lonhost,\$querystr);
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});      if ($result eq 'fail') {
     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});          if (exists($form->{role})) {
     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});              my $role = &Apache::loncommon::cleanup_html($form->{role});
               if ($role ne '') {
     my $role   = $r->dir_config('lonRole');                  $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
     my $domain = $r->dir_config('lonDefDomain');              }
     my $prodir = $r->dir_config('lonUsersDir');          }
     my $contact_name = &mt('LON-CAPA helpdesk');          if (exists($form->{symb})) {
               my $symb = &Apache::loncommon::cleanup_html($form->{symb});
 # ---------------------------------------- Get the information from login token              if ($symb ne '') {
                   $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},              }
                                       $form{'serverid'});          }
           if (exists($form->{firsturl})) {
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||               my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
         ($tmpinfo eq 'no_such_host')) {              if ($firsturl ne '') {
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);                  $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
         return OK;                  if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
     } else {                      unless (exists($form->{linkprot})) {
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},                          if (exists($form->{linkkey})) {
    $form{'serverid'});                              $retry .= 'linkkey='.$form->{linkkey};
         if ( $reply ne 'ok' ) {                          }
             &failed($r,'Session could not be opened.',\%form);                      }
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");                  }
     return OK;              }
  }          }
     }          if (exists($form->{linkprot})) {
               my $ltoken = &Apache::lonnet::tmpput({linkprot => $form->{'linkprot'}},
     if (!&Apache::lonnet::domain($form{'udom'})) {                                                    $r->dir_config('lonHostID'));
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);              if ($ltoken) {
         return OK;                  $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
     }              }
           }
     my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);      } elsif ($querystr ne '') {
     if ($rolestr) {          $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;
         $rolestr = &unescape($rolestr);      }
     }      my $end_page = &Apache::loncommon::end_page();
     if ($symbstr) {      &Apache::loncommon::content_type($r,'text/html');
         $symbstr= &unescape($symbstr);      $r->send_http_header;
     }      my @actions =
     if ($iptokenstr) {           (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
         $iptokenstr = &unescape($iptokenstr);      my $loginhelp = &loginhelpdisplay($udom);
     }      if ($loginhelp) {
     if ($rolestr =~ /^role=/) {          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
         (undef,$form{'role'}) = split('=',$rolestr);      }
     }      #FIXME: link to helpdesk might be added here
     if ($symbstr =~ /^symb=/) {   
         (undef,$form{'symb'}) = split('=',$symbstr);      $r->print(
     }         $start_page
     if ($iptokenstr =~ /^iptoken=/) {        .'<h2>'.&mt('Sorry ...').'</h2>'
         (undef,$form{'iptoken'}) = split('=',$iptokenstr);        .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
     }        .&Apache::lonhtmlcommon::actionbox(\@actions)
         .$end_page
     my $upass = &Apache::loncommon::des_decrypt($key,$form{'upass0'});      );
    }
 # ---------------------------------------------------------------- Authenticate  
   # ------------------------------------------------------------------ Rerouting!
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});  
     my ($cancreate,$statustocreate) =  sub reroute {
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});      my ($r) = @_;
     my $defaultauth;      &Apache::loncommon::content_type($r,'text/html');
     if (ref($cancreate) eq 'ARRAY') {      $r->send_http_header;
         if (grep(/^login$/,@{$cancreate})) {      my $msg='<b>'.&mt('Sorry ...').'</b><br />'
             $defaultauth = 1;             .&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,  # ---------------------------------------------------------------- Main handler
                                               $form{'udom'},$defaultauth,  
                                               $clientcancheckhost);  sub handler {
           my $r = shift;
 # --------------------------------------------------------------------- Failed?      my $londocroot = $r->dir_config('lonDocRoot');
   # Are we re-routing?
     if ($authhost eq 'no_host') {      if (-e "$londocroot/lon-status/reroute.txt") {
  &failed($r,'Username and/or password could not be authenticated.',   &reroute($r);
  \%form);   return OK;
         return OK;      }
     } elsif ($authhost eq 'no_account_on_host') {  
         if ($defaultauth) {      &Apache::lonlocal::get_language_handle($r);
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');  
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {  # -------------------------------- Prevent users from attempting to login twice
                 return OK;      my $handle = &Apache::lonnet::check_for_valid_session($r);
             }      if ($handle ne '') {
             my $start_page =           my $lonidsdir=$r->dir_config('lonIDsDir');
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',          if ($handle=~/^publicuser\_/) {
                                                '',{'no_inline_link'   => 1,});  # For "public user" - remove it, we apparently really want to login
             my $lonhost = $r->dir_config('lonHostID');              unlink($r->dir_config('lonIDsDir')."/$handle.id");
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};          } else {
             my $contacts =   # Indeed, a valid token is found
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',              &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
                                                         $form{'udom'},$origmail);      &Apache::loncommon::content_type($r,'text/html');
             my ($contact_email) = split(',',$contacts);       $r->send_http_header;
             my $output =       my $start_page =
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},          &Apache::loncommon::start_page('Already logged in');
                                                        $domdesc,'',$lonhost,      my $end_page =
                                                        $contact_email,$contact_name,          &Apache::loncommon::end_page();
                                                        undef,$statustocreate);              my $dest = '/adm/roles';
             &Apache::loncommon::content_type($r,'text/html');              if ($env{'form.firsturl'} ne '') {
             $r->send_http_header;                  $dest = $env{'form.firsturl'};
             &Apache::createaccount::print_header($r,$start_page);                  if (($dest =~ m{^/tiny/$match_domain/\w+$}) && ($env{'request.course.id'})) {
             $r->print('<h3>'.&mt('Account creation').'</h3>'.                      my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.                      my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                       $output.&Apache::loncommon::end_page());                      my $symb = &Apache::loncommon::symb_from_tinyurl($dest,$cnum,$cdom);
             return OK;                      if ($symb) {
         } else {                          my $buffer;
             &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);                          if ($r->header_in('Content-length') > 0) {
             return OK;                              $r->read($buffer,$r->header_in('Content-length'),0);
         }                          }
     }                          my %form;
                           foreach my $pair (split(/&/,$buffer)) {
     if (($firsturl eq '') ||                               my ($name,$value) = split(/=/,$pair);
  ($firsturl=~/^\/adm\/(logout|remote)/)) {                              $value =~ tr/+/ /;
  $firsturl='/adm/roles';                              $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
     }                              $form{$name}=$value;
                           }
     my $hosthere;                          &set_deeplink_login(%form);
     if ($form{'iptoken'}) {                      } else {
         my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});                          $r->print(
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});                                    $start_page
         if (($sessiondata{'domain'} eq $form{'udom'}) &&                                   .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
             ($sessiondata{'username'} eq $form{'uname'})) {                                   .'<p>'.&mt('Please [_1]log out[_2] first, and then try your access again',
             $hosthere = 1;                                              '<a href="/adm/logout">','</a>')
         }                                   .'</p>'
     }                                   .$end_page);
                           return OK;
 # --------------------------------- Are we attempting to login as somebody else?                      }
     if ($form{'suname'}) {                  }
         my ($suname,$sudom,$sudomref);              }
         $suname = $form{'suname'};              $r->print(
         $sudom = $form{'udom'};                 $start_page
         if ($form{'sudom'}) {                .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
             unless ($sudom eq $form{'sudom'}) {                .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
                 if (&Apache::lonnet::domain($form{'sudom'})) {                      ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
                     $sudomref = [$form{'sudom'}];                .'</p>'
                     $sudom = $form{'sudom'};                .$end_page
                 }              );
             }              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  # ---------------------------------------------------- No valid token, continue
     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)) {      my $buffer;
                     &Apache::lonnet::logthis('Attempted switch user to privileged user');      if ($r->header_in('Content-length') > 0) {
                 } else {   $r->read($buffer,$r->header_in('Content-length'),0);
                     my $noprivswitch;      }
 #      my %form;
 # su-user's home server and user's home server must have one of:      foreach my $pair (split(/&/,$buffer)) {
 # (a) same domain         my ($name,$value) = split(/=/,$pair);
 # (b) same primary library server for the two domains         $value =~ tr/+/ /;
 # (c) same "internet domain" for primary library server(s) for home servers' domains         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 #         $form{$name}=$value;
                     my $suprim = &Apache::lonnet::domain($sudom,'primary');      }
                     my $suintdom = &Apache::lonnet::internet_dom($suprim);  
                     unless ($sudom eq $form{'udom'}) {      if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');   &failed($r,'Username, password and domain need to be specified.',
                         my $uintdom = &Apache::lonnet::internet_dom($uprim);   \%form);
                         unless ($suprim eq $uprim) {          return OK;
                             unless ($suintdom eq $uintdom) {      }
                                 &Apache::lonnet::logthis('Attempted switch user '  
                                    .'to user with different "internet domain".');  # split user logging in and "su"-user
                                 $noprivswitch = 1;  
                             }      ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
                         }      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
                     }      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
       $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
                     unless ($noprivswitch) {      $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
 #  
 # server where log-in occurs must have same "internet domain" as su-user's home      my $role   = $r->dir_config('lonRole');
 # server      my $domain = $r->dir_config('lonDefDomain');
 #      my $prodir = $r->dir_config('lonUsersDir');
                         my $lonhost = $r->dir_config('lonHostID');      my $contact_name = &mt('LON-CAPA helpdesk');
                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);  
                         if ($hostintdom ne $suintdom) {  # ---------------------------------------- Get the information from login token
                             &Apache::lonnet::logthis('Attempted switch user on a '  
                                 .'server with a different "internet domain".');      my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
                         } else {                                        $form{'serverid'});
   
 # -------------------------------------------------------- actually switch users      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
           ($tmpinfo eq 'no_such_host')) {
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  $form{'udom'}.' logging in as '.$suname.':'.$sudom);          return OK;
     $form{'uname'}=$suname;      } else {
                             if ($form{'udom'} ne $sudom) {   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
                                 $form{'udom'}=$sudom;     $form{'serverid'});
                             }          if ( $reply ne 'ok' ) {
                         }              &failed($r,'Session could not be opened.',\%form);
                     }      &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  }      return OK;
     }   }
  } else {      }
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');  
  }      if (!&Apache::lonnet::domain($form{'udom'})) {
     }          &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
           return OK;
     my ($is_balancer,$otherserver);      }
   
     unless ($hosthere) {      my ($key,$firsturl,@rest)=split(/&/,$tmpinfo);
         ($is_balancer,$otherserver) =      foreach my $item (@rest) {
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');          my ($key,$value) = split(/=/,$item);
         if ($is_balancer) {          $form{$key} = &unescape($value);
             if ($otherserver eq '') {      }
                 my $lowest_load;      if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});          $form{'firsturl'} = $firsturl;
                 if ($lowest_load > 100) {      }
                     $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});      my $upass = $ENV{HTTPS} ? $form{'upass0'}
                 }          : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
             }  
             if ($otherserver ne '') {  # ---------------------------------------------------------------- Authenticate
                 my @hosts = &Apache::lonnet::current_machine_ids();  
                 if (grep(/^\Q$otherserver\E$/,@hosts)) {      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
                     $hosthere = $otherserver;      my ($cancreate,$statustocreate) =
                 }          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
             }      my $defaultauth;
         }      if (ref($cancreate) eq 'ARRAY') {
     }          if (grep(/^login$/,@{$cancreate})) {
               $defaultauth = 1;
     if (($is_balancer) && (!$hosthere)) {          }
         if ($otherserver) {      }
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,      my $clientcancheckhost = 1;
                      \%form);      my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;                                                $form{'udom'},$defaultauth,
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {                                                $clientcancheckhost);
                 $switchto .= '&origurl='.$firsturl;  
             }  # --------------------------------------------------------------------- Failed?
             if ($form{'role'}) {  
                 $switchto .= '&role='.$form{'role'};      if ($authhost eq 'no_host') {
             }   &failed($r,'Username and/or password could not be authenticated.',
             if ($form{'symb'}) {   \%form);
                 $switchto .= '&symb='.$form{'symb'};          return OK;
             }      } elsif ($authhost eq 'no_account_on_host') {
             $r->internal_redirect($switchto);          if ($defaultauth) {
         } else {              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
             $r->print(&noswitch());              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
         }                  return OK;
         return OK;              }
     } else {              my $start_page =
         if (!&check_can_host($r,\%form,$authhost)) {                  &Apache::loncommon::start_page('Create a user account in LON-CAPA',
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});                                                 '',{'no_inline_link'   => 1,});
             if ($otherserver) {              my $lonhost = $r->dir_config('lonHostID');
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
                          \%form);              my $contacts =
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {                                                          $form{'udom'},$origmail);
                     $switchto .= '&origurl='.$firsturl;              my ($contact_email) = split(',',$contacts);
                 }              my $output =
                 if ($form{'role'}) {                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
                     $switchto .= '&role='.$form{'role'};                                                         $domdesc,'',$lonhost,
                 }                                                         $contact_email,$contact_name,
                 if ($form{'symb'}) {                                                         undef,$statustocreate);
                     $switchto .= '&symb='.$form{'symb'};              &Apache::loncommon::content_type($r,'text/html');
                 }              $r->send_http_header;
                 $r->internal_redirect($switchto);              &Apache::createaccount::print_header($r,$start_page);
             } else {              $r->print('<h3>'.&mt('Account creation').'</h3>'.
                 $r->print(&noswitch());                        &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;              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);
 # ------------------------------------------------------- Do the load balancing              return OK;
           }
 # ---------------------------------------------------------- Determine own load      }
         my $loadlim = $r->dir_config('lonLoadLim');  
         my $loadavg;      if (($firsturl eq '') ||
         {   ($firsturl=~/^\/adm\/(logout|remote)/)) {
             my $loadfile=Apache::File->new('/proc/loadavg');   $firsturl='/adm/roles';
             $loadavg=<$loadfile>;      }
         }  
         $loadavg =~ s/\s.*//g;      my $hosthere;
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);      if ($form{'iptoken'}) {
         my $userloadpercent=&Apache::lonnet::userload();          my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
           my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
 # ---------------------------------------------------------- Are we overloaded?          if (($sessiondata{'domain'} eq $form{'udom'}) &&
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {              ($sessiondata{'username'} eq $form{'uname'})) {
             my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});              $hosthere = 1;
             if (!$unloaded) {          }
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});      }
             }  
             if ($unloaded) {  # --------------------------------- Are we attempting to login as somebody else?
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',      if ($form{'suname'}) {
                          undef,\%form);          my ($suname,$sudom,$sudomref);
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);          $suname = $form{'suname'};
                 return OK;          $sudom = $form{'udom'};
             }          if ($form{'sudom'}) {
         }              unless ($sudom eq $form{'sudom'}) {
         if (($is_balancer) && ($hosthere)) {                  if (&Apache::lonnet::domain($form{'sudom'})) {
             $form{'noloadbalance'} = $hosthere;                      $sudomref = [$form{'sudom'}];
         }                      $sudom = $form{'sudom'};
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,                  }
                  \%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
 sub check_can_host {      unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
     my ($r,$form,$authhost,$domdesc) = @_;  # ------------------------------ see if the su-user is not too highly privileged
     return unless (ref($form) eq 'HASH');   if (&Apache::lonnet::privileged($suname,$sudom)) {
     my $canhost = 1;                      &Apache::lonnet::logthis('Attempted switch user to privileged user');
     my $lonhost = $r->dir_config('lonHostID');                  } else {
     my $udom = $form->{'udom'};                      my $noprivswitch;
     my @intdoms;  #
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);  # su-user's home server and user's home server must have one of:
     if (ref($internet_names) eq 'ARRAY') {  # (a) same domain
         @intdoms = @{$internet_names};  # (b) same primary library server for the two domains
     }  # (c) same "internet domain" for primary library server(s) for home servers' domains
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');  #
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);                      my $suprim = &Apache::lonnet::domain($sudom,'primary');
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {                      my $suintdom = &Apache::lonnet::internet_dom($suprim);
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);                      unless ($sudom eq $form{'udom'}) {
         my $hostname = &Apache::lonnet::hostname($lonhost);                          my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);                          my $uintdom = &Apache::lonnet::internet_dom($uprim);
         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);                          unless ($suprim eq $uprim) {
         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);                              unless ($suintdom eq $uintdom) {
         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);                                  &Apache::lonnet::logthis('Attempted switch user '
         my $loncaparev;                                     .'to user with different "internet domain".');                        
         if ($authhost eq 'no_account_on_host') {                                  $noprivswitch = 1;
             $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,                      unless ($noprivswitch) {
                                                      $udomdefaults{'remotesessions'},  #
                                                      $defdomdefaults{'hostedsessions'});  # server where log-in occurs must have same "internet domain" as su-user's home
     }  # server
     unless ($canhost) {  #
         if ($authhost eq 'no_account_on_host') {                          my $lonhost = $r->dir_config('lonHostID');
             my $checkloginvia = 1;                          my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
             my ($login_host,$hostname) =                           if ($hostintdom ne $suintdom) {
                 &Apache::lonnet::choose_server($udom,$checkloginvia);                              &Apache::lonnet::logthis('Attempted switch user on a '
             &Apache::loncommon::content_type($r,'text/html');                                  .'server with a different "internet domain".');
             $r->send_http_header;                          } else {
             if ($login_host ne '') {  
                 my $protocol = $Apache::lonnet::protocol{$login_host};  # -------------------------------------------------------- actually switch users
                 $protocol = 'http' if ($protocol ne 'https');  
                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';              &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').                                $form{'udom'}.' logging in as '.$suname.':'.$sudom);
                           '<h3>'.&mt('Account creation').'</h3>'.              $form{'uname'}=$suname;
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.                              if ($form{'udom'} ne $sudom) {
                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.                                  $form{'udom'}=$sudom;
                           '<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 />'.   } else {
                           '<p>'.&mt('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
                           &Apache::loncommon::end_page());   }
             }      }
         } else {  
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,      my ($is_balancer,$otherserver);
                      $form);  
             my ($otherserver) = &Apache::lonnet::choose_server($udom);      unless ($hosthere) {
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);          ($is_balancer,$otherserver) =
         }              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
     }          if ($is_balancer) {
     return $canhost;              # 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_/)) {
 sub noswitch {                  $otherserver = $found_server;
     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').              }
                  '<h3>'.&mt('Session unavailable').'</h3>'.              if ($otherserver eq '') {
                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.                  my $lowest_load;
                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
                  &Apache::loncommon::end_page();                  if ($lowest_load > 100) {
     return $result;                      $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});
 }                  }
               }
 sub loginhelpdisplay {              if ($otherserver ne '') {
     my ($authdomain) = @_;                  my @hosts = &Apache::lonnet::current_machine_ids();
     my $login_help = 1;                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
     my $lang = &Apache::lonlocal::current_language();                      $hosthere = $otherserver;
     if ($login_help) {                  }
         my $dom = $authdomain;              }
         if ($dom eq '') {          }
             $dom = &Apache::lonnet::default_login_domain();      }
         }  
         my %domconfhash = &Apache::loncommon::get_domainconf($dom);      if (($is_balancer) && (!$hosthere)) {
         my $loginhelp_url;          if ($otherserver) {
         if ($lang) {              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};                       \%form);
             if ($loginhelp_url ne '') {              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                 return $loginhelp_url;              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
             }                  $switchto .= '&origurl='.$firsturl;
         }              }
         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};              if ($form{'role'}) {
         if ($loginhelp_url ne '') {                  $switchto .= '&role='.$form{'role'};
             return $loginhelp_url;              }
         } else {              if ($form{'symb'}) {
             return '/adm/loginproblems.html';                  $switchto .= '&symb='.$form{'symb'};
         }              }
     }              if ($form{'linkprot'}) {
     return;                  $env{'request.linkprot'} = $form{'linkprot'};
 }              } elsif ($form{'linkkey'} ne '') {
                   $env{'request.linkkey'} = $form{'linkkey'};
 1;              }
 __END__              if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                   &set_deeplink_login(%form);
               }
               $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'};
                   } elsif ($form{'linkkey'} ne '') {
                       $env{'request.linkkey'} = $form{'linkkey'};
                   }
                   if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                       &set_deeplink_login(%form);
                   }
                   $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);
                   }
                   $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                   return OK;
               }
           }
           if (($is_balancer) && ($hosthere)) {
               $form{'noloadbalance'} = $hosthere;
           }
           my $extra_env;
           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'}};
                   }
               } 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 set_deeplink_login {
       my (%form) = @_;
       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 ($disallow,$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'};
               }
           }
       }
       return;
   }
   
   sub set_retry_token {
       my ($form,$lonhost,$querystr) = @_;
       if (ref($form) eq 'HASH') {
           my ($firsturl,$token,$extras,@names);
           @names = ('role','symb','linkprot','linkkey');
           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'};
               }
               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;
   }
   
   1;
   __END__
   
   

Removed from v.1.121.2.17  
changed lines
  Added in v.1.168


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