File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.179: download - view: text, annotated - select for diffs
Fri Jun 2 01:20:26 2023 UTC (11 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Bugs 6754 and 6907
  - Return of grades to launcher CMS supported for resources or folders
    accessed via LTI-mediated deep link.
  - Support option: "Encrypt stored consumer secrets defined in domain"
  - Signing of LTI payloads for roster retrieval, passback of grades,
    and callback to logput launcher CMS session all now occur on
    primary library server for course's domain.

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

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