File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.296: download - view: text, annotated - select for diffs
Thu Oct 10 14:34:05 2002 UTC (21 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
This was whining at startup, claiming that the reference to "dump" was
ambiguous, and thus linked to Core::dump.

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

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