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

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

Removed from v.1.121.2.24.2.7  
changed lines
  Added in v.1.172


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