File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.262: download - view: text, annotated - select for diffs
Wed Aug 7 20:40:57 2002 UTC (21 years, 11 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Fixes bug 446.  A role of librarian should allow full browsing access to
resources (given copyright caveats).

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

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