File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.424: download - view: text, annotated - select for diffs
Thu Sep 25 20:25:04 2003 UTC (20 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added &convert_dump_to_currentdump() as this code is now needed in
loncoursedata.pm as well as lonnet::currentdump.

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

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