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

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


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