File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.294: download - view: text, annotated - select for diffs
Wed Oct 9 17:24:06 2002 UTC (21 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Modifystudent will now record $end:$start:$uid:$sec:$fullname in the
'classlist' db.

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

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