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

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

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


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