File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.441: download - view: text, annotated - select for diffs
Tue Nov 4 18:44:17 2003 UTC (20 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#984, I cen't remeber a single time this error message was useful, and it mainly serves to pollute lonnet.log

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

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