File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.382: download - view: text, annotated - select for diffs
Thu Jun 19 19:37:45 2003 UTC (20 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: version_0_99_3, HEAD
- adding timeout (10 minutes) to title cache BUG#1332

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.382 2003/06/19 19:37:45 albertel 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: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
   29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
   30: # 11/8,11/16,11/18,11/22,11/23,12/22,
   31: # 01/06,01/13,02/24,02/28,02/29,
   32: # 03/01,03/02,03/06,03/07,03/13,
   33: # 04/05,05/29,05/31,06/01,
   34: # 06/05,06/26 Gerd Kortemeyer
   35: # 06/26 Ben Tyszka
   36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
   37: # 08/14 Ben Tyszka
   38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
   39: # 10/04 Gerd Kortemeyer
   40: # 10/04 Guy Albertelli
   41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
   42: # 10/30,10/31,
   43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
   44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
   45: # 05/01/01 Guy Albertelli
   46: # 05/01,06/01,09/01 Gerd Kortemeyer
   47: # 09/01 Guy Albertelli
   48: # 09/01,10/01,11/01 Gerd Kortemeyer
   49: # YEAR=2001
   50: # 3/2 Gerd Kortemeyer
   51: # 3/19,3/20 Gerd Kortemeyer
   52: # 5/26,5/28 Gerd Kortemeyer
   53: # 5/30 H. K. Ng
   54: # 6/1 Gerd Kortemeyer
   55: # July Guy Albertelli
   56: # 8/4,8/7,8/8,8/9,8/11,8/16,8/17,8/18,8/20,8/23,9/20,9/21,9/26,
   57: # 10/2 Gerd Kortemeyer
   58: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
   59: # 12/5 Matthew Hall
   60: # 12/5 Guy Albertelli
   61: # 12/6,12/7,12/12 Gerd Kortemeyer
   62: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
   63: # YEAR=2002
   64: # 1/4,2/4,2/7 Gerd Kortemeyer
   65: #
   66: ###
   67: 
   68: package Apache::lonnet;
   69: 
   70: use strict;
   71: use Apache::File;
   72: use LWP::UserAgent();
   73: use HTTP::Headers;
   74: use vars 
   75: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom 
   76:    %libserv %pr %prp %metacache %packagetab %titlecache 
   77:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
   78:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseresdatacache 
   79:    %domaindescription %domain_auth_def %domain_auth_arg_def $tmpdir);
   80: use IO::Socket;
   81: use GDBM_File;
   82: use Apache::Constants qw(:common :http);
   83: use HTML::LCParser;
   84: use Fcntl qw(:flock);
   85: use Apache::loncoursedata;
   86: 
   87: my $readit;
   88: 
   89: # --------------------------------------------------------------------- Logging
   90: 
   91: sub logtouch {
   92:     my $execdir=$perlvar{'lonDaemons'};
   93:     unless (-e "$execdir/logs/lonnet.log") {
   94: 	my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
   95: 	close $fh;
   96:     }
   97:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
   98:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
   99: }
  100: 
  101: sub logthis {
  102:     my $message=shift;
  103:     my $execdir=$perlvar{'lonDaemons'};
  104:     my $now=time;
  105:     my $local=localtime($now);
  106:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
  107:     print $fh "$local ($$): $message\n";
  108:     return 1;
  109: }
  110: 
  111: sub logperm {
  112:     my $message=shift;
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     my $now=time;
  115:     my $local=localtime($now);
  116:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
  117:     print $fh "$now:$message:$local\n";
  118:     return 1;
  119: }
  120: 
  121: # -------------------------------------------------- Non-critical communication
  122: sub subreply {
  123:     my ($cmd,$server)=@_;
  124:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  125:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  126:                                      Type    => SOCK_STREAM,
  127:                                      Timeout => 10)
  128:        or return "con_lost";
  129:     print $client "$cmd\n";
  130:     my $answer=<$client>;
  131:     if (!$answer) { $answer="con_lost"; }
  132:     chomp($answer);
  133:     return $answer;
  134: }
  135: 
  136: sub reply {
  137:     my ($cmd,$server)=@_;
  138:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  139:     my $answer=subreply($cmd,$server);
  140:     if ($answer eq 'con_lost') {
  141:         #sleep 5; 
  142:         #$answer=subreply($cmd,$server);
  143:         #if ($answer eq 'con_lost') {
  144: 	#   &logthis("Second attempt con_lost on $server");
  145:         #   my $peerfile="$perlvar{'lonSockDir'}/$server";
  146:         #   my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  147:         #                                    Type    => SOCK_STREAM,
  148:         #                                    Timeout => 10)
  149:         #              or return "con_lost";
  150:         #   &logthis("Killing socket");
  151:         #   print $client "close_connection_exit\n";
  152:            #sleep 5;
  153:         #   $answer=subreply($cmd,$server);       
  154:        #}   
  155:     }
  156:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  157:        &logthis("<font color=blue>WARNING:".
  158:                 " $cmd to $server returned $answer</font>");
  159:     }
  160:     return $answer;
  161: }
  162: 
  163: # ----------------------------------------------------------- Send USR1 to lonc
  164: 
  165: sub reconlonc {
  166:     my $peerfile=shift;
  167:     &logthis("Trying to reconnect for $peerfile");
  168:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  169:     if (my $fh=Apache::File->new("$loncfile")) {
  170: 	my $loncpid=<$fh>;
  171:         chomp($loncpid);
  172:         if (kill 0 => $loncpid) {
  173: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  174:             kill USR1 => $loncpid;
  175:             sleep 1;
  176:             if (-e "$peerfile") { return; }
  177:             &logthis("$peerfile still not there, give it another try");
  178:             sleep 5;
  179:             if (-e "$peerfile") { return; }
  180:             &logthis(
  181:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  182:         } else {
  183: 	    &logthis(
  184:                "<font color=blue>WARNING:".
  185:                " lonc at pid $loncpid not responding, giving up</font>");
  186:         }
  187:     } else {
  188:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
  189:     }
  190: }
  191: 
  192: # ------------------------------------------------------ Critical communication
  193: 
  194: sub critical {
  195:     my ($cmd,$server)=@_;
  196:     unless ($hostname{$server}) {
  197:         &logthis("<font color=blue>WARNING:".
  198:                " Critical message to unknown server ($server)</font>");
  199:         return 'no_such_host';
  200:     }
  201:     my $answer=reply($cmd,$server);
  202:     if ($answer eq 'con_lost') {
  203:         my $pingreply=reply('ping',$server);
  204: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  205:         my $pongreply=reply('pong',$server);
  206:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
  207:         $answer=reply($cmd,$server);
  208:         if ($answer eq 'con_lost') {
  209:             my $now=time;
  210:             my $middlename=$cmd;
  211:             $middlename=substr($middlename,0,16);
  212:             $middlename=~s/\W//g;
  213:             my $dfilename=
  214:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  215:             $dumpcount++;
  216:             {
  217:              my $dfh;
  218:              if ($dfh=Apache::File->new(">$dfilename")) {
  219:                 print $dfh "$cmd\n";
  220: 	     }
  221:             }
  222:             sleep 2;
  223:             my $wcmd='';
  224:             {
  225: 	     my $dfh;
  226:              if ($dfh=Apache::File->new("$dfilename")) {
  227:                 $wcmd=<$dfh>;
  228: 	     }
  229:             }
  230:             chomp($wcmd);
  231:             if ($wcmd eq $cmd) {
  232: 		&logthis("<font color=blue>WARNING: ".
  233:                          "Connection buffer $dfilename: $cmd</font>");
  234:                 &logperm("D:$server:$cmd");
  235: 	        return 'con_delayed';
  236:             } else {
  237:                 &logthis("<font color=red>CRITICAL:"
  238:                         ." Critical connection failed: $server $cmd</font>");
  239:                 &logperm("F:$server:$cmd");
  240:                 return 'con_failed';
  241:             }
  242:         }
  243:     }
  244:     return $answer;
  245: }
  246:  
  247: # ------------------------------------------- Transfer profile into environment
  248: 
  249: sub transfer_profile_to_env {
  250:     my ($lonidsdir,$handle)=@_;
  251:     my @profile;
  252:     {
  253: 	my $idf=Apache::File->new("$lonidsdir/$handle.id");
  254: 	flock($idf,LOCK_SH);
  255: 	@profile=<$idf>;
  256: 	$idf->close();
  257:     }
  258:     my $envi;
  259:     for ($envi=0;$envi<=$#profile;$envi++) {
  260: 	chomp($profile[$envi]);
  261: 	my ($envname,$envvalue)=split(/=/,$profile[$envi]);
  262: 	$ENV{$envname} = $envvalue;
  263:     }
  264:     $ENV{'user.environment'} = "$lonidsdir/$handle.id";
  265: }
  266: 
  267: # ---------------------------------------------------------- Append Environment
  268: 
  269: sub appenv {
  270:     my %newenv=@_;
  271:     foreach (keys %newenv) {
  272: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
  273:             &logthis("<font color=blue>WARNING: ".
  274:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
  275:                 .'</font>');
  276: 	    delete($newenv{$_});
  277:         } else {
  278:             $ENV{$_}=$newenv{$_};
  279:         }
  280:     }
  281: 
  282:     my $lockfh;
  283:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
  284:        return 'error: '.$!;
  285:     }
  286:     unless (flock($lockfh,LOCK_EX)) {
  287:          &logthis("<font color=blue>WARNING: ".
  288:                   'Could not obtain exclusive lock in appenv: '.$!);
  289:          $lockfh->close();
  290:          return 'error: '.$!;
  291:     }
  292: 
  293:     my @oldenv;
  294:     {
  295:      my $fh;
  296:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  297: 	return 'error: '.$!;
  298:      }
  299:      @oldenv=<$fh>;
  300:      $fh->close();
  301:     }
  302:     for (my $i=0; $i<=$#oldenv; $i++) {
  303:         chomp($oldenv[$i]);
  304:         if ($oldenv[$i] ne '') {
  305:            my ($name,$value)=split(/=/,$oldenv[$i]);
  306:            unless (defined($newenv{$name})) {
  307: 	      $newenv{$name}=$value;
  308: 	   }
  309:         }
  310:     }
  311:     {
  312:      my $fh;
  313:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  314: 	return 'error';
  315:      }
  316:      my $newname;
  317:      foreach $newname (keys %newenv) {
  318: 	 print $fh "$newname=$newenv{$newname}\n";
  319:      }
  320:      $fh->close();
  321:     }
  322: 
  323:     $lockfh->close();
  324:     return 'ok';
  325: }
  326: # ----------------------------------------------------- Delete from Environment
  327: 
  328: sub delenv {
  329:     my $delthis=shift;
  330:     my %newenv=();
  331:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  332:         &logthis("<font color=blue>WARNING: ".
  333:                 "Attempt to delete from environment ".$delthis);
  334:         return 'error';
  335:     }
  336:     my @oldenv;
  337:     {
  338:      my $fh;
  339:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  340: 	return 'error';
  341:      }
  342:      unless (flock($fh,LOCK_SH)) {
  343:          &logthis("<font color=blue>WARNING: ".
  344:                   'Could not obtain shared lock in delenv: '.$!);
  345:          $fh->close();
  346:          return 'error: '.$!;
  347:      }
  348:      @oldenv=<$fh>;
  349:      $fh->close();
  350:     }
  351:     {
  352:      my $fh;
  353:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  354: 	return 'error';
  355:      }
  356:      unless (flock($fh,LOCK_EX)) {
  357:          &logthis("<font color=blue>WARNING: ".
  358:                   'Could not obtain exclusive lock in delenv: '.$!);
  359:          $fh->close();
  360:          return 'error: '.$!;
  361:      }
  362:      foreach (@oldenv) {
  363: 	 unless ($_=~/^$delthis/) { print $fh $_; }
  364:      }
  365:      $fh->close();
  366:     }
  367:     return 'ok';
  368: }
  369: 
  370: # ------------------------------------------ Find out current server userload
  371: # there is a copy in lond
  372: sub userload {
  373:     my $numusers=0;
  374:     {
  375: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  376: 	my $filename;
  377: 	my $curtime=time;
  378: 	while ($filename=readdir(LONIDS)) {
  379: 	    if ($filename eq '.' || $filename eq '..') {next;}
  380: 	    my ($atime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[8];
  381: 	    if ($curtime-$atime < 3600) { $numusers++; }
  382: 	}
  383: 	closedir(LONIDS);
  384:     }
  385:     my $userloadpercent=0;
  386:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  387:     if ($maxuserload) {
  388: 	$userloadpercent=100*$numusers/$maxuserload;
  389:     }
  390:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  391:     return $userloadpercent;
  392: }
  393: 
  394: # ------------------------------------------ Fight off request when overloaded
  395: 
  396: sub overloaderror {
  397:     my ($r,$checkserver)=@_;
  398:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  399:     my $loadavg;
  400:     if ($checkserver eq $perlvar{'lonHostID'}) {
  401:        my $loadfile=Apache::File->new('/proc/loadavg');
  402:        $loadavg=<$loadfile>;
  403:        $loadavg =~ s/\s.*//g;
  404:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  405:     } else {
  406:        $loadavg=&reply('load',$checkserver);
  407:     }
  408:     my $overload=$loadavg-100;
  409:     if ($overload>0) {
  410: 	$r->err_headers_out->{'Retry-After'}=$overload;
  411:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  412:         return 413;
  413:     }    
  414:     return '';
  415: }
  416: 
  417: # ------------------------------ Find server with least workload from spare.tab
  418: 
  419: sub spareserver {
  420:     my ($loadpercent,$userloadpercent) = @_;
  421:     my $tryserver;
  422:     my $spareserver='';
  423:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  424:     my $lowestserver=$loadpercent > $userloadpercent?
  425: 	             $loadpercent :  $userloadpercent;
  426:     foreach $tryserver (keys %spareid) {
  427:        my $loadans=reply('load',$tryserver);
  428:        my $userloadans=reply('userload',$tryserver);
  429:        if ($userloadans !~ /\d/) { $userloadans=0; }
  430:        my $answer=$loadans > $userloadans?
  431:                   $loadans :  $userloadans;
  432:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  433: 	   $spareserver="http://$hostname{$tryserver}";
  434:            $lowestserver=$answer;
  435:        }
  436:     }
  437:     return $spareserver;
  438: }
  439: 
  440: # --------------------------------------------- Try to change a user's password
  441: 
  442: sub changepass {
  443:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  444:     $currentpass = &escape($currentpass);
  445:     $newpass     = &escape($newpass);
  446:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  447: 		       $server);
  448:     if (! $answer) {
  449: 	&logthis("No reply on password change request to $server ".
  450: 		 "by $uname in domain $udom.");
  451:     } elsif ($answer =~ "^ok") {
  452:         &logthis("$uname in $udom successfully changed their password ".
  453: 		 "on $server.");
  454:     } elsif ($answer =~ "^pwchange_failure") {
  455: 	&logthis("$uname in $udom was unable to change their password ".
  456: 		 "on $server.  The action was blocked by either lcpasswd ".
  457: 		 "or pwchange");
  458:     } elsif ($answer =~ "^non_authorized") {
  459:         &logthis("$uname in $udom did not get their password correct when ".
  460: 		 "attempting to change it on $server.");
  461:     } elsif ($answer =~ "^auth_mode_error") {
  462:         &logthis("$uname in $udom attempted to change their password despite ".
  463: 		 "not being locally or internally authenticated on $server.");
  464:     } elsif ($answer =~ "^unknown_user") {
  465:         &logthis("$uname in $udom attempted to change their password ".
  466: 		 "on $server but were unable to because $server is not ".
  467: 		 "their home server.");
  468:     } elsif ($answer =~ "^refused") {
  469: 	&logthis("$server refused to change $uname in $udom password because ".
  470: 		 "it was sent an unencrypted request to change the password.");
  471:     }
  472:     return $answer;
  473: }
  474: 
  475: # ----------------------- Try to determine user's current authentication scheme
  476: 
  477: sub queryauthenticate {
  478:     my ($uname,$udom)=@_;
  479:     if (($perlvar{'lonRole'} eq 'library') && 
  480:         ($udom eq $perlvar{'lonDefDomain'})) {
  481: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
  482: 			 $perlvar{'lonHostID'});
  483: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  484: 	    if (length($answer)) {
  485: 		return $answer;
  486: 	    }
  487: 	    else {
  488: 	&logthis("User $uname at $udom lacks an authentication mechanism");
  489: 		return 'no_host';
  490: 	    }
  491: 	}
  492:     }
  493: 
  494:     my $tryserver;
  495:     foreach $tryserver (keys %libserv) {
  496: 	if ($hostdom{$tryserver} eq $udom) {
  497:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
  498: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  499: 	       if (length($answer)) {
  500: 		   return $answer;
  501: 	       }
  502: 	       else {
  503: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
  504: 		   return 'no_host';
  505: 	       }
  506: 	   }
  507:        }
  508:     }
  509:     &logthis("User $uname at $udom lacks an authentication mechanism");    
  510:     return 'no_host';
  511: }
  512: 
  513: # --------- Try to authenticate user from domain's lib servers (first this one)
  514: 
  515: sub authenticate {
  516:     my ($uname,$upass,$udom)=@_;
  517:     $upass=escape($upass);
  518:     $uname=~s/\W//g;
  519:     if (($perlvar{'lonRole'} eq 'library') && 
  520:         ($udom eq $perlvar{'lonDefDomain'})) {
  521:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
  522:         if ($answer =~ /authorized/) {
  523:               if ($answer eq 'authorized') {
  524:                  &logthis("User $uname at $udom authorized by local server"); 
  525:                  return $perlvar{'lonHostID'}; 
  526:               }
  527:               if ($answer eq 'non_authorized') {
  528:                  &logthis("User $uname at $udom rejected by local server"); 
  529:                  return 'no_host'; 
  530:               }
  531: 	}
  532:     }
  533: 
  534:     my $tryserver;
  535:     foreach $tryserver (keys %libserv) {
  536: 	if ($hostdom{$tryserver} eq $udom) {
  537:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
  538:            if ($answer =~ /authorized/) {
  539:               if ($answer eq 'authorized') {
  540:                  &logthis("User $uname at $udom authorized by $tryserver"); 
  541:                  return $tryserver; 
  542:               }
  543:               if ($answer eq 'non_authorized') {
  544:                  &logthis("User $uname at $udom rejected by $tryserver");
  545:                  return 'no_host';
  546:               } 
  547: 	   }
  548:        }
  549:     }
  550:     &logthis("User $uname at $udom could not be authenticated");    
  551:     return 'no_host';
  552: }
  553: 
  554: # ---------------------- Find the homebase for a user from domain's lib servers
  555: 
  556: sub homeserver {
  557:     my ($uname,$udom,$ignoreBadCache)=@_;
  558:     my $index="$uname:$udom";
  559:     if ($homecache{$index}) { 
  560:         return "$homecache{$index}"; 
  561:     }
  562:     my $tryserver;
  563:     foreach $tryserver (keys %libserv) {
  564:         next if ($ignoreBadCache ne 'true' && 
  565: 		 exists($badServerCache{$tryserver}));
  566: 	if ($hostdom{$tryserver} eq $udom) {
  567:            my $answer=reply("home:$udom:$uname",$tryserver);
  568:            if ($answer eq 'found') { 
  569:               $homecache{$index}=$tryserver;
  570:               return $tryserver; 
  571:            } elsif ($answer eq 'no_host') {
  572: 	       $badServerCache{$tryserver}=1;
  573:            }
  574:        }
  575:     }    
  576:     return 'no_host';
  577: }
  578: 
  579: # ------------------------------------- Find the usernames behind a list of IDs
  580: 
  581: sub idget {
  582:     my ($udom,@ids)=@_;
  583:     my %returnhash=();
  584:     
  585:     my $tryserver;
  586:     foreach $tryserver (keys %libserv) {
  587:        if ($hostdom{$tryserver} eq $udom) {
  588: 	  my $idlist=join('&',@ids);
  589:           $idlist=~tr/A-Z/a-z/; 
  590: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  591:           my @answer=();
  592:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  593: 	      @answer=split(/\&/,$reply);
  594:           }                    ;
  595:           my $i;
  596:           for ($i=0;$i<=$#ids;$i++) {
  597:               if ($answer[$i]) {
  598: 		  $returnhash{$ids[$i]}=$answer[$i];
  599:               } 
  600:           }
  601:        }
  602:     }    
  603:     return %returnhash;
  604: }
  605: 
  606: # ------------------------------------- Find the IDs behind a list of usernames
  607: 
  608: sub idrget {
  609:     my ($udom,@unames)=@_;
  610:     my %returnhash=();
  611:     foreach (@unames) {
  612:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  613:     }
  614:     return %returnhash;
  615: }
  616: 
  617: # ------------------------------- Store away a list of names and associated IDs
  618: 
  619: sub idput {
  620:     my ($udom,%ids)=@_;
  621:     my %servers=();
  622:     foreach (keys %ids) {
  623:         my $uhom=&homeserver($_,$udom);
  624:         if ($uhom ne 'no_host') {
  625:             my $id=&escape($ids{$_});
  626:             $id=~tr/A-Z/a-z/;
  627:             my $unam=&escape($_);
  628: 	    if ($servers{$uhom}) {
  629: 		$servers{$uhom}.='&'.$id.'='.$unam;
  630:             } else {
  631:                 $servers{$uhom}=$id.'='.$unam;
  632:             }
  633:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
  634:         }
  635:     }
  636:     foreach (keys %servers) {
  637:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  638:     }
  639: }
  640: 
  641: # --------------------------------------------------- Assign a key to a student
  642: 
  643: sub assign_access_key {
  644: #
  645: # a valid key looks like uname:udom#comments
  646: # comments are being appended
  647: #
  648:     my ($ckey,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  649:     $cdom=
  650:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  651:     $cnum=
  652:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  653:     $udom=$ENV{'user.name'} unless (defined($udom));
  654:     $uname=$ENV{'user.domain'} unless (defined($uname));
  655:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  656:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  657:         ($existing{$ckey}=~/^$uname\:$udom\#(.*)$/)) { 
  658:                                                   # assigned to this person
  659:                                                   # - this should not happen,
  660:                                                   # unless something went wrong
  661:                                                   # the first time around
  662: # ready to assign
  663:         $logentry=$1.'; '.$logentry;
  664:         if (&put('accesskey',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  665:                                                  $cdom,$cnum) eq 'ok') {
  666: # key now belongs to user
  667: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  668:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  669:                 &appenv('environment.'.$envkey => $ckey);
  670:                 return 'ok';
  671:             } else {
  672:                 return 
  673:   'error: Count not permanently assign key, will need to be re-entered later.';
  674: 	    }
  675:         } else {
  676:             return 'error: Could not assign key, try again later.';
  677:         }
  678:     } elsif (!$existing{$ckey}) {
  679: # the key does not exist
  680: 	return 'error: The key does not exist';
  681:     } else {
  682: # the key is somebody else's
  683: 	return 'error: The key is already in use';
  684:     }
  685: }
  686: 
  687: # ------------------------------------------ put an additional comment on a key
  688: 
  689: sub comment_access_key {
  690: #
  691: # a valid key looks like uname:udom#comments
  692: # comments are being appended
  693: #
  694:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  695:     $cdom=
  696:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  697:     $cnum=
  698:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  699:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  700:     if ($existing{$ckey}) {
  701:         $existing{$ckey}.='; '.$logentry;
  702: # ready to assign
  703:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  704:                                                  $cdom,$cnum) eq 'ok') {
  705: 	    return 'ok';
  706:         } else {
  707: 	    return 'error: Count not store comment.';
  708:         }
  709:     } else {
  710: # the key does not exist
  711: 	return 'error: The key does not exist';
  712:     }
  713: }
  714: 
  715: # ------------------------------------------------------ Generate a set of keys
  716: 
  717: sub generate_access_keys {
  718:     my ($number,$cdom,$cnum,$logentry)=@_;
  719:     $cdom=
  720:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  721:     $cnum=
  722:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  723:     unless (&allowed('mky',$cdom)) { return 0; }
  724:     unless (($cdom) && ($cnum)) { return 0; }
  725:     if ($number>10000) { return 0; }
  726:     sleep(2); # make sure don't get same seed twice
  727:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  728:     my $total=0;
  729:     for (my $i=1;$i<=$number;$i++) {
  730:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  731:                   sprintf("%lx",int(100000*rand)).'-'.
  732:                   sprintf("%lx",int(100000*rand));
  733:        $newkey=~s/1/g/g; # folks mix up 1 and l
  734:        $newkey=~s/0/h/g; # and also 0 and O
  735:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  736:        if ($existing{$newkey}) {
  737:            $i--;
  738:        } else {
  739: 	  if (&put('accesskeys',
  740:               { $newkey => '# generated '.localtime().
  741:                            ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
  742:                            '; '.$logentry },
  743: 		   $cdom,$cnum) eq 'ok') {
  744:               $total++;
  745: 	  }
  746:        }
  747:     }
  748:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
  749:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  750:     return $total;
  751: }
  752: 
  753: # ------------------------------------------------------- Validate an accesskey
  754: 
  755: sub validate_access_key {
  756:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  757:     $cdom=
  758:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  759:     $cnum=
  760:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  761:     $udom=$ENV{'user.name'} unless (defined($udom));
  762:     $uname=$ENV{'user.domain'} unless (defined($uname));
  763:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  764:     return ($existing{$ckey}=~/^$uname\:$udom\#/);
  765: }
  766: 
  767: # ------------------------------------- Find the section of student in a course
  768: 
  769: sub getsection {
  770:     my ($udom,$unam,$courseid)=@_;
  771:     $courseid=~s/\_/\//g;
  772:     $courseid=~s/^(\w)/\/$1/;
  773:     my %Pending; 
  774:     my %Expired;
  775:     #
  776:     # Each role can either have not started yet (pending), be active, 
  777:     #    or have expired.
  778:     #
  779:     # If there is an active role, we are done.
  780:     #
  781:     # If there is more than one role which has not started yet, 
  782:     #     choose the one which will start sooner
  783:     # If there is one role which has not started yet, return it.
  784:     #
  785:     # If there is more than one expired role, choose the one which ended last.
  786:     # If there is a role which has expired, return it.
  787:     #
  788:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  789:                         &homeserver($unam,$udom)))) {
  790:         my ($key,$value)=split(/\=/,$_);
  791:         $key=&unescape($key);
  792:         next if ($key !~/^$courseid(?:\/)*(\w+)*\_st$/);
  793:         my $section=$1;
  794:         if ($key eq $courseid.'_st') { $section=''; }
  795:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  796:         my $now=time;
  797:         if (defined($end) && ($now > $end)) {
  798:             $Expired{$end}=$section;
  799:             next;
  800:         }
  801:         if (defined($start) && ($now < $start)) {
  802:             $Pending{$start}=$section;
  803:             next;
  804:         }
  805:         return $section;
  806:     }
  807:     #
  808:     # Presumedly there will be few matching roles from the above
  809:     # loop and the sorting time will be negligible.
  810:     if (scalar(keys(%Pending))) {
  811:         my ($time) = sort {$a <=> $b} keys(%Pending);
  812:         return $Pending{$time};
  813:     } 
  814:     if (scalar(keys(%Expired))) {
  815:         my @sorted = sort {$a <=> $b} keys(%Expired);
  816:         my $time = pop(@sorted);
  817:         return $Expired{$time};
  818:     }
  819:     return '-1';
  820: }
  821: 
  822: sub usection {
  823:     my ($udom,$unam,$courseid)=@_;
  824:     $courseid=~s/\_/\//g;
  825:     $courseid=~s/^(\w)/\/$1/;
  826:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  827:                         &homeserver($unam,$udom)))) {
  828:         my ($key,$value)=split(/\=/,$_);
  829:         $key=&unescape($key);
  830:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
  831:             my $section=$1;
  832:             if ($key eq $courseid.'_st') { $section=''; }
  833: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  834:             my $now=time;
  835:             my $notactive=0;
  836:             if ($start) {
  837: 		if ($now<$start) { $notactive=1; }
  838:             }
  839:             if ($end) {
  840:                 if ($now>$end) { $notactive=1; }
  841:             } 
  842:             unless ($notactive) { return $section; }
  843:         }
  844:     }
  845:     return '-1';
  846: }
  847: 
  848: # ------------------------------------- Read an entry from a user's environment
  849: 
  850: sub userenvironment {
  851:     my ($udom,$unam,@what)=@_;
  852:     my %returnhash=();
  853:     my @answer=split(/\&/,
  854:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  855:                       &homeserver($unam,$udom)));
  856:     my $i;
  857:     for ($i=0;$i<=$#what;$i++) {
  858: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  859:     }
  860:     return %returnhash;
  861: }
  862: 
  863: # -------------------------------------------------------------------- New chat
  864: 
  865: sub chatsend {
  866:     my ($newentry,$anon)=@_;
  867:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
  868:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
  869:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
  870:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
  871: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
  872: 		   &escape($newentry)),$chome);
  873: }
  874: 
  875: # ------------------------------------------ Find current version of a resource
  876: 
  877: sub getversion {
  878:     my $fname=&clutter(shift);
  879:     unless ($fname=~/^\/res\//) { return -1; }
  880:     return &currentversion(&filelocation('',$fname));
  881: }
  882: 
  883: sub currentversion {
  884:     my $fname=shift;
  885:     my $author=$fname;
  886:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  887:     my ($udom,$uname)=split(/\//,$author);
  888:     my $home=homeserver($uname,$udom);
  889:     if ($home eq 'no_host') { 
  890:         return -1; 
  891:     }
  892:     my $answer=reply("currentversion:$fname",$home);
  893:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  894: 	return -1;
  895:     }
  896:     return $answer;
  897: }
  898: 
  899: # ----------------------------- Subscribe to a resource, return URL if possible
  900: 
  901: sub subscribe {
  902:     my $fname=shift;
  903:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
  904:     my $author=$fname;
  905:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  906:     my ($udom,$uname)=split(/\//,$author);
  907:     my $home=homeserver($uname,$udom);
  908:     if ($home eq 'no_host') {
  909:         return 'not_found';
  910:     }
  911:     my $answer=reply("sub:$fname",$home);
  912:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  913: 	$answer.=' by '.$home;
  914:     }
  915:     return $answer;
  916: }
  917:     
  918: # -------------------------------------------------------------- Replicate file
  919: 
  920: sub repcopy {
  921:     my $filename=shift;
  922:     $filename=~s/\/+/\//g;
  923:     if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
  924:     my $transname="$filename.in.transfer";
  925:     if ((-e $filename) || (-e $transname)) { return OK; }
  926:     my $remoteurl=subscribe($filename);
  927:     if ($remoteurl =~ /^con_lost by/) {
  928: 	   &logthis("Subscribe returned $remoteurl: $filename");
  929:            return HTTP_SERVICE_UNAVAILABLE;
  930:     } elsif ($remoteurl eq 'not_found') {
  931: 	   &logthis("Subscribe returned not_found: $filename");
  932: 	   return HTTP_NOT_FOUND;
  933:     } elsif ($remoteurl =~ /^rejected by/) {
  934: 	   &logthis("Subscribe returned $remoteurl: $filename");
  935:            return FORBIDDEN;
  936:     } elsif ($remoteurl eq 'directory') {
  937:            return OK;
  938:     } else {
  939:         my $author=$filename;
  940:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  941:         my ($udom,$uname)=split(/\//,$author);
  942:         my $home=homeserver($uname,$udom);
  943:         unless ($home eq $perlvar{'lonHostID'}) {
  944:            my @parts=split(/\//,$filename);
  945:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  946:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
  947:                &logthis("Malconfiguration for replication: $filename");
  948: 	       return HTTP_BAD_REQUEST;
  949:            }
  950:            my $count;
  951:            for ($count=5;$count<$#parts;$count++) {
  952:                $path.="/$parts[$count]";
  953:                if ((-e $path)!=1) {
  954: 		   mkdir($path,0777);
  955:                }
  956:            }
  957:            my $ua=new LWP::UserAgent;
  958:            my $request=new HTTP::Request('GET',"$remoteurl");
  959:            my $response=$ua->request($request,$transname);
  960:            if ($response->is_error()) {
  961: 	       unlink($transname);
  962:                my $message=$response->status_line;
  963:                &logthis("<font color=blue>WARNING:"
  964:                        ." LWP get: $message: $filename</font>");
  965:                return HTTP_SERVICE_UNAVAILABLE;
  966:            } else {
  967: 	       if ($remoteurl!~/\.meta$/) {
  968:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
  969:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
  970:                   if ($mresponse->is_error()) {
  971: 		      unlink($filename.'.meta');
  972:                       &logthis(
  973:                      "<font color=yellow>INFO: No metadata: $filename</font>");
  974:                   }
  975: 	       }
  976:                rename($transname,$filename);
  977:                return OK;
  978:            }
  979:        }
  980:     }
  981: }
  982: 
  983: # ------------------------------------------------ Get server side include body
  984: sub ssi_body {
  985:     my ($filelink,%form)=@_;
  986:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
  987:                                      &ssi($filelink,%form));
  988:     $output=~s/^.*\<body[^\>]*\>//si;
  989:     $output=~s/\<\/body\s*\>.*$//si;
  990:     $output=~
  991:             s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
  992:     return $output;
  993: }
  994: 
  995: # --------------------------------------------------------- Server Side Include
  996: 
  997: sub ssi {
  998: 
  999:     my ($fn,%form)=@_;
 1000: 
 1001:     my $ua=new LWP::UserAgent;
 1002:     
 1003:     my $request;
 1004:     
 1005:     if (%form) {
 1006:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
 1007:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1008:     } else {
 1009:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
 1010:     }
 1011: 
 1012:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1013:     my $response=$ua->request($request);
 1014: 
 1015:     return $response->content;
 1016: }
 1017: 
 1018: sub externalssi {
 1019:     my ($url)=@_;
 1020:     my $ua=new LWP::UserAgent;
 1021:     my $request=new HTTP::Request('GET',$url);
 1022:     my $response=$ua->request($request);
 1023:     return $response->content;
 1024: }
 1025: 
 1026: # ------- Add a token to a remote URI's query string to vouch for access rights
 1027: 
 1028: sub tokenwrapper {
 1029:     my $uri=shift;
 1030:     $uri=~s/^http\:\/\/([^\/]+)//;
 1031:     $uri=~s/^\///;
 1032:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
 1033:     my $token=$1;
 1034:     if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
 1035: 	&appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
 1036:         return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
 1037:                (($uri=~/\?/)?'&':'?').'token='.$token.
 1038:                                '&tokenissued='.$perlvar{'lonHostID'};
 1039:     } else {
 1040: 	return '/adm/notfound.html';
 1041:     }
 1042: }
 1043:     
 1044: # --------------- Take an uploaded file and put it into the userfiles directory
 1045: # input: name of form element, coursedoc=1 means this is for the course
 1046: # output: url of file in userspace
 1047: 
 1048: sub userfileupload {
 1049:     my ($formname,$coursedoc)=@_;
 1050:     my $fname=$ENV{'form.'.$formname.'.filename'};
 1051: # Replace Windows backslashes by forward slashes
 1052:     $fname=~s/\\/\//g;
 1053: # Get rid of everything but the actual filename
 1054:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1055: # Replace spaces by underscores
 1056:     $fname=~s/\s+/\_/g;
 1057: # Replace all other weird characters by nothing
 1058:     $fname=~s/[^\w\.\-]//g;
 1059: # See if there is anything left
 1060:     unless ($fname) { return 'error: no uploaded file'; }
 1061:     chop($ENV{'form.'.$formname});
 1062: # Create the directory if not present
 1063:     my $docuname='';
 1064:     my $docudom='';
 1065:     my $docuhome='';
 1066:     if ($coursedoc) {
 1067: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1068: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1069: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1070:     } else {
 1071:         $docuname=$ENV{'user.name'};
 1072:         $docudom=$ENV{'user.domain'};
 1073:         $docuhome=$ENV{'user.home'};
 1074:     }
 1075:     return 
 1076:         &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
 1077: }
 1078: 
 1079: sub finishuserfileupload {
 1080:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
 1081:     my $path=$docudom.'/'.$docuname.'/';
 1082:     my $filepath=$perlvar{'lonDocRoot'};
 1083:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1084:     my $count;
 1085:     for ($count=4;$count<=$#parts;$count++) {
 1086:         $filepath.="/$parts[$count]";
 1087:         if ((-e $filepath)!=1) {
 1088: 	    mkdir($filepath,0777);
 1089:         }
 1090:     }
 1091: # Save the file
 1092:     {
 1093:        my $fh=Apache::File->new('>'.$filepath.'/'.$fname);
 1094:        print $fh $ENV{'form.'.$formname};
 1095:     }
 1096: # Notify homeserver to grep it
 1097: #
 1098:     
 1099:     my $fetchresult= 
 1100:  &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
 1101:     if ($fetchresult eq 'ok') {
 1102: #
 1103: # Return the URL to it
 1104:         return '/uploaded/'.$path.$fname;
 1105:     } else {
 1106:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
 1107:          ' to host '.$docuhome.': '.$fetchresult);
 1108:         return '/adm/notfound.html';
 1109:     }    
 1110: }
 1111: 
 1112: # ------------------------------------------------------------------------- Log
 1113: 
 1114: sub log {
 1115:     my ($dom,$nam,$hom,$what)=@_;
 1116:     return critical("log:$dom:$nam:$what",$hom);
 1117: }
 1118: 
 1119: # ------------------------------------------------------------------ Course Log
 1120: #
 1121: # This routine flushes several buffers of non-mission-critical nature
 1122: #
 1123: 
 1124: sub flushcourselogs {
 1125:     &logthis('Flushing log buffers');
 1126: #
 1127: # course logs
 1128: # This is a log of all transactions in a course, which can be used
 1129: # for data mining purposes
 1130: #
 1131: # It also collects the courseid database, which lists last transaction
 1132: # times and course titles for all courseids
 1133: #
 1134:     my %courseidbuffer=();
 1135:     foreach (keys %courselogs) {
 1136:         my $crsid=$_;
 1137:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1138: 		          &escape($courselogs{$crsid}),
 1139: 		          $coursehombuf{$crsid}) eq 'ok') {
 1140: 	    delete $courselogs{$crsid};
 1141:         } else {
 1142:             &logthis('Failed to flush log buffer for '.$crsid);
 1143:             if (length($courselogs{$crsid})>40000) {
 1144:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
 1145:                         " exceeded maximum size, deleting.</font>");
 1146:                delete $courselogs{$crsid};
 1147:             }
 1148:         }
 1149:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1150:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1151: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
 1152:         } else {
 1153:            $courseidbuffer{$coursehombuf{$crsid}}=
 1154: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
 1155:         }    
 1156:     }
 1157: #
 1158: # Write course id database (reverse lookup) to homeserver of courses 
 1159: # Is used in pickcourse
 1160: #
 1161:     foreach (keys %courseidbuffer) {
 1162:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1163:     }
 1164: #
 1165: # File accesses
 1166: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1167: #
 1168:     foreach (keys %accesshash) {
 1169:         my $entry=$_;
 1170:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
 1171:         my %temphash=($entry => $accesshash{$entry});
 1172:         if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
 1173: 	    delete $accesshash{$entry};
 1174:         }
 1175:     }
 1176: #
 1177: # Roles
 1178: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1179: #
 1180:     foreach (keys %userrolehash) {
 1181:         my $entry=$_;
 1182:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1183: 	    split(/\:/,$entry);
 1184:         if (&Apache::lonnet::put('nohist_userroles',
 1185:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1186:                 $rudom,$runame) eq 'ok') {
 1187: 	    delete $userrolehash{$entry};
 1188:         }
 1189:     }
 1190:     $dumpcount++;
 1191: }
 1192: 
 1193: sub courselog {
 1194:     my $what=shift;
 1195:     $what=time.':'.$what;
 1196:     unless ($ENV{'request.course.id'}) { return ''; }
 1197:     $coursedombuf{$ENV{'request.course.id'}}=
 1198:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1199:     $coursenumbuf{$ENV{'request.course.id'}}=
 1200:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1201:     $coursehombuf{$ENV{'request.course.id'}}=
 1202:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1203:     $coursedescrbuf{$ENV{'request.course.id'}}=
 1204:        $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1205:     if (defined $courselogs{$ENV{'request.course.id'}}) {
 1206: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
 1207:     } else {
 1208: 	$courselogs{$ENV{'request.course.id'}}.=$what;
 1209:     }
 1210:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
 1211: 	&flushcourselogs();
 1212:     }
 1213: }
 1214: 
 1215: sub courseacclog {
 1216:     my $fnsymb=shift;
 1217:     unless ($ENV{'request.course.id'}) { return ''; }
 1218:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
 1219:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
 1220:         $what.=':POST';
 1221: 	foreach (keys %ENV) {
 1222:             if ($_=~/^form\.(.*)/) {
 1223: 		$what.=':'.$1.'='.$ENV{$_};
 1224:             }
 1225:         }
 1226:     }
 1227:     &courselog($what);
 1228: }
 1229: 
 1230: sub countacc {
 1231:     my $url=&declutter(shift);
 1232:     unless ($ENV{'request.course.id'}) { return ''; }
 1233:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
 1234:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1235:     if (defined($accesshash{$key})) {
 1236: 	$accesshash{$key}++;
 1237:     } else {
 1238:         $accesshash{$key}=1;
 1239:     }
 1240: }
 1241: 
 1242: sub linklog {
 1243:     my ($from,$to)=@_;
 1244:     $from=&declutter($from);
 1245:     $to=&declutter($to);
 1246:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1247:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1248: }
 1249:   
 1250: sub userrolelog {
 1251:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1252:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
 1253:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
 1254:         ($trole=~/^cr/)) {
 1255:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1256:        $userrolehash
 1257:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1258:                     =$tend.':'.$tstart;
 1259:    }
 1260: }
 1261: 
 1262: sub get_course_adv_roles {
 1263:     my $cid=shift;
 1264:     $cid=$ENV{'request.course.id'} unless (defined($cid));
 1265:     my %coursehash=&coursedescription($cid);
 1266:     my %returnhash=();
 1267:     my %dumphash=
 1268:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1269:     my $now=time;
 1270:     foreach (keys %dumphash) {
 1271: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1272:         if (($tstart) && ($tstart<0)) { next; }
 1273:         if (($tend) && ($tend<$now)) { next; }
 1274:         if (($tstart) && ($now<$tstart)) { next; }
 1275:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1276:         my $key=&plaintext($role);
 1277:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1278:         if ($returnhash{$key}) {
 1279: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1280:         } else {
 1281:             $returnhash{$key}=$username.':'.$domain;
 1282:         }
 1283:      }
 1284:     return %returnhash;
 1285: }
 1286: 
 1287: # ---------------------------------------------------------- Course ID routines
 1288: # Deal with domain's nohist_courseid.db files
 1289: #
 1290: 
 1291: sub courseidput {
 1292:     my ($domain,$what,$coursehome)=@_;
 1293:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1294: }
 1295: 
 1296: sub courseiddump {
 1297:     my ($domfilter,$descfilter,$sincefilter)=@_;
 1298:     my %returnhash=();
 1299:     unless ($domfilter) { $domfilter=''; }
 1300:     foreach my $tryserver (keys %libserv) {
 1301: 	if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1302: 	    foreach (
 1303:              split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1304: 			       $sincefilter.':'.&escape($descfilter),
 1305:                                $tryserver))) {
 1306: 		my ($key,$value)=split(/\=/,$_);
 1307:                 if (($key) && ($value)) {
 1308: 		    $returnhash{&unescape($key)}=&unescape($value);
 1309:                 }
 1310:             }
 1311: 
 1312:         }
 1313:     }
 1314:     return %returnhash;
 1315: }
 1316: 
 1317: #
 1318: # ----------------------------------------------------------- Check out an item
 1319: 
 1320: sub checkout {
 1321:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 1322:     my $now=time;
 1323:     my $lonhost=$perlvar{'lonHostID'};
 1324:     my $infostr=&escape(
 1325:                  'CHECKOUTTOKEN&'.
 1326:                  $tuname.'&'.
 1327:                  $tudom.'&'.
 1328:                  $tcrsid.'&'.
 1329:                  $symb.'&'.
 1330: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 1331:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 1332:     if ($token=~/^error\:/) { 
 1333:         &logthis("<font color=blue>WARNING: ".
 1334:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 1335:                  "</font>");
 1336:         return ''; 
 1337:     }
 1338: 
 1339:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 1340:     $token=~tr/a-z/A-Z/;
 1341: 
 1342:     my %infohash=('resource.0.outtoken' => $token,
 1343:                   'resource.0.checkouttime' => $now,
 1344:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 1345: 
 1346:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1347:        return '';
 1348:     } else {
 1349:         &logthis("<font color=blue>WARNING: ".
 1350:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 1351:                  "</font>");
 1352:     }    
 1353: 
 1354:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1355:                          &escape('Checkout '.$infostr.' - '.
 1356:                                                  $token)) ne 'ok') {
 1357: 	return '';
 1358:     } else {
 1359:         &logthis("<font color=blue>WARNING: ".
 1360:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 1361:                  "</font>");
 1362:     }
 1363:     return $token;
 1364: }
 1365: 
 1366: # ------------------------------------------------------------ Check in an item
 1367: 
 1368: sub checkin {
 1369:     my $token=shift;
 1370:     my $now=time;
 1371:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 1372:     $lonhost=~tr/A-Z/a-z/;
 1373:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
 1374:     $dtoken=~s/\W/\_/g;
 1375:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 1376:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 1377: 
 1378:     unless (($tuname) && ($tudom)) {
 1379:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 1380:         return '';
 1381:     }
 1382:     
 1383:     unless (&allowed('mgr',$tcrsid)) {
 1384:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 1385:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
 1386:         return '';
 1387:     }
 1388: 
 1389:     my %infohash=('resource.0.intoken' => $token,
 1390:                   'resource.0.checkintime' => $now,
 1391:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 1392: 
 1393:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1394:        return '';
 1395:     }    
 1396: 
 1397:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1398:                          &escape('Checkin - '.$token)) ne 'ok') {
 1399: 	return '';
 1400:     }
 1401: 
 1402:     return ($symb,$tuname,$tudom,$tcrsid);    
 1403: }
 1404: 
 1405: # --------------------------------------------- Set Expire Date for Spreadsheet
 1406: 
 1407: sub expirespread {
 1408:     my ($uname,$udom,$stype,$usymb)=@_;
 1409:     my $cid=$ENV{'request.course.id'}; 
 1410:     if ($cid) {
 1411:        my $now=time;
 1412:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 1413:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 1414:                             $ENV{'course.'.$cid.'.num'}.
 1415: 	        	    ':nohist_expirationdates:'.
 1416:                             &escape($key).'='.$now,
 1417:                             $ENV{'course.'.$cid.'.home'})
 1418:     }
 1419:     return 'ok';
 1420: }
 1421: 
 1422: # ----------------------------------------------------- Devalidate Spreadsheets
 1423: 
 1424: sub devalidate {
 1425:     my ($symb,$uname,$udom)=@_;
 1426:     my $cid=$ENV{'request.course.id'}; 
 1427:     if ($cid) {
 1428: # delete the stored spreadsheets for
 1429: # - the student level sheet of this user in course's homespace
 1430: # - the assessment level sheet for this resource 
 1431: #   for this user in user's homespace
 1432: 	my $key=$uname.':'.$udom.':';
 1433:         my $status=
 1434: 	    &del('nohist_calculatedsheets',
 1435: 		 [$key.'studentcalc'],
 1436: 		 $ENV{'course.'.$cid.'.domain'},
 1437: 		 $ENV{'course.'.$cid.'.num'})
 1438: 		.' '.
 1439: 	    &del('nohist_calculatedsheets_'.$cid,
 1440: 		 [$key.'assesscalc:'.$symb]);
 1441:         unless ($status eq 'ok ok') {
 1442:            &logthis('Could not devalidate spreadsheet '.
 1443:                     $uname.' at '.$udom.' for '.
 1444: 		    $symb.': '.$status);
 1445:         }
 1446:     }
 1447: }
 1448: 
 1449: sub get_scalar {
 1450:     my ($string,$end) = @_;
 1451:     my $value;
 1452:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 1453: 	$value = $1;
 1454:     } elsif ($$string =~ s/^([^&]*?)&//) {
 1455: 	$value = $1;
 1456:     }
 1457:     return &unescape($value);
 1458: }
 1459: 
 1460: sub array2str {
 1461:   my (@array) = @_;
 1462:   my $result=&arrayref2str(\@array);
 1463:   $result=~s/^__ARRAY_REF__//;
 1464:   $result=~s/__END_ARRAY_REF__$//;
 1465:   return $result;
 1466: }
 1467: 
 1468: sub arrayref2str {
 1469:   my ($arrayref) = @_;
 1470:   my $result='__ARRAY_REF__';
 1471:   foreach my $elem (@$arrayref) {
 1472:     if(ref($elem) eq 'ARRAY') {
 1473:       $result.=&arrayref2str($elem).'&';
 1474:     } elsif(ref($elem) eq 'HASH') {
 1475:       $result.=&hashref2str($elem).'&';
 1476:     } elsif(ref($elem)) {
 1477:       #print("Got a ref of ".(ref($elem))." skipping.");
 1478:     } else {
 1479:       $result.=&escape($elem).'&';
 1480:     }
 1481:   }
 1482:   $result=~s/\&$//;
 1483:   $result .= '__END_ARRAY_REF__';
 1484:   return $result;
 1485: }
 1486: 
 1487: sub hash2str {
 1488:   my (%hash) = @_;
 1489:   my $result=&hashref2str(\%hash);
 1490:   $result=~s/^__HASH_REF__//;
 1491:   $result=~s/__END_HASH_REF__$//;
 1492:   return $result;
 1493: }
 1494: 
 1495: sub hashref2str {
 1496:   my ($hashref)=@_;
 1497:   my $result='__HASH_REF__';
 1498:   foreach (keys(%$hashref)) {
 1499:     if (ref($_) eq 'ARRAY') {
 1500:       $result.=&arrayref2str($_).'=';
 1501:     } elsif (ref($_) eq 'HASH') {
 1502:       $result.=&hashref2str($_).'=';
 1503:     } elsif (ref($_)) {
 1504:       $result.='=';
 1505:       #print("Got a ref of ".(ref($_))." skipping.");
 1506:     } else {
 1507: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 1508:     }
 1509: 
 1510:     if(ref($hashref->{$_}) eq 'ARRAY') {
 1511:       $result.=&arrayref2str($hashref->{$_}).'&';
 1512:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 1513:       $result.=&hashref2str($hashref->{$_}).'&';
 1514:     } elsif(ref($hashref->{$_})) {
 1515:        $result.='&';
 1516:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 1517:     } else {
 1518:       $result.=&escape($hashref->{$_}).'&';
 1519:     }
 1520:   }
 1521:   $result=~s/\&$//;
 1522:   $result .= '__END_HASH_REF__';
 1523:   return $result;
 1524: }
 1525: 
 1526: sub str2hash {
 1527:     my ($string)=@_;
 1528:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 1529:     return %$hash;
 1530: }
 1531: 
 1532: sub str2hashref {
 1533:   my ($string) = @_;
 1534: 
 1535:   my %hash;
 1536: 
 1537:   if($string !~ /^__HASH_REF__/) {
 1538:       if (! ($string eq '' || !defined($string))) {
 1539: 	  $hash{'error'}='Not hash reference';
 1540:       }
 1541:       return (\%hash, $string);
 1542:   }
 1543: 
 1544:   $string =~ s/^__HASH_REF__//;
 1545: 
 1546:   while($string !~ /^__END_HASH_REF__/) {
 1547:       #key
 1548:       my $key='';
 1549:       if($string =~ /^__HASH_REF__/) {
 1550:           ($key, $string)=&str2hashref($string);
 1551:           if(defined($key->{'error'})) {
 1552:               $hash{'error'}='Bad data';
 1553:               return (\%hash, $string);
 1554:           }
 1555:       } elsif($string =~ /^__ARRAY_REF__/) {
 1556:           ($key, $string)=&str2arrayref($string);
 1557:           if($key->[0] eq 'Array reference error') {
 1558:               $hash{'error'}='Bad data';
 1559:               return (\%hash, $string);
 1560:           }
 1561:       } else {
 1562:           $string =~ s/^(.*?)=//;
 1563: 	  $key=&unescape($1);
 1564:       }
 1565:       $string =~ s/^=//;
 1566: 
 1567:       #value
 1568:       my $value='';
 1569:       if($string =~ /^__HASH_REF__/) {
 1570:           ($value, $string)=&str2hashref($string);
 1571:           if(defined($value->{'error'})) {
 1572:               $hash{'error'}='Bad data';
 1573:               return (\%hash, $string);
 1574:           }
 1575:       } elsif($string =~ /^__ARRAY_REF__/) {
 1576:           ($value, $string)=&str2arrayref($string);
 1577:           if($value->[0] eq 'Array reference error') {
 1578:               $hash{'error'}='Bad data';
 1579:               return (\%hash, $string);
 1580:           }
 1581:       } else {
 1582: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 1583:       }
 1584:       $string =~ s/^&//;
 1585: 
 1586:       $hash{$key}=$value;
 1587:   }
 1588: 
 1589:   $string =~ s/^__END_HASH_REF__//;
 1590: 
 1591:   return (\%hash, $string);
 1592: }
 1593: 
 1594: sub str2array {
 1595:     my ($string)=@_;
 1596:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 1597:     return @$array;
 1598: }
 1599: 
 1600: sub str2arrayref {
 1601:   my ($string) = @_;
 1602:   my @array;
 1603: 
 1604:   if($string !~ /^__ARRAY_REF__/) {
 1605:       if (! ($string eq '' || !defined($string))) {
 1606: 	  $array[0]='Array reference error';
 1607:       }
 1608:       return (\@array, $string);
 1609:   }
 1610: 
 1611:   $string =~ s/^__ARRAY_REF__//;
 1612: 
 1613:   while($string !~ /^__END_ARRAY_REF__/) {
 1614:       my $value='';
 1615:       if($string =~ /^__HASH_REF__/) {
 1616:           ($value, $string)=&str2hashref($string);
 1617:           if(defined($value->{'error'})) {
 1618:               $array[0] ='Array reference error';
 1619:               return (\@array, $string);
 1620:           }
 1621:       } elsif($string =~ /^__ARRAY_REF__/) {
 1622:           ($value, $string)=&str2arrayref($string);
 1623:           if($value->[0] eq 'Array reference error') {
 1624:               $array[0] ='Array reference error';
 1625:               return (\@array, $string);
 1626:           }
 1627:       } else {
 1628: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 1629:       }
 1630:       $string =~ s/^&//;
 1631: 
 1632:       push(@array, $value);
 1633:   }
 1634: 
 1635:   $string =~ s/^__END_ARRAY_REF__//;
 1636: 
 1637:   return (\@array, $string);
 1638: }
 1639: 
 1640: # -------------------------------------------------------------------Temp Store
 1641: 
 1642: sub tmpreset {
 1643:   my ($symb,$namespace,$domain,$stuname) = @_;
 1644:   if (!$symb) {
 1645:     $symb=&symbread();
 1646:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1647:   }
 1648:   $symb=escape($symb);
 1649: 
 1650:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1651:   $namespace=~s/\//\_/g;
 1652:   $namespace=~s/\W//g;
 1653: 
 1654:   #FIXME needs to do something for /pub resources
 1655:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1656:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1657:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1658:   my %hash;
 1659:   if (tie(%hash,'GDBM_File',
 1660: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1661: 	  &GDBM_WRCREAT(),0640)) {
 1662:     foreach my $key (keys %hash) {
 1663:       if ($key=~ /:$symb/) {
 1664: 	delete($hash{$key});
 1665:       }
 1666:     }
 1667:   }
 1668: }
 1669: 
 1670: sub tmpstore {
 1671:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1672: 
 1673:   if (!$symb) {
 1674:     $symb=&symbread();
 1675:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1676:   }
 1677:   $symb=escape($symb);
 1678: 
 1679:   if (!$namespace) {
 1680:     # I don't think we would ever want to store this for a course.
 1681:     # it seems this will only be used if we don't have a course.
 1682:     #$namespace=$ENV{'request.course.id'};
 1683:     #if (!$namespace) {
 1684:       $namespace=$ENV{'request.state'};
 1685:     #}
 1686:   }
 1687:   $namespace=~s/\//\_/g;
 1688:   $namespace=~s/\W//g;
 1689: #FIXME needs to do something for /pub resources
 1690:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1691:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1692:   my $now=time;
 1693:   my %hash;
 1694:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1695:   if (tie(%hash,'GDBM_File',
 1696: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1697: 	  &GDBM_WRCREAT(),0640)) {
 1698:     $hash{"version:$symb"}++;
 1699:     my $version=$hash{"version:$symb"};
 1700:     my $allkeys=''; 
 1701:     foreach my $key (keys(%$storehash)) {
 1702:       $allkeys.=$key.':';
 1703:       $hash{"$version:$symb:$key"}=$$storehash{$key};
 1704:     }
 1705:     $hash{"$version:$symb:timestamp"}=$now;
 1706:     $allkeys.='timestamp';
 1707:     $hash{"$version:keys:$symb"}=$allkeys;
 1708:     if (untie(%hash)) {
 1709:       return 'ok';
 1710:     } else {
 1711:       return "error:$!";
 1712:     }
 1713:   } else {
 1714:     return "error:$!";
 1715:   }
 1716: }
 1717: 
 1718: # -----------------------------------------------------------------Temp Restore
 1719: 
 1720: sub tmprestore {
 1721:   my ($symb,$namespace,$domain,$stuname) = @_;
 1722: 
 1723:   if (!$symb) {
 1724:     $symb=&symbread();
 1725:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1726:   }
 1727:   $symb=escape($symb);
 1728: 
 1729:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1730:   #FIXME needs to do something for /pub resources
 1731:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1732:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1733: 
 1734:   my %returnhash;
 1735:   $namespace=~s/\//\_/g;
 1736:   $namespace=~s/\W//g;
 1737:   my %hash;
 1738:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1739:   if (tie(%hash,'GDBM_File',
 1740: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1741: 	  &GDBM_READER(),0640)) {
 1742:     my $version=$hash{"version:$symb"};
 1743:     $returnhash{'version'}=$version;
 1744:     my $scope;
 1745:     for ($scope=1;$scope<=$version;$scope++) {
 1746:       my $vkeys=$hash{"$scope:keys:$symb"};
 1747:       my @keys=split(/:/,$vkeys);
 1748:       my $key;
 1749:       $returnhash{"$scope:keys"}=$vkeys;
 1750:       foreach $key (@keys) {
 1751: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
 1752: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
 1753:       }
 1754:     }
 1755:     if (!(untie(%hash))) {
 1756:       return "error:$!";
 1757:     }
 1758:   } else {
 1759:     return "error:$!";
 1760:   }
 1761:   return %returnhash;
 1762: }
 1763: 
 1764: # ----------------------------------------------------------------------- Store
 1765: 
 1766: sub store {
 1767:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1768:     my $home='';
 1769: 
 1770:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1771: 
 1772:     $symb=&symbclean($symb);
 1773:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1774: 
 1775:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1776:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1777: 
 1778:     &devalidate($symb,$stuname,$domain);
 1779: 
 1780:     $symb=escape($symb);
 1781:     if (!$namespace) { 
 1782:        unless ($namespace=$ENV{'request.course.id'}) { 
 1783:           return ''; 
 1784:        } 
 1785:     }
 1786:     if (!$home) { $home=$ENV{'user.home'}; }
 1787:     my $namevalue='';
 1788:     foreach (keys %$storehash) {
 1789:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1790:     }
 1791:     $namevalue=~s/\&$//;
 1792:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 1793:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1794: }
 1795: 
 1796: # -------------------------------------------------------------- Critical Store
 1797: 
 1798: sub cstore {
 1799:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1800:     my $home='';
 1801: 
 1802:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1803: 
 1804:     $symb=&symbclean($symb);
 1805:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1806: 
 1807:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1808:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1809: 
 1810:     &devalidate($symb,$stuname,$domain);
 1811: 
 1812:     $symb=escape($symb);
 1813:     if (!$namespace) { 
 1814:        unless ($namespace=$ENV{'request.course.id'}) { 
 1815:           return ''; 
 1816:        } 
 1817:     }
 1818:     if (!$home) { $home=$ENV{'user.home'}; }
 1819: 
 1820:     my $namevalue='';
 1821:     foreach (keys %$storehash) {
 1822:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1823:     }
 1824:     $namevalue=~s/\&$//;
 1825:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 1826:     return critical
 1827:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1828: }
 1829: 
 1830: # --------------------------------------------------------------------- Restore
 1831: 
 1832: sub restore {
 1833:     my ($symb,$namespace,$domain,$stuname) = @_;
 1834:     my $home='';
 1835: 
 1836:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1837: 
 1838:     if (!$symb) {
 1839:       unless ($symb=escape(&symbread())) { return ''; }
 1840:     } else {
 1841:       $symb=&escape(&symbclean($symb));
 1842:     }
 1843:     if (!$namespace) { 
 1844:        unless ($namespace=$ENV{'request.course.id'}) { 
 1845:           return ''; 
 1846:        } 
 1847:     }
 1848:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1849:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1850:     if (!$home) { $home=$ENV{'user.home'}; }
 1851:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 1852: 
 1853:     my %returnhash=();
 1854:     foreach (split(/\&/,$answer)) {
 1855: 	my ($name,$value)=split(/\=/,$_);
 1856:         $returnhash{&unescape($name)}=&unescape($value);
 1857:     }
 1858:     my $version;
 1859:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 1860:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 1861:           $returnhash{$_}=$returnhash{$version.':'.$_};
 1862:        }
 1863:     }
 1864:     return %returnhash;
 1865: }
 1866: 
 1867: # ---------------------------------------------------------- Course Description
 1868: 
 1869: sub coursedescription {
 1870:     my $courseid=shift;
 1871:     $courseid=~s/^\///;
 1872:     $courseid=~s/\_/\//g;
 1873:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1874:     my $chome=&homeserver($cnum,$cdomain);
 1875:     my $normalid=$cdomain.'_'.$cnum;
 1876:     # need to always cache even if we get errors otherwise we keep 
 1877:     # trying and trying and trying to get the course description.
 1878:     my %envhash=();
 1879:     my %returnhash=();
 1880:     $envhash{'course.'.$normalid.'.last_cache'}=time;
 1881:     if ($chome ne 'no_host') {
 1882:        %returnhash=&dump('environment',$cdomain,$cnum);
 1883:        if (!exists($returnhash{'con_lost'})) {
 1884:            $returnhash{'home'}= $chome;
 1885: 	   $returnhash{'domain'} = $cdomain;
 1886: 	   $returnhash{'num'} = $cnum;
 1887:            while (my ($name,$value) = each %returnhash) {
 1888:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 1889:            }
 1890:            $returnhash{'url'}=&clutter($returnhash{'url'});
 1891:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 1892: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
 1893:            $envhash{'course.'.$normalid.'.home'}=$chome;
 1894:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 1895:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 1896:        }
 1897:     }
 1898:     &appenv(%envhash);
 1899:     return %returnhash;
 1900: }
 1901: 
 1902: # -------------------------------------------------------- Get user privileges
 1903: 
 1904: sub rolesinit {
 1905:     my ($domain,$username,$authhost)=@_;
 1906:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 1907:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 1908:     my %allroles=();
 1909:     my %thesepriv=();
 1910:     my $now=time;
 1911:     my $userroles="user.login.time=$now\n";
 1912:     my $thesestr;
 1913: 
 1914:     if ($rolesdump ne '') {
 1915:         foreach (split(/&/,$rolesdump)) {
 1916: 	  if ($_!~/^rolesdef\&/) {
 1917:             my ($area,$role)=split(/=/,$_);
 1918:             $area=~s/\_\w\w$//;
 1919:             my ($trole,$tend,$tstart)=split(/_/,$role);
 1920:             $userroles.='user.role.'.$trole.'.'.$area.'='.
 1921:                         $tstart.'.'.$tend."\n";
 1922: # log the associated role with the area
 1923:             &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 1924:             if ($tend!=0) {
 1925: 	        if ($tend<$now) {
 1926: 	            $trole='';
 1927:                 } 
 1928:             }
 1929:             if ($tstart!=0) {
 1930:                 if ($tstart>$now) {
 1931:                    $trole='';        
 1932:                 }
 1933:             }
 1934:             if (($area ne '') && ($trole ne '')) {
 1935: 		my $spec=$trole.'.'.$area;
 1936: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 1937: 		if ($trole =~ /^cr\//) {
 1938: 		    my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 1939: 		    my $homsvr=homeserver($rauthor,$rdomain);
 1940: 		    if ($hostname{$homsvr} ne '') {
 1941: 			my $roledef=
 1942: 			    reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
 1943: 				  $homsvr);
 1944: 			if (($roledef ne 'con_lost') && ($roledef ne '')) {
 1945: 			    my ($syspriv,$dompriv,$coursepriv)=
 1946: 				split(/\_/,unescape($roledef));
 1947: 			    if (defined($syspriv)) {
 1948: 				$allroles{'cm./'}.=':'.$syspriv;
 1949: 				$allroles{$spec.'./'}.=':'.$syspriv;
 1950: 			    }
 1951: 			    if ($tdomain ne '') {
 1952: 				if (defined($dompriv)) {
 1953: 				    $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 1954: 				    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 1955: 				}
 1956: 				if ($trest ne '') {
 1957: 				    if (defined($coursepriv)) {
 1958: 					$allroles{'cm.'.$area}.=':'.$coursepriv;
 1959: 					$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 1960: 				    }
 1961: 				}
 1962: 			    }
 1963: 			}
 1964: 		    }
 1965: 		} else {
 1966: 		    if (defined($pr{$trole.':s'})) {
 1967: 			$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 1968: 			$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 1969: 		    }
 1970: 		    if ($tdomain ne '') {
 1971: 			if (defined($pr{$trole.':d'})) {
 1972: 			    $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1973: 			    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1974: 			}
 1975: 			if ($trest ne '') {
 1976: 			    if (defined($pr{$trole.':c'})) {
 1977: 				$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 1978: 				$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 1979: 			    }
 1980: 			}
 1981: 		    }
 1982: 		}
 1983:             }
 1984:           } 
 1985:         }
 1986:         my $adv=0;
 1987:         my $author=0;
 1988:         foreach (keys %allroles) {
 1989:             %thesepriv=();
 1990:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
 1991:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 1992:             foreach (split(/:/,$allroles{$_})) {
 1993:                 if ($_ ne '') {
 1994: 		    my ($privilege,$restrictions)=split(/&/,$_);
 1995:                     if ($restrictions eq '') {
 1996: 			$thesepriv{$privilege}='F';
 1997:                     } else {
 1998:                         if ($thesepriv{$privilege} ne 'F') {
 1999: 			    $thesepriv{$privilege}.=$restrictions;
 2000:                         }
 2001:                     }
 2002:                 }
 2003:             }
 2004:             $thesestr='';
 2005:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2006:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
 2007:         }
 2008:         $userroles.='user.adv='.$adv."\n".
 2009: 	            'user.author='.$author."\n";
 2010:         $ENV{'user.adv'}=$adv;
 2011:     }
 2012:     return $userroles;  
 2013: }
 2014: 
 2015: # --------------------------------------------------------------- get interface
 2016: 
 2017: sub get {
 2018:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2019:    my $items='';
 2020:    foreach (@$storearr) {
 2021:        $items.=escape($_).'&';
 2022:    }
 2023:    $items=~s/\&$//;
 2024:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2025:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2026:    my $uhome=&homeserver($uname,$udomain);
 2027: 
 2028:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2029:    my @pairs=split(/\&/,$rep);
 2030:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2031:      return @pairs;
 2032:    }
 2033:    my %returnhash=();
 2034:    my $i=0;
 2035:    foreach (@$storearr) {
 2036:       $returnhash{$_}=unescape($pairs[$i]);
 2037:       $i++;
 2038:    }
 2039:    return %returnhash;
 2040: }
 2041: 
 2042: # --------------------------------------------------------------- del interface
 2043: 
 2044: sub del {
 2045:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2046:    my $items='';
 2047:    foreach (@$storearr) {
 2048:        $items.=escape($_).'&';
 2049:    }
 2050:    $items=~s/\&$//;
 2051:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2052:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2053:    my $uhome=&homeserver($uname,$udomain);
 2054: 
 2055:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2056: }
 2057: 
 2058: # -------------------------------------------------------------- dump interface
 2059: 
 2060: sub dump {
 2061:    my ($namespace,$udomain,$uname,$regexp)=@_;
 2062:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2063:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2064:    my $uhome=&homeserver($uname,$udomain);
 2065:    if ($regexp) {
 2066:        $regexp=&escape($regexp);
 2067:    } else {
 2068:        $regexp='.';
 2069:    }
 2070:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 2071:    my @pairs=split(/\&/,$rep);
 2072:    my %returnhash=();
 2073:    foreach (@pairs) {
 2074:       my ($key,$value)=split(/=/,$_);
 2075:       $returnhash{unescape($key)}=unescape($value);
 2076:    }
 2077:    return %returnhash;
 2078: }
 2079: 
 2080: # --------------------------------------------------------------- currentdump
 2081: sub currentdump {
 2082:    my ($courseid,$sdom,$sname)=@_;
 2083:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2084:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
 2085:    $sname    = $ENV{'user.name'}         if (! defined($sname));
 2086:    my $uhome = &homeserver($sname,$sdom);
 2087:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2088:    return if ($rep =~ /^(error:|no_such_host)/);
 2089:    #
 2090:    my %returnhash=();
 2091:    #
 2092:    if ($rep eq "unknown_cmd") { 
 2093:        # an old lond will not know currentdump
 2094:        # Do a dump and make it look like a currentdump
 2095:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2096:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2097:        my %hash = @tmp;
 2098:        @tmp=();
 2099:        # Code ripped from lond, essentially.  The only difference
 2100:        # here is the unescaping done by lonnet::dump().  Conceivably
 2101:        # we might run in to problems with parameter names =~ /^v\./
 2102:        while (my ($key,$value) = each(%hash)) {
 2103:            my ($v,$symb,$param) = split(/:/,$key);
 2104:            next if ($v eq 'version' || $symb eq 'keys');
 2105:            next if (exists($returnhash{$symb}) &&
 2106:                     exists($returnhash{$symb}->{$param}) &&
 2107:                     $returnhash{$symb}->{'v.'.$param} > $v);
 2108:            $returnhash{$symb}->{$param}=$value;
 2109:            $returnhash{$symb}->{'v.'.$param}=$v;
 2110:        }
 2111:        #
 2112:        # Remove all of the keys in the hashes which keep track of
 2113:        # the version of the parameter.
 2114:        while (my ($symb,$param_hash) = each(%returnhash)) {
 2115:            # use a foreach because we are going to delete from the hash.
 2116:            foreach my $key (keys(%$param_hash)) {
 2117:                delete($param_hash->{$key}) if ($key =~ /^v\./);
 2118:            }
 2119:        }
 2120:    } else {
 2121:        my @pairs=split(/\&/,$rep);
 2122:        foreach (@pairs) {
 2123:            my ($key,$value)=split(/=/,$_);
 2124:            my ($symb,$param) = split(/:/,$key);
 2125:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2126:                                                           &unescape($value);
 2127:        }
 2128:    }
 2129:    return %returnhash;
 2130: }
 2131: 
 2132: # --------------------------------------------------------------- put interface
 2133: 
 2134: sub put {
 2135:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2136:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2137:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2138:    my $uhome=&homeserver($uname,$udomain);
 2139:    my $items='';
 2140:    foreach (keys %$storehash) {
 2141:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
 2142:    }
 2143:    $items=~s/\&$//;
 2144:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2145: }
 2146: 
 2147: # ------------------------------------------------------ critical put interface
 2148: 
 2149: sub cput {
 2150:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2151:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2152:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2153:    my $uhome=&homeserver($uname,$udomain);
 2154:    my $items='';
 2155:    foreach (keys %$storehash) {
 2156:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
 2157:    }
 2158:    $items=~s/\&$//;
 2159:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 2160: }
 2161: 
 2162: # -------------------------------------------------------------- eget interface
 2163: 
 2164: sub eget {
 2165:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2166:    my $items='';
 2167:    foreach (@$storearr) {
 2168:        $items.=escape($_).'&';
 2169:    }
 2170:    $items=~s/\&$//;
 2171:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2172:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2173:    my $uhome=&homeserver($uname,$udomain);
 2174:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 2175:    my @pairs=split(/\&/,$rep);
 2176:    my %returnhash=();
 2177:    my $i=0;
 2178:    foreach (@$storearr) {
 2179:       $returnhash{$_}=unescape($pairs[$i]);
 2180:       $i++;
 2181:    }
 2182:    return %returnhash;
 2183: }
 2184: 
 2185: # ---------------------------------------------- Custom access rule evaluation
 2186: 
 2187: sub customaccess {
 2188:     my ($priv,$uri)=@_;
 2189:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
 2190:     $urealm=~s/^\W//;
 2191:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 2192:     my $access=0;
 2193:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 2194: 	my ($effect,$realm,$role)=split(/\:/,$_);
 2195:         if ($role) {
 2196: 	   if ($role ne $urole) { next; }
 2197:         }
 2198:         foreach (split(/\s*\,\s*/,$realm)) {
 2199:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 2200:             if ($tdom) {
 2201: 		if ($tdom ne $udom) { next; }
 2202:             }
 2203:             if ($tcrs) {
 2204: 		if ($tcrs ne $ucrs) { next; }
 2205:             }
 2206:             if ($tsec) {
 2207: 		if ($tsec ne $usec) { next; }
 2208:             }
 2209:             $access=($effect eq 'allow');
 2210:             last;
 2211:         }
 2212:     }
 2213:     return $access;
 2214: }
 2215: 
 2216: # ------------------------------------------------- Check for a user privilege
 2217: 
 2218: sub allowed {
 2219:     my ($priv,$uri)=@_;
 2220: 
 2221:     my $orguri=$uri;
 2222:     $uri=&declutter($uri);
 2223: 
 2224: # Free bre access to adm and meta resources
 2225: 
 2226:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 2227: 	return 'F';
 2228:     }
 2229: 
 2230: # Free bre to public access
 2231: 
 2232:     if ($priv eq 'bre') {
 2233:         my $copyright=&metadata($uri,'copyright');
 2234: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
 2235:            return 'F'; 
 2236:         }
 2237:         if ($copyright eq 'priv') {
 2238:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2239: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
 2240: 		return '';
 2241:             }
 2242:         }
 2243:         if ($copyright eq 'domain') {
 2244:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2245: 	    unless (($ENV{'user.domain'} eq $1) ||
 2246:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
 2247: 		return '';
 2248:             }
 2249:         }
 2250:         if ($ENV{'request.role'}=~ /li\.\//) {
 2251:             # Library role, so allow browsing of resources in this domain.
 2252:             return 'F';
 2253:         }
 2254:         if ($copyright eq 'custom') {
 2255: 	    unless (&customaccess($priv,$uri)) { return ''; }
 2256:         }
 2257:     }
 2258:     # Domain coordinator is trying to create a course
 2259:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
 2260:         # uri is the requested domain in this case.
 2261:         # comparison to 'request.role.domain' shows if the user has selected
 2262:         # a role of dc for the domain in question. 
 2263:         return 'F' if ($uri eq $ENV{'request.role.domain'});
 2264:     }
 2265: 
 2266:     my $thisallowed='';
 2267:     my $statecond=0;
 2268:     my $courseprivid='';
 2269: 
 2270: # Course
 2271: 
 2272:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
 2273:        $thisallowed.=$1;
 2274:     }
 2275: 
 2276: # Domain
 2277: 
 2278:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 2279:        =~/$priv\&([^\:]*)/) {
 2280:        $thisallowed.=$1;
 2281:     }
 2282: 
 2283: # Course: uri itself is a course
 2284:     my $courseuri=$uri;
 2285:     $courseuri=~s/\_(\d)/\/$1/;
 2286:     $courseuri=~s/^([^\/])/\/$1/;
 2287: 
 2288:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 2289:        =~/$priv\&([^\:]*)/) {
 2290:        $thisallowed.=$1;
 2291:     }
 2292: 
 2293: # URI is an uploaded document for this course
 2294: 
 2295:     if (($priv eq 'bre') && 
 2296:         ($uri=~/^uploaded\/$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}\/$ENV{'course.'.$ENV{'request.course.id'}.'.num'}/)) {
 2297:         return 'F';
 2298:     }
 2299: # Full access at system, domain or course-wide level? Exit.
 2300: 
 2301:     if ($thisallowed=~/F/) {
 2302: 	return 'F';
 2303:     }
 2304: 
 2305: # If this is generating or modifying users, exit with special codes
 2306: 
 2307:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
 2308: 	return $thisallowed;
 2309:     }
 2310: #
 2311: # Gathered so far: system, domain and course wide privileges
 2312: #
 2313: # Course: See if uri or referer is an individual resource that is part of 
 2314: # the course
 2315: 
 2316:     if ($ENV{'request.course.id'}) {
 2317: 
 2318:        $courseprivid=$ENV{'request.course.id'};
 2319:        if ($ENV{'request.course.sec'}) {
 2320:           $courseprivid.='/'.$ENV{'request.course.sec'};
 2321:        }
 2322:        $courseprivid=~s/\_/\//;
 2323:        my $checkreferer=1;
 2324:        my ($match,$cond)=&is_on_map($uri);
 2325:        if ($match) {
 2326:            $statecond=$cond;
 2327:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2328:                =~/$priv\&([^\:]*)/) {
 2329:                $thisallowed.=$1;
 2330:                $checkreferer=0;
 2331:            }
 2332:        }
 2333:        
 2334:        if ($checkreferer) {
 2335: 	  my $refuri=$ENV{'httpref.'.$orguri};
 2336:             unless ($refuri) {
 2337:                 foreach (keys %ENV) {
 2338: 		    if ($_=~/^httpref\..*\*/) {
 2339: 			my $pattern=$_;
 2340:                         $pattern=~s/^httpref\.\/res\///;
 2341:                         $pattern=~s/\*/\[\^\/\]\+/g;
 2342:                         $pattern=~s/\//\\\//g;
 2343:                         if ($orguri=~/$pattern/) {
 2344: 			    $refuri=$ENV{$_};
 2345:                         }
 2346:                     }
 2347:                 }
 2348:             }
 2349: 
 2350:          if ($refuri) { 
 2351: 	  $refuri=&declutter($refuri);
 2352:           my ($match,$cond)=&is_on_map($refuri);
 2353:             if ($match) {
 2354:               my $refstatecond=$cond;
 2355:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2356:                   =~/$priv\&([^\:]*)/) {
 2357:                   $thisallowed.=$1;
 2358:                   $uri=$refuri;
 2359:                   $statecond=$refstatecond;
 2360:               }
 2361:           }
 2362:         }
 2363:        }
 2364:    }
 2365: 
 2366: #
 2367: # Gathered now: all privileges that could apply, and condition number
 2368: # 
 2369: #
 2370: # Full or no access?
 2371: #
 2372: 
 2373:     if ($thisallowed=~/F/) {
 2374: 	return 'F';
 2375:     }
 2376: 
 2377:     unless ($thisallowed) {
 2378:         return '';
 2379:     }
 2380: 
 2381: # Restrictions exist, deal with them
 2382: #
 2383: #   C:according to course preferences
 2384: #   R:according to resource settings
 2385: #   L:unless locked
 2386: #   X:according to user session state
 2387: #
 2388: 
 2389: # Possibly locked functionality, check all courses
 2390: # Locks might take effect only after 10 minutes cache expiration for other
 2391: # courses, and 2 minutes for current course
 2392: 
 2393:     my $envkey;
 2394:     if ($thisallowed=~/L/) {
 2395:         foreach $envkey (keys %ENV) {
 2396:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 2397:                my $courseid=$2;
 2398:                my $roleid=$1.'.'.$2;
 2399:                $courseid=~s/^\///;
 2400:                my $expiretime=600;
 2401:                if ($ENV{'request.role'} eq $roleid) {
 2402: 		  $expiretime=120;
 2403:                }
 2404: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 2405:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 2406:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 2407: 		   &coursedescription($courseid);
 2408:                }
 2409:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
 2410:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 2411: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 2412:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 2413:                             $ENV{'user.home'},
 2414:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 2415:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 2416:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 2417: 		       return '';
 2418:                    }
 2419:                }
 2420:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
 2421:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 2422: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 2423:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 2424:                             $ENV{'user.home'},
 2425:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 2426:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 2427:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 2428: 		       return '';
 2429:                    }
 2430:                }
 2431: 	   }
 2432:        }
 2433:     }
 2434:    
 2435: #
 2436: # Rest of the restrictions depend on selected course
 2437: #
 2438: 
 2439:     unless ($ENV{'request.course.id'}) {
 2440:        return '1';
 2441:     }
 2442: 
 2443: #
 2444: # Now user is definitely in a course
 2445: #
 2446: 
 2447: 
 2448: # Course preferences
 2449: 
 2450:    if ($thisallowed=~/C/) {
 2451:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 2452:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
 2453:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 2454: 	   =~/$rolecode/) {
 2455:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2456:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 2457:                 $ENV{'request.course.id'});
 2458:            return '';
 2459:        }
 2460: 
 2461:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
 2462: 	   =~/$unamedom/) {
 2463:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2464:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 2465:                 $ENV{'request.course.id'});
 2466:            return '';
 2467:        }
 2468:    }
 2469: 
 2470: # Resource preferences
 2471: 
 2472:    if ($thisallowed=~/R/) {
 2473:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 2474:        if (&metadata($uri,'roledeny')=~/$rolecode/) {
 2475: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2476:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 2477:           return '';
 2478:        }
 2479:    }
 2480: 
 2481: # Restricted by state or randomout?
 2482: 
 2483:    if ($thisallowed=~/X/) {
 2484:       if ($ENV{'acc.randomout'}) {
 2485:          my $symb=&symbread($uri,1);
 2486:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
 2487:             return ''; 
 2488:          }
 2489:       }
 2490:       if (&condval($statecond)) {
 2491: 	 return '2';
 2492:       } else {
 2493:          return '';
 2494:       }
 2495:    }
 2496: 
 2497:    return 'F';
 2498: }
 2499: 
 2500: # --------------------------------------------------- Is a resource on the map?
 2501: 
 2502: sub is_on_map {
 2503:     my $uri=&declutter(shift);
 2504:     my @uriparts=split(/\//,$uri);
 2505:     my $filename=$uriparts[$#uriparts];
 2506:     my $pathname=$uri;
 2507:     $pathname=~s|/\Q$filename\E$||;
 2508:     $pathname=~s/^adm\/wrapper\///;    
 2509:     #Trying to find the conditional for the file
 2510:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 2511: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 2512:     if ($match) {
 2513: 	return (1,$1);
 2514:     } else {
 2515: 	return (0,0);
 2516:     }
 2517: }
 2518: 
 2519: # ----------------------------------------------------------------- Define Role
 2520: 
 2521: sub definerole {
 2522:   if (allowed('mcr','/')) {
 2523:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 2524:     foreach (split('/',$sysrole)) {
 2525: 	my ($crole,$cqual)=split(/\&/,$_);
 2526:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
 2527:         if ($pr{'cr:s'}=~/$crole\&/) {
 2528: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
 2529:                return "refused:s:$crole&$cqual"; 
 2530:             }
 2531:         }
 2532:     }
 2533:     foreach (split('/',$domrole)) {
 2534: 	my ($crole,$cqual)=split(/\&/,$_);
 2535:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
 2536:         if ($pr{'cr:d'}=~/$crole\&/) {
 2537: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
 2538:                return "refused:d:$crole&$cqual"; 
 2539:             }
 2540:         }
 2541:     }
 2542:     foreach (split('/',$courole)) {
 2543: 	my ($crole,$cqual)=split(/\&/,$_);
 2544:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
 2545:         if ($pr{'cr:c'}=~/$crole\&/) {
 2546: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
 2547:                return "refused:c:$crole&$cqual"; 
 2548:             }
 2549:         }
 2550:     }
 2551:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2552:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 2553: 	        "rolesdef_$rolename=".
 2554:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 2555:     return reply($command,$ENV{'user.home'});
 2556:   } else {
 2557:     return 'refused';
 2558:   }
 2559: }
 2560: 
 2561: # ---------------- Make a metadata query against the network of library servers
 2562: 
 2563: sub metadata_query {
 2564:     my ($query,$custom,$customshow,$server_array)=@_;
 2565:     my %rhash;
 2566:     my @server_list = (defined($server_array) ? @$server_array
 2567:                                               : keys(%libserv) );
 2568:     for my $server (@server_list) {
 2569: 	unless ($custom or $customshow) {
 2570: 	    my $reply=&reply("querysend:".&escape($query),$server);
 2571: 	    $rhash{$server}=$reply;
 2572: 	}
 2573: 	else {
 2574: 	    my $reply=&reply("querysend:".&escape($query).':'.
 2575: 			     &escape($custom).':'.&escape($customshow),
 2576: 			     $server);
 2577: 	    $rhash{$server}=$reply;
 2578: 	}
 2579:     }
 2580:     return \%rhash;
 2581: }
 2582: 
 2583: # ----------------------------------------- Send log queries and wait for reply
 2584: 
 2585: sub log_query {
 2586:     my ($uname,$udom,$query,%filters)=@_;
 2587:     my $uhome=&homeserver($uname,$udom);
 2588:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 2589:     my $uhost=$hostname{$uhome};
 2590:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 2591:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 2592:                        $uhome);
 2593:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
 2594:     return get_query_reply($queryid);
 2595: }
 2596: 
 2597: sub get_query_reply {
 2598:     my $queryid=shift;
 2599:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 2600:     my $reply='';
 2601:     for (1..100) {
 2602: 	sleep 2;
 2603:         if (-e $replyfile.'.end') {
 2604: 	    if (my $fh=Apache::File->new($replyfile)) {
 2605:                $reply.=<$fh>;
 2606:                $fh->close;
 2607: 	   } else { return 'error: reply_file_error'; }
 2608:            return &unescape($reply);
 2609: 	}
 2610:     }
 2611:     return 'timeout:'.$queryid;
 2612: }
 2613: 
 2614: sub courselog_query {
 2615: #
 2616: # possible filters:
 2617: # url: url or symb
 2618: # username
 2619: # domain
 2620: # action: view, submit, grade
 2621: # start: timestamp
 2622: # end: timestamp
 2623: #
 2624:     my (%filters)=@_;
 2625:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
 2626:     if ($filters{'url'}) {
 2627: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 2628:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 2629:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 2630:     }
 2631:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 2632:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 2633:     return &log_query($cname,$cdom,'courselog',%filters);
 2634: }
 2635: 
 2636: sub userlog_query {
 2637:     my ($uname,$udom,%filters)=@_;
 2638:     return &log_query($uname,$udom,'userlog',%filters);
 2639: }
 2640: 
 2641: # ------------------------------------------------------------------ Plain Text
 2642: 
 2643: sub plaintext {
 2644:     my $short=shift;
 2645:     return $prp{$short};
 2646: }
 2647: 
 2648: # ----------------------------------------------------------------- Assign Role
 2649: 
 2650: sub assignrole {
 2651:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 2652:     my $mrole;
 2653:     if ($role =~ /^cr\//) {
 2654: 	unless (&allowed('ccr',$url)) {
 2655:            &logthis('Refused custom assignrole: '.
 2656:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2657: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2658:            return 'refused'; 
 2659:         }
 2660:         $mrole='cr';
 2661:     } else {
 2662:         my $cwosec=$url;
 2663:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 2664:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 2665:            &logthis('Refused assignrole: '.
 2666:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2667: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2668:            return 'refused'; 
 2669:         }
 2670:         $mrole=$role;
 2671:     }
 2672:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2673:                 "$udom:$uname:$url".'_'."$mrole=$role";
 2674:     if ($end) { $command.='_'.$end; }
 2675:     if ($start) {
 2676: 	if ($end) { 
 2677:            $command.='_'.$start; 
 2678:         } else {
 2679:            $command.='_0_'.$start;
 2680:         }
 2681:     }
 2682: # actually delete
 2683:     if ($deleteflag) {
 2684: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 2685: # modify command to delete the role
 2686:            $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2687:                 "$udom:$uname:$url".'_'."$mrole";
 2688: 	   &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 2689: # set start and finish to negative values for userrolelog
 2690:            $start=-1;
 2691:            $end=-1;
 2692:         }
 2693:     }
 2694: # send command
 2695:     my $answer=&reply($command,&homeserver($uname,$udom));
 2696: # log new user role if status is ok
 2697:     if ($answer eq 'ok') {
 2698: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
 2699:     }
 2700:     return $answer;
 2701: }
 2702: 
 2703: # -------------------------------------------------- Modify user authentication
 2704: # Overrides without validation
 2705: 
 2706: sub modifyuserauth {
 2707:     my ($udom,$uname,$umode,$upass)=@_;
 2708:     my $uhome=&homeserver($uname,$udom);
 2709:     unless (&allowed('mau',$udom)) { return 'refused'; }
 2710:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 2711:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2712:              ' in domain '.$ENV{'request.role.domain'});  
 2713:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 2714: 		     &escape($upass),$uhome);
 2715:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
 2716:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 2717:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2718:     &log($udom,,$uname,$uhome,
 2719:         'Authentication changed by '.$ENV{'user.domain'}.', '.
 2720:                                      $ENV{'user.name'}.', '.$umode.
 2721:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2722:     unless ($reply eq 'ok') {
 2723:         &logthis('Authentication mode error: '.$reply);
 2724: 	return 'error: '.$reply;
 2725:     }   
 2726:     return 'ok';
 2727: }
 2728: 
 2729: # --------------------------------------------------------------- Modify a user
 2730: 
 2731: sub modifyuser {
 2732:     my ($udom,    $uname, $uid,
 2733:         $umode,   $upass, $first,
 2734:         $middle,  $last,  $gene,
 2735:         $forceid, $desiredhome)=@_;
 2736:     $udom=~s/\W//g;
 2737:     $uname=~s/\W//g;
 2738:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 2739:              $umode.', '.$first.', '.$middle.', '.
 2740: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 2741:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 2742:                                      ' desiredhome not specified'). 
 2743:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2744:              ' in domain '.$ENV{'request.role.domain'});
 2745:     my $uhome=&homeserver($uname,$udom,'true');
 2746: # ----------------------------------------------------------------- Create User
 2747:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
 2748:         my $unhome='';
 2749:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 2750:             $unhome = $desiredhome;
 2751: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 2752: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 2753:         } else { # load balancing routine for determining $unhome
 2754:             my $tryserver;
 2755:             my $loadm=10000000;
 2756:             foreach $tryserver (keys %libserv) {
 2757: 	       if ($hostdom{$tryserver} eq $udom) {
 2758:                   my $answer=reply('load',$tryserver);
 2759:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 2760: 		      $loadm=$answer;
 2761:                       $unhome=$tryserver;
 2762:                   }
 2763: 	       }
 2764: 	    }
 2765:         }
 2766:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 2767: 	    return 'error: unable to find a home server for '.$uname.
 2768:                    ' in domain '.$udom;
 2769:         }
 2770:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 2771:                          &escape($upass),$unhome);
 2772: 	unless ($reply eq 'ok') {
 2773:             return 'error: '.$reply;
 2774:         }   
 2775:         $uhome=&homeserver($uname,$udom,'true');
 2776:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 2777: 	    return 'error: verify home';
 2778:         }
 2779:     }   # End of creation of new user
 2780: # ---------------------------------------------------------------------- Add ID
 2781:     if ($uid) {
 2782:        $uid=~tr/A-Z/a-z/;
 2783:        my %uidhash=&idrget($udom,$uname);
 2784:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 2785:          && (!$forceid)) {
 2786: 	  unless ($uid eq $uidhash{$uname}) {
 2787: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
 2788:           }
 2789:        } else {
 2790: 	  &idput($udom,($uname => $uid));
 2791:        }
 2792:     }
 2793: # -------------------------------------------------------------- Add names, etc
 2794:     my @tmp=&get('environment',
 2795: 		   ['firstname','middlename','lastname','generation'],
 2796: 		   $udom,$uname);
 2797:     my %names;
 2798:     if ($tmp[0] =~ m/^error:.*/) { 
 2799:         %names=(); 
 2800:     } else {
 2801:         %names = @tmp;
 2802:     }
 2803:     if ($first)  { $names{'firstname'}  = $first; }
 2804:     if ($middle) { $names{'middlename'} = $middle; }
 2805:     if ($last)   { $names{'lastname'}   = $last; }
 2806:     if ($gene)   { $names{'generation'} = $gene; }
 2807:     my $reply = &put('environment', \%names, $udom,$uname);
 2808:     if ($reply ne 'ok') { return 'error: '.$reply; }
 2809:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 2810:              $umode.', '.$first.', '.$middle.', '.
 2811: 	     $last.', '.$gene.' by '.
 2812:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2813:     return 'ok';
 2814: }
 2815: 
 2816: # -------------------------------------------------------------- Modify student
 2817: 
 2818: sub modifystudent {
 2819:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 2820:         $end,$start,$forceid,$desiredhome)=@_;
 2821:     my $cid='';
 2822:     unless ($cid=$ENV{'request.course.id'}) {
 2823: 	return 'not_in_class';
 2824:     }
 2825: # --------------------------------------------------------------- Make the user
 2826:     my $reply=&modifyuser
 2827: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 2828:          $desiredhome);
 2829:     unless ($reply eq 'ok') { return $reply; }
 2830:     # This will cause &modify_student_enrollment to get the uid from the
 2831:     # students environment
 2832:     $uid = undef if (!$forceid);
 2833:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
 2834:                                         $last,$gene,$usec,$end,$start);
 2835:     return $reply;
 2836: }
 2837: 
 2838: sub modify_student_enrollment {
 2839:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
 2840:     # Get the course id from the environment
 2841:     my $cid='';
 2842:     unless ($cid=$ENV{'request.course.id'}) {
 2843: 	return 'not_in_class';
 2844:     }
 2845:     # Make sure the user exists
 2846:     my $uhome=&homeserver($uname,$udom);
 2847:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2848: 	return 'error: no such user';
 2849:     }
 2850:     #
 2851:     # Get student data if we were not given enough information
 2852:     if (!defined($first)  || $first  eq '' || 
 2853:         !defined($last)   || $last   eq '' || 
 2854:         !defined($uid)    || $uid    eq '' || 
 2855:         !defined($middle) || $middle eq '' || 
 2856:         !defined($gene)   || $gene   eq '') {
 2857:         # They did not supply us with enough data to enroll the student, so
 2858:         # we need to pick up more information.
 2859:         my %tmp = &get('environment',
 2860:                        ['firstname','middlename','lastname', 'generation','id']
 2861:                        ,$udom,$uname);
 2862: 
 2863:         foreach (keys(%tmp)) {
 2864:             &logthis("key $_ = ".$tmp{$_});
 2865:         }
 2866:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 2867:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 2868:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 2869:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 2870:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 2871:     }
 2872:     my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
 2873:                                                            $first,$middle);
 2874:     my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 2875: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
 2876:                       &escape($uname.':'.$udom).'='.
 2877:                       &escape(join(':',$end,$start,$uid,$usec,$fullname)),
 2878: 	              $ENV{'course.'.$cid.'.home'});
 2879:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 2880: 	return 'error: '.$reply;
 2881:     }
 2882:     # Add student role to user
 2883:     my $uurl='/'.$cid;
 2884:     $uurl=~s/\_/\//g;
 2885:     if ($usec) {
 2886: 	$uurl.='/'.$usec;
 2887:     }
 2888:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 2889: }
 2890: 
 2891: # ------------------------------------------------- Write to course preferences
 2892: 
 2893: sub writecoursepref {
 2894:     my ($courseid,%prefs)=@_;
 2895:     $courseid=~s/^\///;
 2896:     $courseid=~s/\_/\//g;
 2897:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2898:     my $chome=homeserver($cnum,$cdomain);
 2899:     if (($chome eq '') || ($chome eq 'no_host')) { 
 2900: 	return 'error: no such course';
 2901:     }
 2902:     my $cstring='';
 2903:     foreach (keys %prefs) {
 2904: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 2905:     }
 2906:     $cstring=~s/\&$//;
 2907:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 2908: }
 2909: 
 2910: # ---------------------------------------------------------- Make/modify course
 2911: 
 2912: sub createcourse {
 2913:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
 2914:     $url=&declutter($url);
 2915:     my $cid='';
 2916:     unless (&allowed('ccc',$udom)) {
 2917:         return 'refused';
 2918:     }
 2919: # ------------------------------------------------------------------- Create ID
 2920:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2921:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2922: # ----------------------------------------------- Make sure that does not exist
 2923:    my $uhome=&homeserver($uname,$udom,'true');
 2924:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2925:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2926:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2927:        $uhome=&homeserver($uname,$udom,'true');       
 2928:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2929:            return 'error: unable to generate unique course-ID';
 2930:        } 
 2931:    }
 2932: # ------------------------------------------------ Check supplied server name
 2933:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
 2934:     if (! exists($libserv{$course_server})) {
 2935:         return 'error:bad server name '.$course_server;
 2936:     }
 2937: # ------------------------------------------------------------- Make the course
 2938:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 2939:                       $course_server);
 2940:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 2941:     $uhome=&homeserver($uname,$udom,'true');
 2942:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2943: 	return 'error: no such course';
 2944:     }
 2945: # ----------------------------------------------------------------- Course made
 2946: # log existance
 2947:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
 2948:                  $uhome);
 2949:     &flushcourselogs();
 2950: # set toplevel url
 2951:     my $topurl=$url;
 2952:     unless ($nonstandard) {
 2953: # ------------------------------------------ For standard courses, make top url
 2954:         my $mapurl=&clutter($url);
 2955:         if ($mapurl eq '/res/') { $mapurl=''; }
 2956:         $ENV{'form.initmap'}=(<<ENDINITMAP);
 2957: <map>
 2958: <resource id="1" type="start"></resource>
 2959: <resource id="2" src="$mapurl"></resource>
 2960: <resource id="3" type="finish"></resource>
 2961: <link index="1" from="1" to="2"></link>
 2962: <link index="2" from="2" to="3"></link>
 2963: </map>
 2964: ENDINITMAP
 2965:         $topurl=&declutter(
 2966:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
 2967:                           );
 2968:     }
 2969: # ----------------------------------------------------------- Write preferences
 2970:     &writecoursepref($udom.'_'.$uname,
 2971:                      ('description' => $description,
 2972:                       'url'         => $topurl));
 2973:     return '/'.$udom.'/'.$uname;
 2974: }
 2975: 
 2976: # ---------------------------------------------------------- Assign Custom Role
 2977: 
 2978: sub assigncustomrole {
 2979:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 2980:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 2981:                        $end,$start,$deleteflag);
 2982: }
 2983: 
 2984: # ----------------------------------------------------------------- Revoke Role
 2985: 
 2986: sub revokerole {
 2987:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 2988:     my $now=time;
 2989:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 2990: }
 2991: 
 2992: # ---------------------------------------------------------- Revoke Custom Role
 2993: 
 2994: sub revokecustomrole {
 2995:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 2996:     my $now=time;
 2997:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 2998:            $deleteflag);
 2999: }
 3000: 
 3001: # ------------------------------------------------------------ Directory lister
 3002: 
 3003: sub dirlist {
 3004:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 3005: 
 3006:     $uri=~s/^\///;
 3007:     $uri=~s/\/$//;
 3008:     my ($udom, $uname);
 3009:     (undef,$udom,$uname)=split(/\//,$uri);
 3010:     if(defined($userdomain)) {
 3011:         $udom = $userdomain;
 3012:     }
 3013:     if(defined($username)) {
 3014:         $uname = $username;
 3015:     }
 3016: 
 3017:     my $dirRoot = $perlvar{'lonDocRoot'};
 3018:     if(defined($alternateDirectoryRoot)) {
 3019:         $dirRoot = $alternateDirectoryRoot;
 3020:         $dirRoot =~ s/\/$//;
 3021:     }
 3022: 
 3023:     if($udom) {
 3024:         if($uname) {
 3025:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
 3026:                               homeserver($uname,$udom));
 3027:             return split(/:/,$listing);
 3028:         } elsif(!defined($alternateDirectoryRoot)) {
 3029:             my $tryserver;
 3030:             my %allusers=();
 3031:             foreach $tryserver (keys %libserv) {
 3032:                 if($hostdom{$tryserver} eq $udom) {
 3033:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 3034:                                       $udom, $tryserver);
 3035:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 3036:                         && ($listing ne 'con_lost')) {
 3037:                         foreach (split(/:/,$listing)) {
 3038:                             my ($entry,@stat)=split(/&/,$_);
 3039:                             $allusers{$entry}=1;
 3040:                         }
 3041:                     }
 3042:                 }
 3043:             }
 3044:             my $alluserstr='';
 3045:             foreach (sort keys %allusers) {
 3046:                 $alluserstr.=$_.'&user:';
 3047:             }
 3048:             $alluserstr=~s/:$//;
 3049:             return split(/:/,$alluserstr);
 3050:         } else {
 3051:             my @emptyResults = ();
 3052:             push(@emptyResults, 'missing user name');
 3053:             return split(':',@emptyResults);
 3054:         }
 3055:     } elsif(!defined($alternateDirectoryRoot)) {
 3056:         my $tryserver;
 3057:         my %alldom=();
 3058:         foreach $tryserver (keys %libserv) {
 3059:             $alldom{$hostdom{$tryserver}}=1;
 3060:         }
 3061:         my $alldomstr='';
 3062:         foreach (sort keys %alldom) {
 3063:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
 3064:         }
 3065:         $alldomstr=~s/:$//;
 3066:         return split(/:/,$alldomstr);       
 3067:     } else {
 3068:         my @emptyResults = ();
 3069:         push(@emptyResults, 'missing domain');
 3070:         return split(':',@emptyResults);
 3071:     }
 3072: }
 3073: 
 3074: # --------------------------------------------- GetFileTimestamp
 3075: # This function utilizes dirlist and returns the date stamp for
 3076: # when it was last modified.  It will also return an error of -1
 3077: # if an error occurs
 3078: 
 3079: sub GetFileTimestamp {
 3080:     my ($studentDomain,$studentName,$filename,$root)=@_;
 3081:     $studentDomain=~s/\W//g;
 3082:     $studentName=~s/\W//g;
 3083:     my $subdir=$studentName.'__';
 3084:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 3085:     my $proname="$studentDomain/$subdir/$studentName";
 3086:     $proname .= '/'.$filename;
 3087:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 3088:                                               $studentName, $root);
 3089:     my @stats = split('&', $fileStat);
 3090:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 3091:         # @stats contains first the filename, then the stat output
 3092:         return $stats[10]; # so this is 10 instead of 9.
 3093:     } else {
 3094:         return -1;
 3095:     }
 3096: }
 3097: 
 3098: # -------------------------------------------------------- Value of a Condition
 3099: 
 3100: sub directcondval {
 3101:     my $number=shift;
 3102:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 3103:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 3104:     } else {
 3105:        return 2;
 3106:     }
 3107: }
 3108: 
 3109: sub condval {
 3110:     my $condidx=shift;
 3111:     my $result=0;
 3112:     my $allpathcond='';
 3113:     foreach (split(/\|/,$condidx)) {
 3114:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 3115: 	   $allpathcond.=
 3116:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 3117:        }
 3118:     }
 3119:     $allpathcond=~s/\|$//;
 3120:     if ($ENV{'request.course.id'}) {
 3121:        if ($allpathcond) {
 3122:           my $operand='|';
 3123: 	  my @stack;
 3124:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 3125:               if ($_ eq '(') {
 3126:                  push @stack,($operand,$result)
 3127:               } elsif ($_ eq ')') {
 3128:                   my $before=pop @stack;
 3129: 		  if (pop @stack eq '&') {
 3130: 		      $result=$result>$before?$before:$result;
 3131:                   } else {
 3132:                       $result=$result>$before?$result:$before;
 3133:                   }
 3134:               } elsif (($_ eq '&') || ($_ eq '|')) {
 3135:                   $operand=$_;
 3136:               } else {
 3137:                   my $new=directcondval($_);
 3138:                   if ($operand eq '&') {
 3139:                      $result=$result>$new?$new:$result;
 3140:                   } else {
 3141:                      $result=$result>$new?$result:$new;
 3142:                   }
 3143:               }
 3144:           }
 3145:        }
 3146:     }
 3147:     return $result;
 3148: }
 3149: 
 3150: # ---------------------------------------------------- Devalidate courseresdata
 3151: 
 3152: sub devalidatecourseresdata {
 3153:     my ($coursenum,$coursedomain)=@_;
 3154:     my $hashid=$coursenum.':'.$coursedomain;
 3155:     delete $courseresdatacache{$hashid.'.time'};
 3156: }
 3157: 
 3158: # --------------------------------------------------- Course Resourcedata Query
 3159: 
 3160: sub courseresdata {
 3161:     my ($coursenum,$coursedomain,@which)=@_;
 3162:     my $coursehom=&homeserver($coursenum,$coursedomain);
 3163:     my $hashid=$coursenum.':'.$coursedomain;
 3164:     my $dodump=0;
 3165:     if (!defined($courseresdatacache{$hashid.'.time'})) {
 3166: 	$dodump=1;
 3167:     } else {
 3168: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
 3169:     }
 3170:     if ($dodump) {
 3171: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 3172: 	my ($tmp) = keys(%dumpreply);
 3173: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 3174: 	    $courseresdatacache{$hashid.'.time'}=time;
 3175: 	    $courseresdatacache{$hashid}=\%dumpreply;
 3176: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 3177: 	    return $tmp;
 3178: 	}
 3179:     }
 3180:     foreach my $item (@which) {
 3181: 	if (defined($courseresdatacache{$hashid}->{$item})) {
 3182: 	    return $courseresdatacache{$hashid}->{$item};
 3183: 	}
 3184:     }
 3185:     return undef;
 3186: }
 3187: 
 3188: #
 3189: # EXT resource caching routines
 3190: #
 3191: 
 3192: sub clear_EXT_cache_status {
 3193:     &delenv('cache.');
 3194: }
 3195: 
 3196: sub EXT_cache_status {
 3197:     my ($target_domain,$target_user) = @_;
 3198:     my $cachename = 'cache.'.$target_user.'.'.$target_domain;
 3199:     if (exists($ENV{$cachename}) && ($ENV{$cachename}+1800) > time) {
 3200:         # We know already the user has no data
 3201:         return 1;
 3202:     } else {
 3203:         return 0;
 3204:     }
 3205: }
 3206: 
 3207: sub EXT_cache_set {
 3208:     my ($target_domain,$target_user) = @_;
 3209:     my $cachename = 'cache.'.$target_user.'.'.$target_domain;
 3210:     &appenv($cachename => time);
 3211: }
 3212: 
 3213: # --------------------------------------------------------- Value of a Variable
 3214: sub EXT {
 3215:     my ($varname,$symbparm,$udom,$uname,$usection)=@_;
 3216: 
 3217:     unless ($varname) { return ''; }
 3218:     #get real user name/domain, courseid and symb
 3219:     my $courseid;
 3220:     my $publicuser;
 3221:     if (!($uname && $udom)) {
 3222:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 3223: 	  &Apache::lonxml::whichuser($symbparm);
 3224:       if (!$symbparm) {	$symbparm=$cursymb; }
 3225:     } else {
 3226: 	$courseid=$ENV{'request.course.id'};
 3227:     }
 3228:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 3229:     my $rest;
 3230:     if (defined($therest[0])) {
 3231:        $rest=join('.',@therest);
 3232:     } else {
 3233:        $rest='';
 3234:     }
 3235: 
 3236:     my $qualifierrest=$qualifier;
 3237:     if ($rest) { $qualifierrest.='.'.$rest; }
 3238:     my $spacequalifierrest=$space;
 3239:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 3240:     if ($realm eq 'user') {
 3241: # --------------------------------------------------------------- user.resource
 3242: 	if ($space eq 'resource') {
 3243: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
 3244: 		return $Apache::lonhomework::history{$qualifierrest};
 3245: 	    } else {
 3246: 		my %restored;
 3247: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
 3248: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 3249: 		} else {
 3250: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 3251: 		}
 3252: 		return $restored{$qualifierrest};
 3253: 	    }
 3254: # ----------------------------------------------------------------- user.access
 3255:         } elsif ($space eq 'access') {
 3256: 	    # FIXME - not supporting calls for a specific user
 3257:             return &allowed($qualifier,$rest);
 3258: # ------------------------------------------ user.preferences, user.environment
 3259:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 3260: 	    if (($uname eq $ENV{'user.name'}) &&
 3261: 		($udom eq $ENV{'user.domain'})) {
 3262: 		return $ENV{join('.',('environment',$qualifierrest))};
 3263: 	    } else {
 3264: 		my %returnhash;
 3265: 		if (!$publicuser) {
 3266: 		    %returnhash=&userenvironment($udom,$uname,
 3267: 						 $qualifierrest);
 3268: 		}
 3269: 		return $returnhash{$qualifierrest};
 3270: 	    }
 3271: # ----------------------------------------------------------------- user.course
 3272:         } elsif ($space eq 'course') {
 3273: 	    # FIXME - not supporting calls for a specific user
 3274:             return $ENV{join('.',('request.course',$qualifier))};
 3275: # ------------------------------------------------------------------- user.role
 3276:         } elsif ($space eq 'role') {
 3277: 	    # FIXME - not supporting calls for a specific user
 3278:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 3279:             if ($qualifier eq 'value') {
 3280: 		return $role;
 3281:             } elsif ($qualifier eq 'extent') {
 3282:                 return $where;
 3283:             }
 3284: # ----------------------------------------------------------------- user.domain
 3285:         } elsif ($space eq 'domain') {
 3286:             return $udom;
 3287: # ------------------------------------------------------------------- user.name
 3288:         } elsif ($space eq 'name') {
 3289:             return $uname;
 3290: # ---------------------------------------------------- Any other user namespace
 3291:         } else {
 3292: 	    my %reply;
 3293: 	    if (!$publicuser) {
 3294: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 3295: 	    }
 3296: 	    return $reply{$qualifierrest};
 3297:         }
 3298:     } elsif ($realm eq 'query') {
 3299: # ---------------------------------------------- pull stuff out of query string
 3300:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},[$space]);
 3301: 	return $ENV{'form.'.$spacequalifierrest}; 
 3302:    } elsif ($realm eq 'request') {
 3303: # ------------------------------------------------------------- request.browser
 3304:         if ($space eq 'browser') {
 3305: 	    return $ENV{'browser.'.$qualifier};
 3306: # ------------------------------------------------------------ request.filename
 3307:         } else {
 3308:             return $ENV{'request.'.$spacequalifierrest};
 3309:         }
 3310:     } elsif ($realm eq 'course') {
 3311: # ---------------------------------------------------------- course.description
 3312:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
 3313:     } elsif ($realm eq 'resource') {
 3314: 
 3315: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
 3316: 
 3317: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 3318: 
 3319: # ----------------------------------------------------- Cascading lookup scheme
 3320: 	    if (!$symbparm) { $symbparm=&symbread(); }
 3321: 	    my $symbp=$symbparm;
 3322: 	    my $mapp=(split(/\_\_\_/,$symbp))[0];
 3323: 
 3324: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 3325: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 3326: 
 3327: 	    my $section;
 3328: 	    if (($ENV{'user.name'} eq $uname) &&
 3329: 		($ENV{'user.domain'} eq $udom)) {
 3330: 		$section=$ENV{'request.course.sec'};
 3331: 	    } else {
 3332:                 if (! defined($usection)) {
 3333:                     $section=&usection($udom,$uname,$courseid);
 3334:                 } else {
 3335:                     $section = $usection;
 3336:                 }
 3337: 	    }
 3338: 
 3339: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 3340: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 3341: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 3342: 
 3343: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
 3344: 	    my $courselevelr=$courseid.'.'.$symbparm;
 3345: 	    my $courselevelm=$courseid.'.'.$mapparm;
 3346: 
 3347: # ----------------------------------------------------------- first, check user
 3348: 	    #most student don\'t have any data set, check if there is some data
 3349:             #every thirty minutes
 3350: 	    if (! &EXT_cache_status($udom,$uname)) {
 3351: 		my %resourcedata=&get('resourcedata',
 3352: 				      [$courselevelr,$courselevelm,$courselevel],
 3353: 				      $udom,$uname);
 3354: 		my ($tmp)=keys(%resourcedata);
 3355: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 3356: 		    if ($resourcedata{$courselevelr}) {
 3357: 			return $resourcedata{$courselevelr}; }
 3358: 		    if ($resourcedata{$courselevelm}) {
 3359: 			return $resourcedata{$courselevelm}; }
 3360: 		    if ($resourcedata{$courselevel}) {
 3361: 			return $resourcedata{$courselevel}; }
 3362: 		} else {
 3363: 		    if ($tmp!~/No such file/) {
 3364: 			&logthis("<font color=blue>WARNING:".
 3365: 				 " Trying to get resource data for ".
 3366: 				 $uname." at ".$udom.": ".
 3367: 				 $tmp."</font>");
 3368: 		    } elsif ($tmp=~/error:No such file/) {
 3369:                         &EXT_cache_set($udom,$uname);
 3370: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 3371: 			return $tmp;
 3372: 		    }
 3373: 		}
 3374: 	    }
 3375: 
 3376: # -------------------------------------------------------- second, check course
 3377: 
 3378: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
 3379: 					  $ENV{'course.'.$courseid.'.domain'},
 3380: 					  ($seclevelr,$seclevelm,$seclevel,
 3381: 					   $courselevelr,$courselevelm,
 3382: 					   $courselevel));
 3383: 	    if (defined($coursereply)) { return $coursereply; }
 3384: 
 3385: # ------------------------------------------------------ third, check map parms
 3386: 	    my %parmhash=();
 3387: 	    my $thisparm='';
 3388: 	    if (tie(%parmhash,'GDBM_File',
 3389: 		    $ENV{'request.course.fn'}.'_parms.db',
 3390: 		    &GDBM_READER(),0640)) {
 3391: 		$thisparm=$parmhash{$symbparm};
 3392: 		untie(%parmhash);
 3393: 	    }
 3394: 	    if ($thisparm) { return $thisparm; }
 3395: 	}
 3396: # --------------------------------------------- last, look in resource metadata
 3397: 
 3398: 	$spacequalifierrest=~s/\./\_/;
 3399: 	my $filename;
 3400: 	if (!$symbparm) { $symbparm=&symbread(); }
 3401: 	if ($symbparm) {
 3402: 	    $filename=(split(/\_\_\_/,$symbparm))[2];
 3403: 	} else {
 3404: 	    $filename=$ENV{'request.filename'};
 3405: 	}
 3406: 	my $metadata=&metadata($filename,$spacequalifierrest);
 3407: 	if (defined($metadata)) { return $metadata; }
 3408: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 3409: 	if (defined($metadata)) { return $metadata; }
 3410: 
 3411: # ------------------------------------------------------------------ Cascade up
 3412: 	unless ($space eq '0') {
 3413: 	    my @parts=split(/_/,$space);
 3414: 	    my $id=pop(@parts);
 3415: 	    my $part=join('_',@parts);
 3416: 	    if ($part eq '') { $part='0'; }
 3417: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 3418: 				 $symbparm,$udom,$uname);
 3419: 	    if (defined($partgeneral)) { return $partgeneral; }
 3420: 	}
 3421: 
 3422: # ---------------------------------------------------- Any other user namespace
 3423:     } elsif ($realm eq 'environment') {
 3424: # ----------------------------------------------------------------- environment
 3425: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
 3426: 	    return $ENV{'environment.'.$spacequalifierrest};
 3427: 	} else {
 3428: 	    my %returnhash=&userenvironment($udom,$uname,
 3429: 					    $spacequalifierrest);
 3430: 	    return $returnhash{$spacequalifierrest};
 3431: 	}
 3432:     } elsif ($realm eq 'system') {
 3433: # ----------------------------------------------------------------- system.time
 3434: 	if ($space eq 'time') {
 3435: 	    return time;
 3436:         }
 3437:     }
 3438:     return '';
 3439: }
 3440: 
 3441: sub add_prefix_and_part {
 3442:     my ($prefix,$part)=@_;
 3443:     my $keyroot;
 3444:     if (defined($prefix) && $prefix !~ /^__/) {
 3445: 	# prefix that has a part already
 3446: 	$keyroot=$prefix;
 3447:     } elsif (defined($prefix)) {
 3448: 	# prefix that is missing a part
 3449: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 3450:     } else {
 3451: 	# no prefix at all
 3452: 	if (defined($part)) { $keyroot='_'.$part; }
 3453:     }
 3454:     return $keyroot;
 3455: }
 3456: 
 3457: # ---------------------------------------------------------------- Get metadata
 3458: 
 3459: sub metadata {
 3460:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 3461: 
 3462:     $uri=&declutter($uri);
 3463:     # if it is a non metadata possible uri return quickly
 3464:     if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
 3465:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
 3466: 	return '';
 3467:     }
 3468:     my $filename=$uri;
 3469:     $uri=~s/\.meta$//;
 3470: #
 3471: # Is the metadata already cached?
 3472: # Look at timestamp of caching
 3473: # Everything is cached by the main uri, libraries are never directly cached
 3474: #
 3475:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
 3476: #
 3477: # Is this a recursive call for a library?
 3478: #
 3479:         if ($liburi) {
 3480: 	    $liburi=&declutter($liburi);
 3481:             $filename=$liburi;
 3482:         }
 3483:         my %metathesekeys=();
 3484:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 3485: 	my $metastring=&getfile(&filelocation('',&clutter($filename)));
 3486:         my $parser=HTML::LCParser->new(\$metastring);
 3487:         my $token;
 3488:         undef %metathesekeys;
 3489: 	delete($metacache{$uri.':packages'});
 3490:         while ($token=$parser->get_token) {
 3491: 	    if ($token->[0] eq 'S') {
 3492: 		if (defined($token->[2]->{'package'})) {
 3493: #
 3494: # This is a package - get package info
 3495: #
 3496: 		    my $package=$token->[2]->{'package'};
 3497: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3498: 		    if (defined($token->[2]->{'id'})) { 
 3499: 			$keyroot.='_'.$token->[2]->{'id'}; 
 3500: 		    }
 3501: 		    if ($metacache{$uri.':packages'}) {
 3502: 			$metacache{$uri.':packages'}.=','.$package.$keyroot;
 3503: 		    } else {
 3504: 			$metacache{$uri.':packages'}=$package.$keyroot;
 3505: 		    }
 3506: 		    foreach (keys %packagetab) {
 3507: 			if ($_=~/^$package\&/) {
 3508: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 3509: 			    my $value=$packagetab{$_};
 3510: 			    my $part=$keyroot;
 3511: 			    $part=~s/^\_//;
 3512: 			    if ($subp eq 'display') {
 3513: 				$value.=' [Part: '.$part.']';
 3514: 			    }
 3515: 			    my $unikey='parameter'.$keyroot.'_'.$name;
 3516: 			    if ($subp eq 'default') {
 3517: 				$unikey='parameter_0_'.$name;
 3518: 				$metacache{$uri.':'.$unikey.'.part'}='0';
 3519: 			    } else {
 3520: 				$metacache{$uri.':'.$unikey.'.part'}=$part;
 3521: 				$metathesekeys{$unikey}=1;
 3522: 			    }
 3523: 			    unless (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
 3524: 				$metacache{$uri.':'.$unikey.'.'.$subp}=$value;
 3525: 			    }
 3526: 			    if (defined($metacache{$uri.':'.$unikey.'.default'})) {
 3527: 				$metacache{$uri.':'.$unikey}=
 3528: 				    $metacache{$uri.':'.$unikey.'.default'};
 3529: 			    }
 3530: 			}
 3531: 		    }
 3532: 		} else {
 3533: #
 3534: # This is not a package - some other kind of start tag
 3535: #
 3536: 		    my $entry=$token->[1];
 3537: 		    my $unikey;
 3538: 		    if ($entry eq 'import') {
 3539: 			$unikey='';
 3540: 		    } else {
 3541: 			$unikey=$entry;
 3542: 		    }
 3543: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3544: 
 3545: 		    if (defined($token->[2]->{'id'})) { 
 3546: 			$unikey.='_'.$token->[2]->{'id'}; 
 3547: 		    }
 3548: 
 3549: 		    if ($entry eq 'import') {
 3550: #
 3551: # Importing a library here
 3552: #
 3553: 			if ($depthcount<20) {
 3554: 			    my $location=$parser->get_text('/import');
 3555: 			    my $dir=$filename;
 3556: 			    $dir=~s|[^/]*$||;
 3557: 			    $location=&filelocation($dir,$location);
 3558: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 3559: 							       $location,$unikey,
 3560: 							       $depthcount+1)))) {
 3561: 				$metathesekeys{$_}=1;
 3562: 			    }
 3563: 			}
 3564: 		    } else { 
 3565: 			
 3566: 			if (defined($token->[2]->{'name'})) { 
 3567: 			    $unikey.='_'.$token->[2]->{'name'}; 
 3568: 			}
 3569: 			$metathesekeys{$unikey}=1;
 3570: 			foreach (@{$token->[3]}) {
 3571: 			    $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
 3572: 			}
 3573: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 3574: 			my $default=$metacache{$uri.':'.$unikey.'.default'};
 3575: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 3576: 		 # only ws inside the tag, and not in default, so use default
 3577: 		 # as value
 3578: 			    $metacache{$uri.':'.$unikey}=$default;
 3579: 			} else {
 3580: 		  # either something interesting inside the tag or default
 3581:                   # uninteresting
 3582: 			    $metacache{$uri.':'.$unikey}=$internaltext;
 3583: 			}
 3584: # end of not-a-package not-a-library import
 3585: 		    }
 3586: # end of not-a-package start tag
 3587: 		}
 3588: # the next is the end of "start tag"
 3589: 	    }
 3590: 	}
 3591: # are there custom rights to evaluate
 3592: 	if ($metacache{$uri.':copyright'} eq 'custom') {
 3593: 
 3594:     #
 3595:     # Importing a rights file here
 3596:     #
 3597: 	    unless ($depthcount) {
 3598: 		my $location=$metacache{$uri.':customdistributionfile'};
 3599: 		my $dir=$filename;
 3600: 		$dir=~s|[^/]*$||;
 3601: 		$location=&filelocation($dir,$location);
 3602: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 3603: 						   $location,'_rights',
 3604: 						   $depthcount+1)))) {
 3605: 		    $metathesekeys{$_}=1;
 3606: 		}
 3607: 	    }
 3608: 	}
 3609: 	$metacache{$uri.':keys'}=join(',',keys %metathesekeys);
 3610: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
 3611: 	$metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
 3612: 	$metacache{$uri.':cachedtimestamp'}=time;
 3613: # this is the end of "was not already recently cached
 3614:     }
 3615:     return $metacache{$uri.':'.$what};
 3616: }
 3617: 
 3618: sub metadata_generate_part0 {
 3619:     my ($metadata,$metacache,$uri) = @_;
 3620:     my %allnames;
 3621:     foreach my $metakey (sort keys %$metadata) {
 3622: 	if ($metakey=~/^parameter\_(.*)/) {
 3623: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
 3624: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
 3625: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 3626: 	    $allnames{$name}=$part;
 3627: 	  }
 3628: 	}
 3629:     }
 3630:     foreach my $name (keys(%allnames)) {
 3631:       $$metadata{"parameter_0_$name"}=1;
 3632:       my $key="$uri:parameter_0_$name";
 3633:       $$metacache{"$key.part"}='0';
 3634:       $$metacache{"$key.name"}=$name;
 3635:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
 3636: 					   $allnames{$name}.'_'.$name.
 3637: 					   '.type'};
 3638:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
 3639: 			     '.display'};
 3640:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
 3641:       $olddis=~s/$expr/\[Part: 0\]/;
 3642:       $$metacache{"$key.display"}=$olddis;
 3643:     }
 3644: }
 3645: 
 3646: # ------------------------------------------------- Get the title of a resource
 3647: 
 3648: sub gettitle {
 3649:     my $urlsymb=shift;
 3650:     my $symb=&symbread($urlsymb);
 3651:     unless ($symb) {
 3652: 	unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
 3653:         return &metadata($urlsymb,'title'); 
 3654:     }
 3655:     if ($titlecache{$symb}) {
 3656: 	if (time < ($titlecache{$symb}[1] + 600)) {
 3657: 	    return $titlecache{$symb}[0];
 3658: 	} else {
 3659: 	    delete($titlecache{$symb});
 3660: 	}
 3661:     }
 3662:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
 3663:     my $title='';
 3664:     my %bighash;
 3665:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3666:                             &GDBM_READER(),0640)) {
 3667:         my $mapid=$bighash{'map_pc_'.&clutter($map)};
 3668:         $title=$bighash{'title_'.$mapid.'.'.$resid};
 3669:         untie %bighash;
 3670:     }
 3671:     $title=~s/\&colon\;/\:/gs;
 3672:     if ($title) {
 3673:         $titlecache{$symb}=[$title,time];
 3674:         return $title;
 3675:     } else {
 3676: 	return &metadata($urlsymb,'title');
 3677:     }
 3678: }
 3679:     
 3680: # ------------------------------------------------- Update symbolic store links
 3681: 
 3682: sub symblist {
 3683:     my ($mapname,%newhash)=@_;
 3684:     $mapname=declutter($mapname);
 3685:     my %hash;
 3686:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 3687:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3688:                       &GDBM_WRCREAT(),0640)) {
 3689: 	    foreach (keys %newhash) {
 3690:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
 3691:             }
 3692:             if (untie(%hash)) {
 3693: 		return 'ok';
 3694:             }
 3695:         }
 3696:     }
 3697:     return 'error';
 3698: }
 3699: 
 3700: # --------------------------------------------------------------- Verify a symb
 3701: 
 3702: sub symbverify {
 3703:     my ($symb,$thisfn)=@_;
 3704:     $thisfn=&declutter($thisfn);
 3705: # direct jump to resource in page or to a sequence - will construct own symbs
 3706:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 3707: # check URL part
 3708:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
 3709:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
 3710: 
 3711:     $symb=&symbclean($symb);
 3712: 
 3713:     my %bighash;
 3714:     my $okay=0;
 3715:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3716:                             &GDBM_READER(),0640)) {
 3717:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3718:         unless ($ids) { 
 3719:            $ids=$bighash{'ids_/'.$thisfn};
 3720:         }
 3721:         if ($ids) {
 3722: # ------------------------------------------------------------------- Has ID(s)
 3723: 	    foreach (split(/\,/,$ids)) {
 3724:                my ($mapid,$resid)=split(/\./,$_);
 3725:                if (
 3726:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 3727:    eq $symb) { 
 3728:                   $okay=1; 
 3729:                }
 3730: 	   }
 3731:         }
 3732: 	untie(%bighash);
 3733:     }
 3734:     return $okay;
 3735: }
 3736: 
 3737: # --------------------------------------------------------------- Clean-up symb
 3738: 
 3739: sub symbclean {
 3740:     my $symb=shift;
 3741: 
 3742: # remove version from map
 3743:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 3744: 
 3745: # remove version from URL
 3746:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 3747: 
 3748:     return $symb;
 3749: }
 3750: 
 3751: # ------------------------------------------------------ Return symb list entry
 3752: 
 3753: sub symbread {
 3754:     my ($thisfn,$donotrecurse)=@_;
 3755: # no filename provided? try from environment
 3756:     unless ($thisfn) {
 3757:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
 3758: 	$thisfn=$ENV{'request.filename'};
 3759:     }
 3760: # is that filename actually a symb? Verify, clean, and return
 3761:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 3762: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
 3763:     }
 3764:     $thisfn=declutter($thisfn);
 3765:     my %hash;
 3766:     my %bighash;
 3767:     my $syval='';
 3768:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 3769:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3770:                       &GDBM_READER(),0640)) {
 3771: 	    $syval=$hash{$thisfn};
 3772:             untie(%hash);
 3773:         }
 3774: # ---------------------------------------------------------- There was an entry
 3775:         if ($syval) {
 3776:            unless ($syval=~/\_\d+$/) {
 3777: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 3778:                   &appenv('request.ambiguous' => $thisfn);
 3779:                   return '';
 3780:                }    
 3781:                $syval.=$1;
 3782: 	   }
 3783:         } else {
 3784: # ------------------------------------------------------- Was not in symb table
 3785:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3786:                             &GDBM_READER(),0640)) {
 3787: # ---------------------------------------------- Get ID(s) for current resource
 3788:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3789:               unless ($ids) { 
 3790:                  $ids=$bighash{'ids_/'.$thisfn};
 3791:               }
 3792:               unless ($ids) {
 3793: # alias?
 3794: 		  $ids=$bighash{'mapalias_'.$thisfn};
 3795:               }
 3796:               if ($ids) {
 3797: # ------------------------------------------------------------------- Has ID(s)
 3798:                  my @possibilities=split(/\,/,$ids);
 3799:                  if ($#possibilities==0) {
 3800: # ----------------------------------------------- There is only one possibility
 3801: 		     my ($mapid,$resid)=split(/\./,$ids);
 3802:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 3803:                  } elsif (!$donotrecurse) {
 3804: # ------------------------------------------ There is more than one possibility
 3805:                      my $realpossible=0;
 3806:                      foreach (@possibilities) {
 3807: 			 my $file=$bighash{'src_'.$_};
 3808:                          if (&allowed('bre',$file)) {
 3809:          		    my ($mapid,$resid)=split(/\./,$_);
 3810:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 3811: 				$realpossible++;
 3812:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 3813:                                        '___'.$resid;
 3814:                             }
 3815: 			 }
 3816:                      }
 3817: 		     if ($realpossible!=1) { $syval=''; }
 3818:                  } else {
 3819:                      $syval='';
 3820:                  }
 3821: 	      }
 3822:               untie(%bighash)
 3823:            } 
 3824:         }
 3825:         if ($syval) {
 3826:            return &symbclean($syval.'___'.$thisfn); 
 3827:         }
 3828:     }
 3829:     &appenv('request.ambiguous' => $thisfn);
 3830:     return '';
 3831: }
 3832: 
 3833: # ---------------------------------------------------------- Return random seed
 3834: 
 3835: sub numval {
 3836:     my $txt=shift;
 3837:     $txt=~tr/A-J/0-9/;
 3838:     $txt=~tr/a-j/0-9/;
 3839:     $txt=~tr/K-T/0-9/;
 3840:     $txt=~tr/k-t/0-9/;
 3841:     $txt=~tr/U-Z/0-5/;
 3842:     $txt=~tr/u-z/0-5/;
 3843:     $txt=~s/\D//g;
 3844:     return int($txt);
 3845: }
 3846: 
 3847: sub latest_rnd_algorithm_id {
 3848:     return '64bit';
 3849: }
 3850: 
 3851: sub rndseed {
 3852:     my ($symb,$courseid,$domain,$username)=@_;
 3853: 
 3854:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 3855:     if (!$symb) {
 3856: 	unless ($symb=$wsymb) { return time; }
 3857:     }
 3858:     if (!$courseid) { $courseid=$wcourseid; }
 3859:     if (!$domain) { $domain=$wdomain; }
 3860:     if (!$username) { $username=$wusername }
 3861:     my $which=$ENV{"course.$courseid.rndseed"};
 3862:     my $CODE=$ENV{'scantron.CODE'};
 3863:     if (defined($CODE)) {
 3864: 	&rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 3865:     } elsif ($which eq '64bit') {
 3866: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 3867:     }
 3868:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 3869: }
 3870: 
 3871: sub rndseed_32bit {
 3872:     my ($symb,$courseid,$domain,$username)=@_;
 3873:     {
 3874: 	use integer;
 3875: 	my $symbchck=unpack("%32C*",$symb) << 27;
 3876: 	my $symbseed=numval($symb) << 22;
 3877: 	my $namechck=unpack("%32C*",$username) << 17;
 3878: 	my $nameseed=numval($username) << 12;
 3879: 	my $domainseed=unpack("%32C*",$domain) << 7;
 3880: 	my $courseseed=unpack("%32C*",$courseid);
 3881: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 3882: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 3883: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 3884: 	return $num;
 3885:     }
 3886: }
 3887: 
 3888: sub rndseed_64bit {
 3889:     my ($symb,$courseid,$domain,$username)=@_;
 3890:     {
 3891: 	use integer;
 3892: 	my $symbchck=unpack("%32S*",$symb) << 21;
 3893: 	my $symbseed=numval($symb) << 10;
 3894: 	my $namechck=unpack("%32S*",$username);
 3895: 	
 3896: 	my $nameseed=numval($username) << 21;
 3897: 	my $domainseed=unpack("%32S*",$domain) << 10;
 3898: 	my $courseseed=unpack("%32S*",$courseid);
 3899: 	
 3900: 	my $num1=$symbchck+$symbseed+$namechck;
 3901: 	my $num2=$nameseed+$domainseed+$courseseed;
 3902: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 3903: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 3904: 	return "$num1,$num2";
 3905:     }
 3906: }
 3907: 
 3908: sub rndseed_CODE_64bit {
 3909:     my ($symb,$courseid,$domain,$username)=@_;
 3910:     {
 3911: 	use integer;
 3912: 	my $symbchck=unpack("%32S*",$symb) << 16;
 3913: 	my $symbseed=numval($symb);
 3914: 	my $CODEseed=numval($ENV{'scantron.CODE'}) << 16;
 3915: 	my $courseseed=unpack("%32S*",$courseid);
 3916: 	my $num1=$symbseed+$CODEseed;
 3917: 	my $num2=$courseseed+$symbchck;
 3918: 	#&Apache::lonxml::debug("$symbseed:$CODEseed|$courseseed:$symbchck");
 3919: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 3920: 	return "$num1,$num2";
 3921:     }
 3922: }
 3923: 
 3924: sub setup_random_from_rndseed {
 3925:     my ($rndseed)=@_;
 3926:     if ($rndseed =~/,/) {
 3927: 	my ($num1,$num2)=split(/,/,$rndseed);
 3928: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 3929:     } else {
 3930: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 3931:     }
 3932: }
 3933: 
 3934: sub ireceipt {
 3935:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
 3936:     my $cuname=unpack("%32C*",$funame);
 3937:     my $cudom=unpack("%32C*",$fudom);
 3938:     my $cucourseid=unpack("%32C*",$fucourseid);
 3939:     my $cusymb=unpack("%32C*",$fusymb);
 3940:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
 3941:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
 3942:            ($cunique%$cuname+
 3943:             $cunique%$cudom+
 3944:             $cusymb%$cuname+
 3945:             $cusymb%$cudom+
 3946:             $cucourseid%$cuname+
 3947:             $cucourseid%$cudom);
 3948: }
 3949: 
 3950: sub receipt {
 3951:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 3952:   return &ireceipt($name,$domain,$courseid,$symb);
 3953: }
 3954: 
 3955: # ------------------------------------------------------------ Serves up a file
 3956: # returns either the contents of the file or a -1
 3957: sub getfile {
 3958:  my $file=shift;
 3959:  if ($file=~/^\/*uploaded\//) { # user file
 3960:     my $ua=new LWP::UserAgent;
 3961:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
 3962:     my $response=$ua->request($request);
 3963:     if ($response->is_success()) {
 3964:        return $response->content;
 3965:     } else { 
 3966:        return -1; 
 3967:     }
 3968:  } else { # normal file from res space
 3969:   &repcopy($file);
 3970:   if (! -e $file ) { return -1; };
 3971:   my $fh=Apache::File->new($file);
 3972:   my $a='';
 3973:   while (<$fh>) { $a .=$_; }
 3974:   return $a;
 3975:  }
 3976: }
 3977: 
 3978: sub filelocation {
 3979:   my ($dir,$file) = @_;
 3980:   my $location;
 3981:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 3982:   if ($file=~m:^/~:) { # is a contruction space reference
 3983:     $location = $file;
 3984:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 3985:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
 3986:     $location=$file;
 3987:   } else {
 3988:     $file=~s/^$perlvar{'lonDocRoot'}//;
 3989:     $file=~s:^/*res::;
 3990:     if ( !( $file =~ m:^/:) ) {
 3991:       $location = $dir. '/'.$file;
 3992:     } else {
 3993:       $location = '/home/httpd/html/res'.$file;
 3994:     }
 3995:   }
 3996:   $location=~s://+:/:g; # remove duplicate /
 3997:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 3998:   return $location;
 3999: }
 4000: 
 4001: sub hreflocation {
 4002:     my ($dir,$file)=@_;
 4003:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
 4004:        my $finalpath=filelocation($dir,$file);
 4005:        $finalpath=~s/^\/home\/httpd\/html//;
 4006:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
 4007:        return $finalpath;
 4008:     } else {
 4009:        return $file;
 4010:     }
 4011: }
 4012: 
 4013: # ------------------------------------------------------------- Declutters URLs
 4014: 
 4015: sub declutter {
 4016:     my $thisfn=shift;
 4017:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 4018:     $thisfn=~s/^\///;
 4019:     $thisfn=~s/^res\///;
 4020:     $thisfn=~s/\?.+$//;
 4021:     return $thisfn;
 4022: }
 4023: 
 4024: # ------------------------------------------------------------- Clutter up URLs
 4025: 
 4026: sub clutter {
 4027:     my $thisfn='/'.&declutter(shift);
 4028:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
 4029:        $thisfn='/res'.$thisfn; 
 4030:     }
 4031:     return $thisfn;
 4032: }
 4033: 
 4034: # -------------------------------------------------------- Escape Special Chars
 4035: 
 4036: sub escape {
 4037:     my $str=shift;
 4038:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 4039:     return $str;
 4040: }
 4041: 
 4042: # ----------------------------------------------------- Un-Escape Special Chars
 4043: 
 4044: sub unescape {
 4045:     my $str=shift;
 4046:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 4047:     return $str;
 4048: }
 4049: 
 4050: # ================================================================ Main Program
 4051: 
 4052: sub goodbye {
 4053:    &logthis("Starting Shut down");
 4054:    &flushcourselogs();
 4055:    &logthis("Shutting down");
 4056:    return DONE;
 4057: }
 4058: 
 4059: BEGIN {
 4060: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 4061:     unless ($readit) {
 4062: {
 4063:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
 4064: 
 4065:     while (my $configline=<$config>) {
 4066:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 4067: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 4068:            chomp($varvalue);
 4069:            $perlvar{$varname}=$varvalue;
 4070:         }
 4071:     }
 4072: }
 4073: {
 4074:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
 4075: 
 4076:     while (my $configline=<$config>) {
 4077:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 4078: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 4079:            chomp($varvalue);
 4080:            $perlvar{$varname}=$varvalue;
 4081:         }
 4082:     }
 4083: }
 4084: 
 4085: # ------------------------------------------------------------ Read domain file
 4086: {
 4087:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
 4088:                             '/domain.tab');
 4089:     %domaindescription = ();
 4090:     %domain_auth_def = ();
 4091:     %domain_auth_arg_def = ();
 4092:     if ($fh) {
 4093:        while (<$fh>) {
 4094:            next if /^\#/;
 4095:            chomp;
 4096:            my ($domain, $domain_description, $def_auth, $def_auth_arg)
 4097:                = split(/:/,$_,4);
 4098:            $domain_auth_def{$domain}=$def_auth;
 4099:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 4100:            $domaindescription{$domain}=$domain_description;
 4101: #          &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 4102: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 4103:        }
 4104:     }
 4105: }
 4106: 
 4107: 
 4108: # ------------------------------------------------------------- Read hosts file
 4109: {
 4110:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
 4111: 
 4112:     while (my $configline=<$config>) {
 4113:        next if ($configline =~ /^(\#|\s*$)/);
 4114:        chomp($configline);
 4115:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
 4116:        if ($id && $domain && $role && $name && $ip) {
 4117: 	 $hostname{$id}=$name;
 4118: 	 $hostdom{$id}=$domain;
 4119: 	 $hostip{$id}=$ip;
 4120: 	 $iphost{$ip}=$id;
 4121: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 4122:        } else {
 4123: 	 if ($configline) {
 4124: 	   &logthis("Skipping hosts.tab line -$configline-");
 4125: 	 }
 4126:        }
 4127:     }
 4128: }
 4129: 
 4130: # ------------------------------------------------------ Read spare server file
 4131: {
 4132:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
 4133: 
 4134:     while (my $configline=<$config>) {
 4135:        chomp($configline);
 4136:        if ($configline) {
 4137:           $spareid{$configline}=1;
 4138:        }
 4139:     }
 4140: }
 4141: # ------------------------------------------------------------ Read permissions
 4142: {
 4143:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
 4144: 
 4145:     while (my $configline=<$config>) {
 4146:        chomp($configline);
 4147:       if ($configline) {
 4148:        my ($role,$perm)=split(/ /,$configline);
 4149:        if ($perm ne '') { $pr{$role}=$perm; }
 4150:       }
 4151:     }
 4152: }
 4153: 
 4154: # -------------------------------------------- Read plain texts for permissions
 4155: {
 4156:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
 4157: 
 4158:     while (my $configline=<$config>) {
 4159:        chomp($configline);
 4160:       if ($configline) {
 4161:        my ($short,$plain)=split(/:/,$configline);
 4162:        if ($plain ne '') { $prp{$short}=$plain; }
 4163:       }
 4164:     }
 4165: }
 4166: 
 4167: # ---------------------------------------------------------- Read package table
 4168: {
 4169:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
 4170: 
 4171:     while (my $configline=<$config>) {
 4172:        chomp($configline);
 4173:        my ($short,$plain)=split(/:/,$configline);
 4174:        my ($pack,$name)=split(/\&/,$short);
 4175:        if ($plain ne '') {
 4176:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
 4177:           $packagetab{$short}=$plain; 
 4178:        }
 4179:     }
 4180: }
 4181: 
 4182: # ------------- set up temporary directory
 4183: {
 4184:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 4185: 
 4186: }
 4187: 
 4188: %metacache=();
 4189: 
 4190: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 4191: $dumpcount=0;
 4192: 
 4193: &logtouch();
 4194: &logthis('<font color=yellow>INFO: Read configuration</font>');
 4195: $readit=1;
 4196: }
 4197: }
 4198: 
 4199: 1;
 4200: __END__
 4201: 
 4202: =pod
 4203: 
 4204: =head1 NAME
 4205: 
 4206: Apache::lonnet - Subroutines to ask questions about things in the network.
 4207: 
 4208: =head1 SYNOPSIS
 4209: 
 4210: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 4211: 
 4212:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 4213: 
 4214: Common parameters:
 4215: 
 4216: =over 4
 4217: 
 4218: =item *
 4219: 
 4220: $uname : an internal username (if $cname expecting a course Id specifically)
 4221: 
 4222: =item *
 4223: 
 4224: $udom : a domain (if $cdom expecting a course's domain specifically)
 4225: 
 4226: =item *
 4227: 
 4228: $symb : a resource instance identifier
 4229: 
 4230: =item *
 4231: 
 4232: $namespace : the name of a .db file that contains the data needed or
 4233: being set.
 4234: 
 4235: =back
 4236: 
 4237: =head1 INTRODUCTION
 4238: 
 4239: This module provides subroutines which interact with the
 4240: lonc/lond (TCP) network layer of LON-CAPA. And Can be used to ask about 
 4241: - classes
 4242: - users 
 4243: - resources
 4244: 
 4245: For many of these objects you can also use this to store data about
 4246: them or modify them in various ways.
 4247: 
 4248: This is part of the LearningOnline Network with CAPA project
 4249: described at http://www.lon-capa.org.
 4250: 
 4251: =head1 RETURN MESSAGES
 4252: 
 4253: =over 4
 4254: 
 4255: =item *
 4256: 
 4257: con_lost : unable to contact remote host
 4258: 
 4259: =item *
 4260: 
 4261: con_delayed : unable to contact remote host, message will be delivered
 4262: when the connection is brought back up
 4263: 
 4264: =item *
 4265: 
 4266: con_failed : unable to contact remote host and unable to save message
 4267: for later delivery
 4268: 
 4269: =item *
 4270: 
 4271: error: : an error a occured, a description of the error follows the :
 4272: 
 4273: =item *
 4274: 
 4275: no_such_host : unable to fund a host associated with the user/domain
 4276: that was requested
 4277: 
 4278: =back
 4279: 
 4280: =head1 PUBLIC SUBROUTINES
 4281: 
 4282: =head2 Session Environment Functions
 4283: 
 4284: =over 4
 4285: 
 4286: =item *
 4287: 
 4288: appenv(%hash) : the value of %hash is written to the user envirnoment
 4289: file, and will be restored for each access this user makes during this
 4290: session, also modifies the %ENV for the current process
 4291: 
 4292: =item *
 4293: 
 4294: delenv($regexp) : removes all items from the session environment file that matches the regular expression in $regexp. The values are also delted from the current processes %ENV.
 4295: 
 4296: =back
 4297: 
 4298: =head2 User Information
 4299: 
 4300: =over 4
 4301: 
 4302: =item *
 4303: 
 4304: queryauthenticate($uname,$udom) : try to determine user's current
 4305: authentication scheme
 4306: 
 4307: =item *
 4308: 
 4309: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
 4310: servers (first use the current one), $upass should be the users password
 4311: 
 4312: =item *
 4313: 
 4314: homeserver($uname,$udom) : find the server which has the user's
 4315: directory and files (there must be only one), this caches the answer,
 4316: and also caches if there is a borken connection.
 4317: 
 4318: =item *
 4319: 
 4320: idget($udom,@ids) : find the usernames behind a list of IDs (IDs are a
 4321: unique resource in a domain, there must be only 1 ID per username, and
 4322: only 1 username per ID in a specific domain) (returns hash:
 4323: id=>name,id=>name)
 4324: 
 4325: =item *
 4326: 
 4327: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
 4328: name=>id,name=>id)
 4329: 
 4330: =item *
 4331: 
 4332: idput($udom,%ids) : store away a list of names and associated IDs
 4333: 
 4334: =item *
 4335: 
 4336: rolesinit($udom,$username,$authhost) : get user privileges
 4337: 
 4338: =item *
 4339: 
 4340: usection($udom,$uname,$cname) : finds the section of student in the
 4341: course $cname, return section name/number or '' for "not in course"
 4342: and '-1' for "no section"
 4343: 
 4344: =item *
 4345: 
 4346: userenvironment($udom,$uname,@what) : gets the values of the keys
 4347: passed in @what from the requested user's environment, returns a hash
 4348: 
 4349: =back
 4350: 
 4351: =head2 User Roles
 4352: 
 4353: =over 4
 4354: 
 4355: =item *
 4356: 
 4357: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 4358: actions
 4359:  F: full access
 4360:  U,I,K: authentication modes (cxx only)
 4361:  '': forbidden
 4362:  1: user needs to choose course
 4363:  2: browse allowed
 4364: 
 4365: =item *
 4366: 
 4367: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 4368: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 4369: and course level
 4370: 
 4371: =item *
 4372: 
 4373: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 4374: explanation of a user role term
 4375: 
 4376: =back
 4377: 
 4378: =head2 User Modification
 4379: 
 4380: =over 4
 4381: 
 4382: =item *
 4383: 
 4384: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 4385: user for the level given by URL.  Optional start and end dates (leave empty
 4386: string or zero for "no date")
 4387: 
 4388: =item *
 4389: 
 4390: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 4391: change a users, password, possible return values are: ok,
 4392: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 4393: refused
 4394: 
 4395: =item *
 4396: 
 4397: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 4398: 
 4399: =item *
 4400: 
 4401: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 4402: modify user
 4403: 
 4404: =item *
 4405: 
 4406: modifystudent
 4407: 
 4408: modify a students enrollment and identification information.
 4409: The course id is resolved based on the current users environment.  
 4410: This means the envoking user must be a course coordinator or otherwise
 4411: associated with a course.
 4412: 
 4413: This call is essentially a wrapper for lonnet::modifyuser and
 4414: lonnet::modify_student_enrollment
 4415: 
 4416: Inputs: 
 4417: 
 4418: =over 4
 4419: 
 4420: =item B<$udom> Students loncapa domain
 4421: 
 4422: =item B<$uname> Students loncapa login name
 4423: 
 4424: =item B<$uid> Students id/student number
 4425: 
 4426: =item B<$umode> Students authentication mode
 4427: 
 4428: =item B<$upass> Students password
 4429: 
 4430: =item B<$first> Students first name
 4431: 
 4432: =item B<$middle> Students middle name
 4433: 
 4434: =item B<$last> Students last name
 4435: 
 4436: =item B<$gene> Students generation
 4437: 
 4438: =item B<$usec> Students section in course
 4439: 
 4440: =item B<$end> Unix time of the roles expiration
 4441: 
 4442: =item B<$start> Unix time of the roles start date
 4443: 
 4444: =item B<$forceid> If defined, allow $uid to be changed
 4445: 
 4446: =item B<$desiredhome> server to use as home server for student
 4447: 
 4448: =back
 4449: 
 4450: =item *
 4451: 
 4452: modify_student_enrollment
 4453: 
 4454: Change a students enrollment status in a class.  The environment variable
 4455: 'role.request.course' must be defined for this function to proceed.
 4456: 
 4457: Inputs:
 4458: 
 4459: =over 4
 4460: 
 4461: =item $udom, students domain
 4462: 
 4463: =item $uname, students name
 4464: 
 4465: =item $uid, students user id
 4466: 
 4467: =item $first, students first name
 4468: 
 4469: =item $middle
 4470: 
 4471: =item $last
 4472: 
 4473: =item $gene
 4474: 
 4475: =item $usec
 4476: 
 4477: =item $end
 4478: 
 4479: =item $start
 4480: 
 4481: =back
 4482: 
 4483: 
 4484: =item *
 4485: 
 4486: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 4487: custom role; give a custom role to a user for the level given by URL.  Specify
 4488: name and domain of role author, and role name
 4489: 
 4490: =item *
 4491: 
 4492: revokerole($udom,$uname,$url,$role) : revoke a role for url
 4493: 
 4494: =item *
 4495: 
 4496: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 4497: 
 4498: =back
 4499: 
 4500: =head2 Course Infomation
 4501: 
 4502: =over 4
 4503: 
 4504: =item *
 4505: 
 4506: coursedescription($courseid) : course description
 4507: 
 4508: =item *
 4509: 
 4510: courseresdata($coursenum,$coursedomain,@which) : request for current
 4511: parameter setting for a specific course, @what should be a list of
 4512: parameters to ask about. This routine caches answers for 5 minutes.
 4513: 
 4514: =back
 4515: 
 4516: =head2 Course Modification
 4517: 
 4518: =over 4
 4519: 
 4520: =item *
 4521: 
 4522: writecoursepref($courseid,%prefs) : write preferences (environment
 4523: database) for a course
 4524: 
 4525: =item *
 4526: 
 4527: createcourse($udom,$description,$url) : make/modify course
 4528: 
 4529: =back
 4530: 
 4531: =head2 Resource Subroutines
 4532: 
 4533: =over 4
 4534: 
 4535: =item *
 4536: 
 4537: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 4538: 
 4539: =item *
 4540: 
 4541: repcopy($filename) : subscribes to the requested file, and attempts to
 4542: replicate from the owning library server, Might return
 4543: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
 4544: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
 4545: resource. Expects the local filesystem pathname
 4546: (/home/httpd/html/res/....)
 4547: 
 4548: =back
 4549: 
 4550: =head2 Resource Information
 4551: 
 4552: =over 4
 4553: 
 4554: =item *
 4555: 
 4556: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 4557: a vairety of different possible values, $varname should be a request
 4558: string, and the other parameters can be used to specify who and what
 4559: one is asking about.
 4560: 
 4561: Possible values for $varname are environment.lastname (or other item
 4562: from the envirnment hash), user.name (or someother aspect about the
 4563: user), resource.0.maxtries (or some other part and parameter of a
 4564: resource)
 4565: 
 4566: =item *
 4567: 
 4568: directcondval($number) : get current value of a condition; reads from a state
 4569: string
 4570: 
 4571: =item *
 4572: 
 4573: condval($condidx) : value of condition index based on state
 4574: 
 4575: =item *
 4576: 
 4577: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 4578: resource's metadata, $what should be either a specific key, or either
 4579: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 4580: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 4581: 
 4582: this function automatically caches all requests
 4583: 
 4584: =item *
 4585: 
 4586: metadata_query($query,$custom,$customshow) : make a metadata query against the
 4587: network of library servers; returns file handle of where SQL and regex results
 4588: will be stored for query
 4589: 
 4590: =item *
 4591: 
 4592: symbread($filename) : return symbolic list entry (filename argument optional);
 4593: returns the data handle
 4594: 
 4595: =item *
 4596: 
 4597: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 4598: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
 4599: failure, user must be in a course, as it assumes the existance of the
 4600: course initi hash, and uses $ENV('request.course.id'}
 4601: 
 4602: 
 4603: =item *
 4604: 
 4605: symbclean($symb) : removes versions numbers from a symb, returns the
 4606: cleaned symb
 4607: 
 4608: =item *
 4609: 
 4610: is_on_map($uri) : checks if the $uri is somewhere on the current
 4611: course map, user must be in a course for it to work.
 4612: 
 4613: =item *
 4614: 
 4615: numval($salt) : return random seed value (addend for rndseed)
 4616: 
 4617: =item *
 4618: 
 4619: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 4620: a random seed, all arguments are optional, if they aren't sent it uses the
 4621: environment to derive them. Note: if symb isn't sent and it can't get one
 4622: from &symbread it will use the current time as its return value
 4623: 
 4624: =item *
 4625: 
 4626: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 4627: unfakeable, receipt
 4628: 
 4629: =item *
 4630: 
 4631: receipt() : API to ireceipt working off of ENV values; given out to users
 4632: 
 4633: =item *
 4634: 
 4635: countacc($url) : count the number of accesses to a given URL
 4636: 
 4637: =item *
 4638: 
 4639: checkout($symb,$tuname,$tudom,$tcrsid) :  creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
 4640: 
 4641: =item *
 4642: 
 4643: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
 4644: 
 4645: =item *
 4646: 
 4647: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 4648: 
 4649: =item *
 4650: 
 4651: devalidate($symb) : devalidate temporary spreadsheet calculations,
 4652: forcing spreadsheet to reevaluate the resource scores next time.
 4653: 
 4654: =back
 4655: 
 4656: =head2 Storing/Retreiving Data
 4657: 
 4658: =over 4
 4659: 
 4660: =item *
 4661: 
 4662: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 4663: for this url; hashref needs to be given and should be a \%hashname; the
 4664: remaining args aren't required and if they aren't passed or are '' they will
 4665: be derived from the ENV
 4666: 
 4667: =item *
 4668: 
 4669: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 4670: uses critical subroutine
 4671: 
 4672: =item *
 4673: 
 4674: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 4675: all args are optional
 4676: 
 4677: =item *
 4678: 
 4679: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 4680: works very similar to store/cstore, but all data is stored in a
 4681: temporary location and can be reset using tmpreset, $storehash should
 4682: be a hash reference, returns nothing on success
 4683: 
 4684: =item *
 4685: 
 4686: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 4687: similar to restore, but all data is stored in a temporary location and
 4688: can be reset using tmpreset. Returns a hash of values on success,
 4689: error string otherwise.
 4690: 
 4691: =item *
 4692: 
 4693: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 4694: deltes all keys for $symb form the temporary storage hash.
 4695: 
 4696: =item *
 4697: 
 4698: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 4699: reference filled in from namesp ($udom and $uname are optional)
 4700: 
 4701: =item *
 4702: 
 4703: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 4704: namesp ($udom and $uname are optional)
 4705: 
 4706: =item *
 4707: 
 4708: dump($namespace,$udom,$uname,$regexp) : 
 4709: dumps the complete (or key matching regexp) namespace into a hash
 4710: ($udom, $uname and $regexp are optional)
 4711: 
 4712: =item *
 4713: 
 4714: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 4715: ($udom and $uname are optional)
 4716: 
 4717: =item *
 4718: 
 4719: cput($namespace,$storehash,$udom,$uname) : critical put
 4720: ($udom and $uname are optional)
 4721: 
 4722: =item *
 4723: 
 4724: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 4725: reference filled in from namesp (encrypts the return communication)
 4726: ($udom and $uname are optional)
 4727: 
 4728: =item *
 4729: 
 4730: log($udom,$name,$home,$message) : write to permanent log for user; use
 4731: critical subroutine
 4732: 
 4733: =back
 4734: 
 4735: =head2 Network Status Functions
 4736: 
 4737: =over 4
 4738: 
 4739: =item *
 4740: 
 4741: dirlist($uri) : return directory list based on URI
 4742: 
 4743: =item *
 4744: 
 4745: spareserver() : find server with least workload from spare.tab
 4746: 
 4747: =back
 4748: 
 4749: =head2 Apache Request
 4750: 
 4751: =over 4
 4752: 
 4753: =item *
 4754: 
 4755: ssi($url,%hash) : server side include, does a complete request cycle on url to
 4756: localhost, posts hash
 4757: 
 4758: =back
 4759: 
 4760: =head2 Data to String to Data
 4761: 
 4762: =over 4
 4763: 
 4764: =item *
 4765: 
 4766: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 4767: and '&' separators, supports elements that are arrayrefs and hashrefs
 4768: 
 4769: =item *
 4770: 
 4771: hashref2str($hashref) : convert a hashref into a string complete with
 4772: escaping and '=' and '&' separators, supports elements that are
 4773: arrayrefs and hashrefs
 4774: 
 4775: =item *
 4776: 
 4777: arrayref2str($arrayref) : convert an arrayref into a string complete
 4778: with escaping and '&' separators, supports elements that are arrayrefs
 4779: and hashrefs
 4780: 
 4781: =item *
 4782: 
 4783: str2hash($string) : convert string to hash using unescaping and
 4784: splitting on '=' and '&', supports elements that are arrayrefs and
 4785: hashrefs
 4786: 
 4787: =item *
 4788: 
 4789: str2array($string) : convert string to hash using unescaping and
 4790: splitting on '&', supports elements that are arrayrefs and hashrefs
 4791: 
 4792: =back
 4793: 
 4794: =head2 Logging Routines
 4795: 
 4796: =over 4
 4797: 
 4798: These routines allow one to make log messages in the lonnet.log and
 4799: lonnet.perm logfiles.
 4800: 
 4801: =item *
 4802: 
 4803: logtouch() : make sure the logfile, lonnet.log, exists
 4804: 
 4805: =item *
 4806: 
 4807: logthis() : append message to the normal lonnet.log file, it gets
 4808: preiodically rolled over and deleted.
 4809: 
 4810: =item *
 4811: 
 4812: logperm() : append a permanent message to lonnet.perm.log, this log
 4813: file never gets deleted by any automated portion of the system, only
 4814: messages of critical importance should go in here.
 4815: 
 4816: =back
 4817: 
 4818: =head2 General File Helper Routines
 4819: 
 4820: =over 4
 4821: 
 4822: =item *
 4823: 
 4824: getfile($file) : returns the entire contents of a file or -1; it
 4825: properly subscribes to and replicates the file if neccessary.
 4826: 
 4827: =item *
 4828: 
 4829: filelocation($dir,$file) : returns file system location of a file
 4830: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 4831: directory that relative $file lookups are to looked in ($dir of /a/dir
 4832: and a file of ../bob will become /a/bob)
 4833: 
 4834: =item *
 4835: 
 4836: hreflocation($dir,$file) : returns file system location or a URL; same as
 4837: filelocation except for hrefs
 4838: 
 4839: =item *
 4840: 
 4841: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 4842: 
 4843: =back
 4844: 
 4845: =head2 HTTP Helper Routines
 4846: 
 4847: =over 4
 4848: 
 4849: =item *
 4850: 
 4851: escape() : unpack non-word characters into CGI-compatible hex codes
 4852: 
 4853: =item *
 4854: 
 4855: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 4856: 
 4857: =back
 4858: 
 4859: =head1 PRIVATE SUBROUTINES
 4860: 
 4861: =head2 Underlying communication routines (Shouldn't call)
 4862: 
 4863: =over 4
 4864: 
 4865: =item *
 4866: 
 4867: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 4868: 
 4869: =item *
 4870: 
 4871: reply() : uses subreply to send a message to remote machine, logs all failures
 4872: 
 4873: =item *
 4874: 
 4875: critical() : passes a critical message to another server; if cannot
 4876: get through then place message in connection buffer directory and
 4877: returns con_delayed, if incapable of saving message, returns
 4878: con_failed
 4879: 
 4880: =item *
 4881: 
 4882: reconlonc() : tries to reconnect lonc client processes.
 4883: 
 4884: =back
 4885: 
 4886: =head2 Resource Access Logging
 4887: 
 4888: =over 4
 4889: 
 4890: =item *
 4891: 
 4892: flushcourselogs() : flush (save) buffer logs and access logs
 4893: 
 4894: =item *
 4895: 
 4896: courselog($what) : save message for course in hash
 4897: 
 4898: =item *
 4899: 
 4900: courseacclog($what) : save message for course using &courselog().  Perform
 4901: special processing for specific resource types (problems, exams, quizzes, etc).
 4902: 
 4903: =item *
 4904: 
 4905: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 4906: as a PerlChildExitHandler
 4907: 
 4908: =back
 4909: 
 4910: =head2 Other
 4911: 
 4912: =over 4
 4913: 
 4914: =item *
 4915: 
 4916: symblist($mapname,%newhash) : update symbolic storage links
 4917: 
 4918: =back
 4919: 
 4920: =cut

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