File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.364: download - view: text, annotated - select for diffs
Tue Apr 22 21:00:42 2003 UTC (21 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Continued work on key access to courses.

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

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