File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.173: download - view: text, annotated - select for diffs
Sat May 21 05:16:43 2022 UTC (2 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Provider
  Escape any single quotes in destination URL to avoid javascript errors.

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.173 2022/05/21 05:16:43 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::lonauth;
   30: 
   31: use strict;
   32: use LONCAPA qw(:DEFAULT :match);
   33: use Apache::Constants qw(:common);
   34: use CGI qw(:standard);
   35: use Apache::loncommon();
   36: use Apache::lonnet;
   37: use Apache::lonmenu();
   38: use Apache::createaccount;
   39: use Apache::ltiauth;
   40: use Fcntl qw(:flock);
   41: use Apache::lonlocal;
   42: use Apache::File();
   43: use HTML::Entities;
   44: use Digest::MD5;
   45: use CGI::Cookie();
   46:  
   47: # ------------------------------------------------------------ Successful login
   48: sub success {
   49:     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
   50: 	$form,$skipcritical,$cid,$expirepub) = @_;
   51: 
   52: # ------------------------------------------------------------ Get cookie ready
   53:     my $cookie =
   54: 	&Apache::loncommon::init_user_environment($r, $username, $domain,
   55: 						  $authhost, $form,
   56: 						  {'extra_env' => $extra_env,});
   57: 
   58:     my $public=($username eq 'public' && $domain eq 'public');
   59: 
   60:     if ($public or $lowerurl eq 'noredirect') { return $cookie; }
   61: 
   62: # -------------------------------------------------------------------- Log this
   63: 
   64:     my $ip = &Apache::lonnet::get_requestor_ip();
   65:     &Apache::lonnet::log($domain,$username,$authhost,
   66:                          "Login $ip");
   67: 
   68: # ------------------------------------------------- Check for critical messages
   69: 
   70:     unless ($skipcritical) {
   71:         my @what=&Apache::lonnet::dump('critical',$domain,$username);
   72:         if ($what[0]) {
   73: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
   74: 	        $lowerurl='/adm/email?critical=display';
   75:             }
   76:         }
   77:     }
   78: 
   79: # ----------------------------------------------------------- Get cookies ready
   80:     my ($securecookie,$defaultcookie);
   81:     my $ssl = $r->subprocess_env('https');
   82:     if ($ssl) {
   83:         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";
   84:         my $lonidsdir=$r->dir_config('lonIDsDir');
   85:         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
   86:             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
   87:             if (-e "$lonidsdir/$linkname.id") {
   88:                 unlink("$lonidsdir/$linkname.id");
   89:             }
   90:             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
   91:                                               "$lonidsdir/$linkname.id"); 1 };
   92:             if ($made_symlink) {
   93:                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
   94:                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});
   95:             }
   96:         }
   97:     } else {
   98:         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
   99:     }
  100: # -------------------------------------------------------- Menu script and info
  101:     my $destination = $lowerurl;
  102:     if ($env{'request.lti.login'}) {
  103:         if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
  104:             &Apache::loncommon::content_type($r,'text/html');
  105:             if ($securecookie) {
  106:                 $r->headers_out->add('Set-cookie' => $securecookie);
  107:             }
  108:             if ($defaultcookie) {
  109:                 $r->headers_out->add('Set-cookie' => $defaultcookie);
  110:             }
  111:             $r->send_http_header;
  112:             if (ref($form) eq 'HASH') {
  113:                 $form->{'lti.login'} = $env{'request.lti.login'};
  114:                 $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
  115:                 $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
  116:                 $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
  117:             }
  118:             &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
  119:             return;
  120:         }
  121:         if ($env{'request.lti.selfenrollrole'}) {
  122:             if (&Apache::ltiauth::lti_enroll($username,$domain,
  123:                                              $env{'request.lti.selfenrollrole'}) eq 'ok') {
  124:                 $form->{'role'} = $env{'request.lti.selfenrollrole'};
  125:                 &Apache::lonnet::delenv('request.lti.selfenrollrole');
  126:             } else {
  127:                 &Apache::ltiauth::invalid_request($r,24);
  128:             }
  129:         }
  130:     }
  131:     if (defined($form->{role})) {
  132:         my $envkey = 'user.role.'.$form->{role};
  133:         my $now=time;
  134:         my $then=$env{'user.login.time'};
  135:         my $refresh=$env{'user.refresh.time'};
  136:         my $update=$env{'user.update.time'};
  137:         if (!$update) {
  138:             $update = $then;
  139:         }
  140:         if (exists($env{$envkey})) {
  141:             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
  142:             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
  143:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  144:             if ($tstatus eq 'is') {
  145:                 $destination  .= ($destination =~ /\?/) ? '&' : '?';
  146:                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
  147:                 $destination .= 'selectrole=1&'.$newrole.'=1';
  148:             }
  149:         }
  150:     }
  151:     if (defined($form->{symb})) {
  152:         my $destsymb = $form->{symb};
  153:         my $encrypted;
  154:         if ($destsymb =~ m{^/enc/}) {
  155:             $encrypted = 1;
  156:             if ($cid) {
  157:                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);
  158:             }
  159:         }
  160:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
  161:         if ($destsymb =~ /___/) {
  162:             my ($map,$resid,$desturl)=split(/___/,$destsymb);
  163:             $desturl = &Apache::lonnet::clutter($desturl);
  164:             if ($encrypted) {
  165:                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);
  166:                 $destsymb = $form->{symb};
  167:             }
  168:             $desturl = &HTML::Entities::encode($desturl,'"<>&');
  169:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  170:             $destination .= 'destinationurl='.$desturl.
  171:                             '&destsymb='.$destsymb;
  172:         } elsif (!$encrypted) {
  173:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  174:             $destination .= 'destinationurl='.$destsymb;
  175:         }
  176:     }
  177:     if ($destination =~ m{^/adm/roles}) {
  178:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
  179:         $destination .= 'source=login';
  180:     }
  181: 
  182:     if (($env{'request.deeplink.login'} eq $lowerurl) &&
  183:         (($env{'request.linkprot'}) || ($env{'request.linkkey'} ne ''))) {
  184:         my %info;
  185:         if ($env{'request.linkprot'}) {
  186:             $info{'linkprot'} = $env{'request.linkprot'};
  187:         } elsif ($env{'request.linkkey'} ne '') {
  188:             $info{'linkkey'} = $env{'request.linkkey'};
  189:         }
  190:         $info{'origurl'} = $lowerurl;
  191:         my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
  192:         unless (($token eq 'con_lost') || ($token eq 'refused') ||
  193:                 ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
  194:             $destination .= (($destination =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
  195:         }
  196:     }
  197: 
  198:     my $windowname = 'loncapaclient';
  199:     if ($env{'request.lti.login'}) {
  200:         $windowname .= 'lti';
  201:     }
  202:     my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
  203:     my $brcrum = [{'href' => '',
  204:                    'text' => 'Successful Login'},];
  205:     my $args = {'bread_crumbs' => $brcrum,};
  206:     unless ((defined($form->{role})) || (defined($form->{symb}))) {
  207:         my $update=$env{'user.update.time'};
  208:         if (!$update) {
  209:             $update = $env{'user.login.time'};
  210:         }
  211:         my %roles_in_env;
  212:         my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
  213:         if ($showcount == 1) {
  214:             foreach my $rolecode (keys(%roles_in_env)) {
  215:                 my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
  216:                 if ($cid) {
  217:                     my %coursedescription =
  218:                         &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
  219:                     if ($coursedescription{'type'} eq 'Placement') {
  220:                         $args->{'crstype'} = 'Placement';
  221:                     }
  222:                     last;
  223:                 }
  224:             }
  225:         }
  226:     }
  227: 
  228: # ------------------------------------------------- Output for successful login
  229: 
  230:     &Apache::loncommon::content_type($r,'text/html');
  231:     if ($securecookie) {
  232:         $r->headers_out->add('Set-cookie' => $securecookie);
  233:     }
  234:     if ($defaultcookie) {
  235:         $r->headers_out->add('Set-cookie' => $defaultcookie);
  236:     }
  237:     if ($expirepub) {
  238:         my $c = new CGI::Cookie(-name    => 'lonPubID',
  239:                                 -value   => '',
  240:                                 -expires => '-10y',);
  241:         $r->headers_out->add('Set-cookie' => $c);
  242:     }
  243:     $r->send_http_header;
  244: 
  245:     my ($start_page,$js,$pagebody,$end_page);
  246:     if ($env{'request.lti.login'}) {
  247:         $args = {'only_body' => 1};
  248:         if ($env{'request.lti.target'} eq '') {
  249:             my $ltitarget = (($destination =~ /\?/) ? '&' : '?').
  250:                             'ltitarget=iframe';
  251:             &js_escape(\$destination);
  252:             $js = <<"ENDJS";
  253: 
  254: <script type="text/javascript">
  255: // <![CDATA[
  256: function setLTItarget() {
  257:     var newloc = '$destination';
  258:     if (parent !== window) {
  259:         newloc += '$ltitarget';
  260:     }
  261:     window.location.href=newloc;
  262: }
  263: // ]]>
  264: </script>
  265: 
  266: ENDJS
  267:             $args->{'add_entries'} = {'onload' => "javascript:setLTItarget();"};
  268:             $pagebody =  '<noscript><span class="LC_warning">'
  269:                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
  270:                         .'</span></noscript>';
  271:         } else {
  272:             $args->{'redirect'} = [0,$destination,1];
  273:         }
  274:         $start_page=&Apache::loncommon::start_page('',$js,$args);
  275:     } else {
  276:         $args->{'redirect'} = [0,$destination];
  277:         $start_page=&Apache::loncommon::start_page('Successful Login',
  278:                                                    $js,$args);
  279: 
  280:         my %lt=&Apache::lonlocal::texthash(
  281: 				           'wel' => 'Welcome',
  282: 				           'pro' => 'Login problems?',
  283: 				          );
  284:         $pagebody = "<h1>$lt{'wel'}</h1>\n".
  285:                     &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
  286:         my $loginhelp = &loginhelpdisplay($domain);
  287:         if ($loginhelp) {
  288:             $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
  289:         }
  290:     }
  291:     $end_page = &Apache::loncommon::end_page();
  292:     $r->print(<<ENDSUCCESS);
  293: $start_page
  294: $windowinfo
  295: $pagebody
  296: $end_page
  297: ENDSUCCESS
  298:     return;
  299: }
  300: 
  301: # --------------------------------------------------------------- Failed login!
  302: 
  303: sub failed {
  304:     my ($r,$message,$form,$authhost) = @_;
  305:     (undef,undef,undef,my $clientmathml,my $clientunicode) =
  306:         &Apache::loncommon::decode_user_agent();
  307:     my $args = {};
  308:     if ($clientunicode && !$clientmathml) {
  309:         $args = {'browser.unicode' => 1};
  310:     }
  311: 
  312:     my @actions;
  313:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
  314:     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
  315:     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
  316:     if (&Apache::lonnet::domain($udom,'description') eq '') {
  317:         undef($udom);
  318:     }
  319:     my $authtype;
  320:     if (($udom ne '') && ($uname ne '') && ($authhost eq 'no_host')) {
  321:         $authtype = &Apache::lonnet::queryauthenticate($uname,$udom);
  322:     }
  323:     my $retry = '/adm/login';
  324:     if (($uname eq $form->{'uname'}) && ($authtype !~ /^lti:/)) {
  325:         $retry .= '?username='.$uname;
  326:     }
  327:     if ($udom) {
  328:         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
  329:     }
  330:     my $lonhost = $r->dir_config('lonHostID');
  331:     my $querystr;
  332:     my $result = &set_retry_token($form,$lonhost,\$querystr);
  333:     if ($result eq 'fail') {
  334:         if (exists($form->{role})) {
  335:             my $role = &Apache::loncommon::cleanup_html($form->{role});
  336:             if ($role ne '') {
  337:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
  338:             }
  339:         }
  340:         if (exists($form->{symb})) {
  341:             my $symb = &Apache::loncommon::cleanup_html($form->{symb});
  342:             if ($symb ne '') {
  343:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
  344:             }
  345:         }
  346:         if (exists($form->{firsturl})) {
  347:             my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
  348:             if ($firsturl ne '') {
  349:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
  350:                 if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
  351:                     unless (exists($form->{linkprot})) {
  352:                         if (exists($form->{linkkey})) {
  353:                             $retry .= 'linkkey='.$form->{linkkey};
  354:                         }
  355:                     }
  356:                 }
  357:             }
  358:         }
  359:         if (exists($form->{linkprot})) {
  360:             my $ltoken = &Apache::lonnet::tmpput({linkprot => $form->{'linkprot'}},
  361:                                                  $r->dir_config('lonHostID'),'retry');
  362:             if ($ltoken) {
  363:                 $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
  364:             }
  365:         }
  366:     } elsif ($querystr ne '') {
  367:         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;
  368:     }
  369:     my $end_page = &Apache::loncommon::end_page();
  370:     &Apache::loncommon::content_type($r,'text/html');
  371:     $r->send_http_header;
  372:     if ($authtype =~ /^lti:/) {
  373:         $message = &mt('Direct login is not supported with the username you entered.').
  374:                    '<br /><br />'.
  375:                    &mt('You likely need to launch LON-CAPA from within a course in a different Learning Management System.').
  376:                    '<br />'.
  377:                    &mt('You can also try to log in with a different username.');
  378:         @actions = 
  379:             (&mt('Try your [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
  380:     } else {
  381:         $message = &mt($message);
  382:         @actions =
  383:             (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
  384:     }
  385:     my $loginhelp = &loginhelpdisplay($udom);
  386:     if ($loginhelp) {
  387:         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
  388:     }
  389:     #FIXME: link to helpdesk might be added here
  390:     $r->print(
  391:        $start_page
  392:       .'<h2>'.&mt('Sorry ...').'</h2>'
  393:       .&Apache::lonhtmlcommon::confirm_success($message,1).'<br /><br />'
  394:       .&Apache::lonhtmlcommon::actionbox(\@actions)
  395:       .$end_page
  396:     );
  397:  }
  398: 
  399: # ------------------------------------------------------------------ Rerouting!
  400: 
  401: sub reroute {
  402:     my ($r) = @_;
  403:     &Apache::loncommon::content_type($r,'text/html');
  404:     $r->send_http_header;
  405:     my $msg='<b>'.&mt('Sorry ...').'</b><br />'
  406:            .&mt('Please [_1]log in again[_2].');
  407:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
  408: }
  409: 
  410: # ---------------------------------------------------------------- Main handler
  411: 
  412: sub handler {
  413:     my $r = shift;
  414:     my $londocroot = $r->dir_config('lonDocRoot');
  415: # Are we re-routing?
  416:     if (-e "$londocroot/lon-status/reroute.txt") {
  417: 	&reroute($r);
  418: 	return OK;
  419:     }
  420: 
  421:     &Apache::lonlocal::get_language_handle($r);
  422: 
  423: # -------------------------------- Prevent users from attempting to login twice
  424:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  425:     if ($handle ne '') {
  426:         my $lonidsdir=$r->dir_config('lonIDsDir');
  427:         if ($handle=~/^publicuser\_/) {
  428: # For "public user" - remove it, we apparently really want to login
  429:             unlink($r->dir_config('lonIDsDir')."/$handle.id");
  430:         } else {
  431: # Indeed, a valid token is found
  432:             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  433: 	    &Apache::loncommon::content_type($r,'text/html');
  434: 	    $r->send_http_header;
  435: 	    my $start_page =
  436: 	        &Apache::loncommon::start_page('Already logged in');
  437: 	    my $end_page = 
  438: 	        &Apache::loncommon::end_page();
  439:             my $dest = '/adm/roles';
  440:             my %form = &get_form_items($r);
  441:             if ($form{'logtoken'}) {
  442:                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  443:                                                      $form{'serverid'});
  444:                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
  445:                         ($tmpinfo eq 'no_such_host')) {
  446:                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
  447:                     $firsturl = &unescape($firsturl);
  448:                     my %info;
  449:                     foreach my $item (@rest) {
  450:                         my ($key,$value) = split(/=/,$item);
  451:                         $info{$key} = &unescape($value);
  452:                     }
  453:                     if ($firsturl ne '') {
  454:                         $info{'firsturl'} = $firsturl;
  455:                         $dest = $firsturl;
  456:                         my $relogin;
  457:                         if ($dest =~ m{^/tiny/$match_domain/\w+$}) {
  458:                             if ($env{'request.course.id'}) {
  459:                                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  460:                                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  461:                                 my $symb = &Apache::loncommon::symb_from_tinyurl($dest,$cnum,$cdom);
  462:                                 if ($symb) {
  463:                                     unless (&set_deeplink_login(%info) eq 'ok') {
  464:                                         $relogin = 1;
  465:                                     }
  466:                                 }
  467:                             }
  468:                             if ($relogin) {
  469:                                 $r->print(
  470:                                       $start_page
  471:                                      .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  472:                                      .'<p>'.&mt('Please [_1]log out[_2] first, and then try your access again',
  473:                                                 '<a href="/adm/logout">','</a>')
  474:                                      .'</p>'
  475:                                      .$end_page);
  476:                             } else {
  477:                                 if (($info{'linkprot'}) || ($info{'linkkey'} ne '')) {
  478:                                     my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
  479:                                     unless (($token eq 'con_lost') || ($token eq 'refused') ||
  480:                                             ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
  481:                                         $dest .= (($dest =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
  482:                                     }
  483:                                 }
  484:                                 $r->print(
  485:                                       $start_page
  486:                                      .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  487:                                      .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4] first, and then try your access again',
  488:                                                 '<a href="'.$dest.'">','</a>',
  489:                                                 '<a href="/adm/logout">','</a>')
  490:                                      .'</p>'
  491:                                      .$end_page);
  492:                             }
  493:                             return OK;
  494:                         }
  495:                     }
  496:                 }
  497:             }
  498:             $r->print(
  499:                   $start_page
  500:                  .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  501:                  .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
  502:                           ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
  503:                  .'</p>'
  504:                  .$end_page
  505:             );
  506:             return OK;
  507:         }
  508:     }
  509: 
  510: # ---------------------------------------------------- No valid token, continue
  511: 
  512:     my %form = &get_form_items($r);
  513:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  514: 	&failed($r,'Username, password and domain need to be specified.',
  515: 		\%form);
  516:         return OK;
  517:     }
  518: 
  519: # split user logging in and "su"-user
  520: 
  521:     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
  522:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
  523:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
  524:     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
  525:     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
  526: 
  527:     my $role   = $r->dir_config('lonRole');
  528:     my $domain = $r->dir_config('lonDefDomain');
  529:     my $prodir = $r->dir_config('lonUsersDir');
  530:     my $contact_name = &mt('LON-CAPA helpdesk');
  531: 
  532: # ---------------------------------------- Get the information from login token
  533: 
  534:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  535:                                       $form{'serverid'});
  536: 
  537:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') || 
  538:         ($tmpinfo eq 'no_such_host')) {
  539: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  540:         return OK;
  541:     } else {
  542: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
  543: 					   $form{'serverid'});
  544:         if ( $reply ne 'ok' ) {
  545:             &failed($r,'Session could not be opened.',\%form);
  546: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  547: 	    return OK;
  548: 	}
  549:     }
  550: 
  551:     if (!&Apache::lonnet::domain($form{'udom'})) {
  552:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
  553:         return OK;
  554:     }
  555: 
  556:     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
  557:     $firsturl = &unescape($firsturl);
  558:     foreach my $item (@rest) {
  559:         my ($key,$value) = split(/=/,$item);
  560:         $form{$key} = &unescape($value);
  561:     }
  562:     if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
  563:         $form{'firsturl'} = $firsturl;
  564:     }
  565:     my $upass = $ENV{HTTPS} ? $form{'upass0'} 
  566:         : &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});
  567: 
  568: # ---------------------------------------------------------------- Authenticate
  569: 
  570:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  571:     my ($cancreate,$statustocreate) =
  572:         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
  573:     my $defaultauth;
  574:     if (ref($cancreate) eq 'ARRAY') {
  575:         if (grep(/^login$/,@{$cancreate})) {
  576:             $defaultauth = 1;
  577:         }
  578:     }
  579:     my $clientcancheckhost = 1;
  580:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  581:                                               $form{'udom'},$defaultauth,
  582:                                               $clientcancheckhost);
  583: 
  584: # --------------------------------------------------------------------- Failed?
  585: 
  586:     if ($authhost eq 'no_host') {
  587:         my $pwdverify;
  588:         if (&Apache::lonnet::homeserver($form{'uname'},$form{'udom'}) eq 'no_host') {
  589:             my %possunames = &alternate_unames_check($form{'uname'},$form{'udom'});
  590:             if (keys(%possunames) > 0) {
  591:                 foreach my $rulematch (keys(%possunames)) {
  592:                     my $possuname = $possunames{$rulematch};
  593:                     if (($possuname ne '') && ($possuname =~ /^$match_username$/)) {
  594:                         $authhost=Apache::lonnet::authenticate($possuname,$upass,
  595:                                                                $form{'udom'},undef,
  596:                                                                $clientcancheckhost);
  597:                         if (($authhost eq 'no_host') || ($authhost eq 'no_account_on_host')) {
  598:                             next;
  599:                         } elsif (($authhost ne '') && (&Apache::lonnet::hostname($authhost) ne '')) {
  600:                             $pwdverify = 1;
  601:                             &Apache::lonnet::logthis("Authenticated user: $possuname was submitted as: $form{'uname'}"); 
  602:                             $form{'uname'} = $possuname;
  603:                             last;
  604:                         }
  605:                     }
  606:                 }
  607:             }
  608:         }
  609:         unless ($pwdverify) {
  610:             &failed($r,'Username and/or password could not be authenticated.',
  611:                     \%form,$authhost);
  612:             return OK;
  613:         }
  614:     } elsif ($authhost eq 'no_account_on_host') {
  615:         if ($defaultauth) {
  616:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  617:             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
  618:                 return OK;
  619:             }
  620:             my $start_page = 
  621:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',
  622:                                                '',{'no_inline_link'   => 1,});
  623:             my $lonhost = $r->dir_config('lonHostID');
  624:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  625:             my $contacts = 
  626:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  627:                                                         $form{'udom'},$origmail);
  628:             my ($contact_email) = split(',',$contacts); 
  629:             my $output = 
  630:                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
  631:                                                        $domdesc,'',$lonhost,
  632:                                                        $contact_email,$contact_name,
  633:                                                        undef,$statustocreate);
  634:             &Apache::loncommon::content_type($r,'text/html');
  635:             $r->send_http_header;
  636:             &Apache::createaccount::print_header($r,$start_page);
  637:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
  638:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
  639:                       $output.&Apache::loncommon::end_page());
  640:             return OK;
  641:         } else {
  642:             &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);
  643:             return OK;
  644:         }
  645:     }
  646: 
  647:     if (($firsturl eq '') || 
  648: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  649: 	$firsturl='/adm/roles';
  650:     }
  651: 
  652:     my ($hosthere,%sessiondata);
  653:     if ($form{'iptoken'}) {
  654:         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
  655:         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
  656:         if (($sessiondata{'domain'} eq $form{'udom'}) &&
  657:             ($sessiondata{'username'} eq $form{'uname'})) {
  658:             $hosthere = 1;
  659:         }
  660:     }
  661: 
  662: # --------------------------------- Are we attempting to login as somebody else?
  663:     if ($form{'suname'}) {
  664:         my ($suname,$sudom,$sudomref);
  665:         $suname = $form{'suname'};
  666:         $sudom = $form{'udom'};
  667:         if ($form{'sudom'}) {
  668:             unless ($sudom eq $form{'sudom'}) {
  669:                 if (&Apache::lonnet::domain($form{'sudom'})) {
  670:                     $sudomref = [$form{'sudom'}];
  671:                     $sudom = $form{'sudom'};
  672:                 }
  673:             }
  674:         }
  675: # ------------ see if the original user has enough privileges to pull this stunt
  676: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
  677: # ---------------------------------------------------- see if the su-user exists
  678: 	    unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
  679: # ------------------------------ see if the su-user is not too highly privileged
  680: 		if (&Apache::lonnet::privileged($suname,$sudom)) {
  681:                     &Apache::lonnet::logthis('Attempted switch user to privileged user');
  682:                 } else {
  683:                     my $noprivswitch;
  684: #
  685: # su-user's home server and user's home server must have one of:
  686: # (a) same domain
  687: # (b) same primary library server for the two domains
  688: # (c) same "internet domain" for primary library server(s) for home servers' domains
  689: #
  690:                     my $suprim = &Apache::lonnet::domain($sudom,'primary');
  691:                     my $suintdom = &Apache::lonnet::internet_dom($suprim);
  692:                     unless ($sudom eq $form{'udom'}) {
  693:                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
  694:                         my $uintdom = &Apache::lonnet::internet_dom($uprim);
  695:                         unless ($suprim eq $uprim) {
  696:                             unless ($suintdom eq $uintdom) {
  697:                                 &Apache::lonnet::logthis('Attempted switch user '
  698:                                    .'to user with different "internet domain".');
  699:                                 $noprivswitch = 1;
  700:                             }
  701:                         }
  702:                     }
  703: 
  704:                     unless ($noprivswitch) {
  705: #
  706: # server where log-in occurs must have same "internet domain" as su-user's home
  707: # server
  708: #
  709:                         my $lonhost = $r->dir_config('lonHostID');
  710:                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
  711:                         if ($hostintdom ne $suintdom) {
  712:                             &Apache::lonnet::logthis('Attempted switch user on a '
  713:                                 .'server with a different "internet domain".'); 
  714:                         } else {
  715: 
  716: # -------------------------------------------------------- actually switch users
  717: 
  718: 		            &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
  719:                               $form{'udom'}.' logging in as '.$suname.':'.$sudom);
  720: 		            $form{'uname'}=$suname;
  721:                             if ($form{'udom'} ne $sudom) {
  722:                                 $form{'udom'}=$sudom;
  723:                             }
  724:                         }
  725:                     }
  726: 		}
  727: 	    }
  728: 	} else {
  729: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  730: 	}
  731:     }
  732: 
  733:     my ($is_balancer,$otherserver);
  734: 
  735:     unless ($hosthere) {
  736:         ($is_balancer,$otherserver) =
  737:             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
  738:         if ($is_balancer) {
  739:             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
  740:             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
  741:             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {
  742:                 $otherserver = $found_server;
  743:             }
  744:             if ($otherserver eq '') {
  745:                 my $lowest_load;
  746:                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
  747:                 if ($lowest_load > 100) {
  748:                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});
  749:                 }
  750:             }
  751:             if ($otherserver ne '') {
  752:                 my @hosts = &Apache::lonnet::current_machine_ids();
  753:                 if (grep(/^\Q$otherserver\E$/,@hosts)) {
  754:                     $hosthere = $otherserver;
  755:                 }
  756:             }
  757:         }
  758:     }
  759: 
  760:     if (($is_balancer) && (!$hosthere)) {
  761:         if ($otherserver) {
  762:             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  763:                      \%form);
  764:             my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  765:             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  766:                 $switchto .= '&origurl='.$firsturl;
  767:             }
  768:             if ($form{'role'}) {
  769:                 $switchto .= '&role='.$form{'role'};
  770:             }
  771:             if ($form{'symb'}) {
  772:                 $switchto .= '&symb='.$form{'symb'};
  773:             }
  774:             if ($form{'linkprot'}) {
  775:                 $env{'request.linkprot'} = $form{'linkprot'};
  776:             } elsif ($form{'linkkey'} ne '') {
  777:                 $env{'request.linkkey'} = $form{'linkkey'};
  778:             }
  779:             if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  780:                 &set_deeplink_login(%form);
  781:             }
  782:             $r->internal_redirect($switchto);
  783:         } else {
  784:             &Apache::loncommon::content_type($r,'text/html');
  785:             $r->send_http_header;
  786:             $r->print(&noswitch());
  787:         }
  788:         return OK;
  789:     } else {
  790:         if (!&check_can_host($r,\%form,$authhost)) {
  791:             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
  792:             if ($otherserver) {
  793:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  794:                          \%form);
  795:                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  796:                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  797:                     $switchto .= '&origurl='.$firsturl;
  798:                 }
  799:                 if ($form{'role'}) {
  800:                     $switchto .= '&role='.$form{'role'};
  801:                 }
  802:                 if ($form{'symb'}) {
  803:                     $switchto .= '&symb='.$form{'symb'};
  804:                 }
  805:                 if ($form{'linkprot'}) {
  806:                     $env{'request.linkprot'} = $form{'linkprot'};
  807:                 } elsif ($form{'linkkey'} ne '') {
  808:                     $env{'request.linkkey'} = $form{'linkkey'};
  809:                 }
  810:                 if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  811:                     &set_deeplink_login(%form);
  812:                 }
  813:                 $r->internal_redirect($switchto);
  814:             } else {
  815:                 &Apache::loncommon::content_type($r,'text/html');
  816:                 $r->send_http_header;
  817:                 $r->print(&noswitch());
  818:             }
  819:             return OK;
  820:         }
  821: 
  822: # ------------------------------------------------------- Do the load balancing
  823: 
  824: # ---------------------------------------------------------- Determine own load
  825:         my $loadlim = $r->dir_config('lonLoadLim');
  826:         my $loadavg;
  827:         {
  828:             my $loadfile=Apache::File->new('/proc/loadavg');
  829:             $loadavg=<$loadfile>;
  830:         }
  831:         $loadavg =~ s/\s.*//g;
  832:         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
  833:         my $userloadpercent=&Apache::lonnet::userload();
  834: 
  835: # ---------------------------------------------------------- Are we overloaded?
  836:         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
  837:             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});
  838:             if (!$unloaded) {
  839:                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
  840:             }
  841:             if ($unloaded) {
  842:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
  843:                          undef,\%form);
  844:                 if ($form{'linkprot'}) {
  845:                     $env{'request.linkprot'} = $form{'linkprot'};
  846:                 } elsif ($form{'linkkey'} ne '') {
  847:                     $env{'request.linkkey'} = $form{'linkkey'};
  848:                 }
  849:                 if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  850:                     &set_deeplink_login(%form);
  851:                 }
  852:                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
  853:                 return OK;
  854:             }
  855:         }
  856:         if (($is_balancer) && ($hosthere)) {
  857:             $form{'noloadbalance'} = $hosthere;
  858:         }
  859:         my $extra_env;
  860:         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {
  861:             if ($sessiondata{'origurl'} ne '') {
  862:                 $firsturl = $sessiondata{'origurl'};
  863:                 $form{'firsturl'} = $sessiondata{'origurl'};
  864:                 my @names = ('role','symb','linkprot','linkkey');
  865:                 foreach my $item (@names) {
  866:                     if ($sessiondata{$item} ne '') {
  867:                         $form{$item} = $sessiondata{$item};
  868:                     }
  869:                 }
  870:             }
  871:         }
  872:         if ($form{'linkprot'}) {
  873:             my ($linkprotector,$uri) = split(/:/,$form{'linkprot'},2);
  874:             if ($linkprotector) {
  875:                 $extra_env = {'user.linkprotector' => $linkprotector,
  876:                               'user.linkproturi'   => $uri};
  877:             }
  878:         } elsif ($form{'linkkey'} ne '') {
  879:             $extra_env = {'user.deeplinkkey'  => $form{'linkkey'},
  880:                           'user.keyedlinkuri' => $form{'firsturl'}};
  881:         }
  882:         if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  883:             &set_deeplink_login(%form);
  884:             if ($form{'linkprot'}) {
  885:                 if (ref($extra_env) eq 'HASH') {
  886:                     %{$extra_env} = ( %{$extra_env}, 'request.linkprot' => $form{'linkprot'} );
  887:                 } else {
  888:                     $extra_env = {'request.linkprot' => $form{'linkprot'}};
  889:                 }
  890:             } elsif ($form{'linkkey'} ne '') {
  891:                 if (ref($extra_env) eq 'HASH') {
  892:                     %{$extra_env} = ( %{$extra_env}, 'request.linkkey' => $form{'linkkey'} );
  893:                 } else {
  894:                     $extra_env = {'request.linkkey' => $form{'linkkey'}};
  895:                 }
  896:             }
  897:             if ($env{'request.deeplink.login'}) {
  898:                 if (ref($extra_env) eq 'HASH') {
  899:                     %{$extra_env} = ( %{$extra_env}, 'request.deeplink.login' => $form{'firsturl'} );
  900:                 } else {
  901:                     $extra_env = {'request.deeplink.login' => $form{'firsturl'}};
  902:                 }
  903:             }
  904:         }
  905:         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,$extra_env,
  906:                  \%form);
  907:         return OK;
  908:     }
  909: }
  910: 
  911: sub get_form_items {
  912:     my ($r) = @_;
  913:     my $buffer;
  914:     if ($r->header_in('Content-length') > 0) {
  915:         $r->read($buffer,$r->header_in('Content-length'),0);
  916:     }
  917:     my %form;
  918:     foreach my $pair (split(/&/,$buffer)) {
  919:        my ($name,$value) = split(/=/,$pair);
  920:        $value =~ tr/+/ /;
  921:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  922:        $form{$name}=$value;
  923:     }
  924:     return %form;
  925: }
  926: 
  927: sub set_deeplink_login {
  928:     my (%form) = @_;
  929:     my $disallow;
  930:     if ($form{'firsturl'} =~ m{^/tiny/($match_domain)/\w+$}) {
  931:         my $cdom = $1;
  932:         my ($cnum,$symb) = &Apache::loncommon::symb_from_tinyurl($form{'firsturl'},'',$cdom);
  933:         if ($symb) {
  934:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
  935:                 my $deeplink;
  936:                 if ($symb =~ /\.(page|sequence)$/) {
  937:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($symb))[2]);
  938:                     my $navmap = Apache::lonnavmaps::navmap->new();
  939:                     if (ref($navmap)) {
  940:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
  941:                     }
  942:                 } else {
  943:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
  944:                 }
  945:                 if ($deeplink ne '') {
  946:                     my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
  947:                     if (($protect ne 'none') && ($protect ne '')) {
  948:                         my ($acctype,$item) = split(/:/,$protect);
  949:                         if ($acctype =~ /lti(c|d)$/) {
  950:                             unless ($form{'linkprot'} eq $item.$1.':'.$env{'request.deeplink.login'}) {
  951:                                 $disallow = 1;
  952:                             }
  953:                         } elsif ($acctype eq 'key') {
  954:                             unless ($form{'linkkey'} eq $item) {
  955:                                 $disallow = 1;
  956:                             }
  957:                         }
  958:                     }
  959:                 }
  960:                 unless ($disallow) {
  961:                     $env{'request.deeplink.login'} = $form{'firsturl'};
  962:                 }
  963:             } else {
  964:                 $env{'request.deeplink.login'} = $form{'firsturl'};
  965:             }
  966:         }
  967:     }
  968:     if ($disallow) {
  969:         return;
  970:     }
  971:     return 'ok';
  972: }
  973: 
  974: sub set_retry_token {
  975:     my ($form,$lonhost,$querystr) = @_;
  976:     if (ref($form) eq 'HASH') {
  977:         my ($firsturl,$token,$extras,@names);
  978:         @names = ('role','symb','linkprot','linkkey','iptoken');
  979:         foreach my $name (@names) {
  980:             if ($form->{$name} ne '') {
  981:                 $extras .= '&'.$name.'='.&escape($form->{$name});
  982:                 last if ($name eq 'linkprot');
  983:             }
  984:         }
  985:         my $firsturl = $form->{'firsturl'};
  986:         if (($firsturl ne '') || ($extras ne '')) {
  987:             $extras .= ':retry';
  988:             $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).
  989:                                             $extras,$lonhost);
  990:             if (($token eq 'con_lost') || ($token eq 'no_such_host')) {
  991:                 return 'fail';
  992:             } else {
  993:                 if (ref($querystr)) {
  994:                     $$querystr = 'retry='.$token;
  995:                 }
  996:                 return 'ok';
  997:             }
  998:         }
  999:     }
 1000:     return;
 1001: }
 1002: 
 1003: sub check_can_host {
 1004:     my ($r,$form,$authhost,$domdesc) = @_;
 1005:     return unless (ref($form) eq 'HASH');
 1006:     my $canhost = 1;
 1007:     my $lonhost = $r->dir_config('lonHostID');
 1008:     my $udom = $form->{'udom'};
 1009:     my @intdoms;
 1010:     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 1011:     if (ref($internet_names) eq 'ARRAY') {
 1012:         @intdoms = @{$internet_names};
 1013:     }
 1014:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1015:     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1016:     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1017:         my $machine_dom = &Apache::lonnet::host_domain($lonhost);
 1018:         my $hostname = &Apache::lonnet::hostname($lonhost);
 1019:         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
 1020:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1021:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1022:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
 1023:         my $loncaparev;
 1024:         if ($authhost eq 'no_account_on_host') {
 1025:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
 1026:         } else {
 1027:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
 1028:         }
 1029:         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
 1030:                                                      $udomdefaults{'remotesessions'},
 1031:                                                      $defdomdefaults{'hostedsessions'});
 1032:     }
 1033:     unless ($canhost) {
 1034:         if ($authhost eq 'no_account_on_host') {
 1035:             my $checkloginvia = 1;
 1036:             my ($login_host,$hostname) = 
 1037:                 &Apache::lonnet::choose_server($udom,$checkloginvia);
 1038:             &Apache::loncommon::content_type($r,'text/html');
 1039:             $r->send_http_header;
 1040:             if ($login_host ne '') {
 1041:                 my $protocol = $Apache::lonnet::protocol{$login_host};
 1042:                 $protocol = 'http' if ($protocol ne 'https');
 1043:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);
 1044:                 $hostname = $alias if ($alias ne '');
 1045:                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
 1046: #FIXME Should preserve where user was going and linkprot by setting ltoken at $login_host
 1047:                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
 1048:                           '<h3>'.&mt('Account creation').'</h3>'.
 1049:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
 1050:                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
 1051:                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
 1052:                           &Apache::loncommon::end_page());
 1053:             } else {
 1054:                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
 1055:                           '<h3>'.&mt('Account creation unavailable').'</h3>'.
 1056:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
 1057:                           '<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>'.
 1058:                           &Apache::loncommon::end_page());
 1059:             }
 1060:         } else {
 1061:             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
 1062:                      $form);
 1063:             if ($form->{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
 1064:                 $env{'request.deeplink.login'} = $form->{'firsturl'};
 1065:             }
 1066:             if ($form->{'linkprot'}) {
 1067:                 $env{'request.linkprot'} = $form->{'linkprot'};
 1068:             } elsif ($form->{'linkkey'} ne '') {
 1069:                 $env{'request.linkkey'} = $form->{'linkkey'};
 1070:             }
 1071:             my ($otherserver) = &Apache::lonnet::choose_server($udom);
 1072:             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
 1073:         }
 1074:     }
 1075:     return $canhost;
 1076: }
 1077: 
 1078: sub noswitch {
 1079:     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
 1080:                  '<h3>'.&mt('Session unavailable').'</h3>'.
 1081:                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.
 1082:                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
 1083:                  &Apache::loncommon::end_page();
 1084:     return $result;
 1085: }
 1086: 
 1087: sub loginhelpdisplay {
 1088:     my ($authdomain) = @_;
 1089:     my $login_help = 1;
 1090:     my $lang = &Apache::lonlocal::current_language();
 1091:     if ($login_help) {
 1092:         my $dom = $authdomain;
 1093:         if ($dom eq '') {
 1094:             $dom = &Apache::lonnet::default_login_domain();
 1095:         }
 1096:         my %domconfhash = &Apache::loncommon::get_domainconf($dom);
 1097:         my $loginhelp_url;
 1098:         if ($lang) {
 1099:             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
 1100:             if ($loginhelp_url ne '') {
 1101:                 return $loginhelp_url;
 1102:             }
 1103:         }
 1104:         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
 1105:         if ($loginhelp_url ne '') {
 1106:             return $loginhelp_url;
 1107:         } else {
 1108:             return '/adm/loginproblems.html';
 1109:         }
 1110:     }
 1111:     return;
 1112: }
 1113: 
 1114: sub alternate_unames_check {
 1115:     my ($uname,$udom) = @_;
 1116:     my %possunames;
 1117:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1118:     if (ref($domdefs{'unamemap_rule'}) eq 'ARRAY') { 
 1119:         if (@{$domdefs{'unamemap_rule'}} > 0) {
 1120:             %possunames =
 1121:                 &Apache::lonnet::inst_rulecheck($udom,$uname,undef,
 1122:                                                 'unamemap',$domdefs{'unamemap_rule'});
 1123:         }
 1124:     }
 1125:     return %possunames;
 1126: }
 1127: 
 1128: 1;
 1129: __END__
 1130: 
 1131: 

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