File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.438: download - view: text, annotated - select for diffs
Fri Oct 31 22:20:37 2003 UTC (20 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Trying to fix versioned maps. Not quite there yet.

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

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