File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.196: download - view: text, annotated - select for diffs
Fri Jan 4 15:38:02 2002 UTC (22 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Force id to force override of IDs and disable ID saveguard.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.196 2002/01/04 15:38:02 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
   29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
   30: # 11/8,11/16,11/18,11/22,11/23,12/22,
   31: # 01/06,01/13,02/24,02/28,02/29,
   32: # 03/01,03/02,03/06,03/07,03/13,
   33: # 04/05,05/29,05/31,06/01,
   34: # 06/05,06/26 Gerd Kortemeyer
   35: # 06/26 Ben Tyszka
   36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
   37: # 08/14 Ben Tyszka
   38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
   39: # 10/04 Gerd Kortemeyer
   40: # 10/04 Guy Albertelli
   41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
   42: # 10/30,10/31,
   43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
   44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
   45: # 05/01/01 Guy Albertelli
   46: # 05/01,06/01,09/01 Gerd Kortemeyer
   47: # 09/01 Guy Albertelli
   48: # 09/01,10/01,11/01 Gerd Kortemeyer
   49: # YEAR=2001
   50: # 02/27/01 Scott Harrison
   51: # 3/2 Gerd Kortemeyer
   52: # 3/15,3/19 Scott Harrison
   53: # 3/19,3/20 Gerd Kortemeyer
   54: # 3/22,3/27,4/2,4/16,4/17 Scott Harrison
   55: # 5/26,5/28 Gerd Kortemeyer
   56: # 5/30 H. K. Ng
   57: # 6/1 Gerd Kortemeyer
   58: # July Guy Albertelli
   59: # 8/4,8/7,8/8,8/9,8/11,8/16,8/17,8/18,8/20,8/23,9/20,9/21,9/26,
   60: # 10/2 Gerd Kortemeyer
   61: # 10/5,10/10,11/13,11/15 Scott Harrison
   62: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
   63: # 12/5 Matthew Hall
   64: # 12/5 Guy Albertelli
   65: # 12/6,12/7,12/12 Gerd Kortemeyer
   66: # 12/18 Scott Harrison
   67: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
   68: # YEAR=2002
   69: # 1/4 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 %hostip %spareid %hostdom 
   81:    %libserv %pr %prp %metacache %packagetab 
   82:    %courselogs %accesshash $processmarker $dumpcount 
   83:    %coursedombuf %coursehombuf);
   84: use IO::Socket;
   85: use GDBM_File;
   86: use Apache::Constants qw(:common :http);
   87: use HTML::TokeParser;
   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:     my $answer=subreply($cmd,$server);
  141:     if ($answer eq 'con_lost') { $answer=subreply($cmd,$server); }
  142:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  143:        &logthis("<font color=blue>WARNING:".
  144:                 " $cmd to $server returned $answer</font>");
  145:     }
  146:     return $answer;
  147: }
  148: 
  149: # ----------------------------------------------------------- Send USR1 to lonc
  150: 
  151: sub reconlonc {
  152:     my $peerfile=shift;
  153:     &logthis("Trying to reconnect for $peerfile");
  154:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  155:     if (my $fh=Apache::File->new("$loncfile")) {
  156: 	my $loncpid=<$fh>;
  157:         chomp($loncpid);
  158:         if (kill 0 => $loncpid) {
  159: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  160:             kill USR1 => $loncpid;
  161:             sleep 1;
  162:             if (-e "$peerfile") { return; }
  163:             &logthis("$peerfile still not there, give it another try");
  164:             sleep 5;
  165:             if (-e "$peerfile") { return; }
  166:             &logthis(
  167:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  168:         } else {
  169: 	    &logthis(
  170:                "<font color=blue>WARNING:".
  171:                " lonc at pid $loncpid not responding, giving up</font>");
  172:         }
  173:     } else {
  174:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
  175:     }
  176: }
  177: 
  178: # ------------------------------------------------------ Critical communication
  179: 
  180: sub critical {
  181:     my ($cmd,$server)=@_;
  182:     unless ($hostname{$server}) {
  183:         &logthis("<font color=blue>WARNING:".
  184:                " Critical message to unknown server ($server)</font>");
  185:         return 'no_such_host';
  186:     }
  187:     my $answer=reply($cmd,$server);
  188:     if ($answer eq 'con_lost') {
  189:         my $pingreply=reply('ping',$server);
  190: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  191:         my $pongreply=reply('pong',$server);
  192:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
  193:         $answer=reply($cmd,$server);
  194:         if ($answer eq 'con_lost') {
  195:             my $now=time;
  196:             my $middlename=$cmd;
  197:             $middlename=substr($middlename,0,16);
  198:             $middlename=~s/\W//g;
  199:             my $dfilename=
  200:              "$perlvar{'lonSockDir'}/delayed/$now.$middlename.$server";
  201:             {
  202:              my $dfh;
  203:              if ($dfh=Apache::File->new(">$dfilename")) {
  204:                 print $dfh "$cmd\n";
  205: 	     }
  206:             }
  207:             sleep 2;
  208:             my $wcmd='';
  209:             {
  210: 	     my $dfh;
  211:              if ($dfh=Apache::File->new("$dfilename")) {
  212:                 $wcmd=<$dfh>;
  213: 	     }
  214:             }
  215:             chomp($wcmd);
  216:             if ($wcmd eq $cmd) {
  217: 		&logthis("<font color=blue>WARNING: ".
  218:                          "Connection buffer $dfilename: $cmd</font>");
  219:                 &logperm("D:$server:$cmd");
  220: 	        return 'con_delayed';
  221:             } else {
  222:                 &logthis("<font color=red>CRITICAL:"
  223:                         ." Critical connection failed: $server $cmd</font>");
  224:                 &logperm("F:$server:$cmd");
  225:                 return 'con_failed';
  226:             }
  227:         }
  228:     }
  229:     return $answer;
  230: }
  231: 
  232: # ---------------------------------------------------------- Append Environment
  233: 
  234: sub appenv {
  235:     my %newenv=@_;
  236:     foreach (keys %newenv) {
  237: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
  238:             &logthis("<font color=blue>WARNING: ".
  239:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
  240:                 .'</font>');
  241: 	    delete($newenv{$_});
  242:         } else {
  243:             $ENV{$_}=$newenv{$_};
  244:         }
  245:     }
  246: 
  247:     my $lockfh;
  248:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
  249:        return 'error: '.$!;
  250:     }
  251:     unless (flock($lockfh,LOCK_EX)) {
  252:          &logthis("<font color=blue>WARNING: ".
  253:                   'Could not obtain exclusive lock in appenv: '.$!);
  254:          $lockfh->close();
  255:          return 'error: '.$!;
  256:     }
  257: 
  258:     my @oldenv;
  259:     {
  260:      my $fh;
  261:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  262: 	return 'error: '.$!;
  263:      }
  264:      @oldenv=<$fh>;
  265:      $fh->close();
  266:     }
  267:     for (my $i=0; $i<=$#oldenv; $i++) {
  268:         chomp($oldenv[$i]);
  269:         if ($oldenv[$i] ne '') {
  270:            my ($name,$value)=split(/=/,$oldenv[$i]);
  271:            unless (defined($newenv{$name})) {
  272: 	      $newenv{$name}=$value;
  273: 	   }
  274:         }
  275:     }
  276:     {
  277:      my $fh;
  278:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  279: 	return 'error';
  280:      }
  281:      my $newname;
  282:      foreach $newname (keys %newenv) {
  283: 	 print $fh "$newname=$newenv{$newname}\n";
  284:      }
  285:      $fh->close();
  286:     }
  287: 
  288:     $lockfh->close();
  289:     return 'ok';
  290: }
  291: # ----------------------------------------------------- Delete from Environment
  292: 
  293: sub delenv {
  294:     my $delthis=shift;
  295:     my %newenv=();
  296:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  297:         &logthis("<font color=blue>WARNING: ".
  298:                 "Attempt to delete from environment ".$delthis);
  299:         return 'error';
  300:     }
  301:     my @oldenv;
  302:     {
  303:      my $fh;
  304:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  305: 	return 'error';
  306:      }
  307:      unless (flock($fh,LOCK_SH)) {
  308:          &logthis("<font color=blue>WARNING: ".
  309:                   'Could not obtain shared lock in delenv: '.$!);
  310:          $fh->close();
  311:          return 'error: '.$!;
  312:      }
  313:      @oldenv=<$fh>;
  314:      $fh->close();
  315:     }
  316:     {
  317:      my $fh;
  318:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  319: 	return 'error';
  320:      }
  321:      unless (flock($fh,LOCK_EX)) {
  322:          &logthis("<font color=blue>WARNING: ".
  323:                   'Could not obtain exclusive lock in delenv: '.$!);
  324:          $fh->close();
  325:          return 'error: '.$!;
  326:      }
  327:      foreach (@oldenv) {
  328: 	 unless ($_=~/^$delthis/) { print $fh $_; }
  329:      }
  330:      $fh->close();
  331:     }
  332:     return 'ok';
  333: }
  334: 
  335: # ------------------------------ Find server with least workload from spare.tab
  336: 
  337: sub spareserver {
  338:     my $tryserver;
  339:     my $spareserver='';
  340:     my $lowestserver=100;
  341:     foreach $tryserver (keys %spareid) {
  342:        my $answer=reply('load',$tryserver);
  343:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  344: 	   $spareserver="http://$hostname{$tryserver}";
  345:            $lowestserver=$answer;
  346:        }
  347:     }    
  348:     return $spareserver;
  349: }
  350: 
  351: # ----------------------- Try to determine user's current authentication scheme
  352: 
  353: sub queryauthenticate {
  354:     my ($uname,$udom)=@_;
  355:     if (($perlvar{'lonRole'} eq 'library') && 
  356:         ($udom eq $perlvar{'lonDefDomain'})) {
  357: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
  358: 			 $perlvar{'lonHostID'});
  359: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  360: 	    if (length($answer)) {
  361: 		return $answer;
  362: 	    }
  363: 	    else {
  364: 	&logthis("User $uname at $udom lacks an authentication mechanism");
  365: 		return 'no_host';
  366: 	    }
  367: 	}
  368:     }
  369: 
  370:     my $tryserver;
  371:     foreach $tryserver (keys %libserv) {
  372: 	if ($hostdom{$tryserver} eq $udom) {
  373:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
  374: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  375: 	       if (length($answer)) {
  376: 		   return $answer;
  377: 	       }
  378: 	       else {
  379: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
  380: 		   return 'no_host';
  381: 	       }
  382: 	   }
  383:        }
  384:     }
  385:     &logthis("User $uname at $udom lacks an authentication mechanism");    
  386:     return 'no_host';
  387: }
  388: 
  389: # --------- Try to authenticate user from domain's lib servers (first this one)
  390: 
  391: sub authenticate {
  392:     my ($uname,$upass,$udom)=@_;
  393:     $upass=escape($upass);
  394:     if (($perlvar{'lonRole'} eq 'library') && 
  395:         ($udom eq $perlvar{'lonDefDomain'})) {
  396:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
  397:         if ($answer =~ /authorized/) {
  398:               if ($answer eq 'authorized') {
  399:                  &logthis("User $uname at $udom authorized by local server"); 
  400:                  return $perlvar{'lonHostID'}; 
  401:               }
  402:               if ($answer eq 'non_authorized') {
  403:                  &logthis("User $uname at $udom rejected by local server"); 
  404:                  return 'no_host'; 
  405:               }
  406: 	}
  407:     }
  408: 
  409:     my $tryserver;
  410:     foreach $tryserver (keys %libserv) {
  411: 	if ($hostdom{$tryserver} eq $udom) {
  412:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
  413:            if ($answer =~ /authorized/) {
  414:               if ($answer eq 'authorized') {
  415:                  &logthis("User $uname at $udom authorized by $tryserver"); 
  416:                  return $tryserver; 
  417:               }
  418:               if ($answer eq 'non_authorized') {
  419:                  &logthis("User $uname at $udom rejected by $tryserver");
  420:                  return 'no_host';
  421:               } 
  422: 	   }
  423:        }
  424:     }
  425:     &logthis("User $uname at $udom could not be authenticated");    
  426:     return 'no_host';
  427: }
  428: 
  429: # ---------------------- Find the homebase for a user from domain's lib servers
  430: 
  431: sub homeserver {
  432:     my ($uname,$udom)=@_;
  433: 
  434:     my $index="$uname:$udom";
  435:     if ($homecache{$index}) { return "$homecache{$index}"; }
  436: 
  437:     my $tryserver;
  438:     foreach $tryserver (keys %libserv) {
  439: 	if ($hostdom{$tryserver} eq $udom) {
  440:            my $answer=reply("home:$udom:$uname",$tryserver);
  441:            if ($answer eq 'found') { 
  442: 	      $homecache{$index}=$tryserver;
  443:               return $tryserver; 
  444: 	   }
  445:        }
  446:     }    
  447:     return 'no_host';
  448: }
  449: 
  450: # ------------------------------------- Find the usernames behind a list of IDs
  451: 
  452: sub idget {
  453:     my ($udom,@ids)=@_;
  454:     my %returnhash=();
  455:     
  456:     my $tryserver;
  457:     foreach $tryserver (keys %libserv) {
  458:        if ($hostdom{$tryserver} eq $udom) {
  459: 	  my $idlist=join('&',@ids);
  460:           $idlist=~tr/A-Z/a-z/; 
  461: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  462:           my @answer=();
  463:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  464: 	      @answer=split(/\&/,$reply);
  465:           }                    ;
  466:           my $i;
  467:           for ($i=0;$i<=$#ids;$i++) {
  468:               if ($answer[$i]) {
  469: 		  $returnhash{$ids[$i]}=$answer[$i];
  470:               } 
  471:           }
  472:        }
  473:     }    
  474:     return %returnhash;
  475: }
  476: 
  477: # ------------------------------------- Find the IDs behind a list of usernames
  478: 
  479: sub idrget {
  480:     my ($udom,@unames)=@_;
  481:     my %returnhash=();
  482:     foreach (@unames) {
  483:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  484:     }
  485:     return %returnhash;
  486: }
  487: 
  488: # ------------------------------- Store away a list of names and associated IDs
  489: 
  490: sub idput {
  491:     my ($udom,%ids)=@_;
  492:     my %servers=();
  493:     foreach (keys %ids) {
  494:         my $uhom=&homeserver($_,$udom);
  495:         if ($uhom ne 'no_host') {
  496:             my $id=&escape($ids{$_});
  497:             $id=~tr/A-Z/a-z/;
  498:             my $unam=&escape($_);
  499: 	    if ($servers{$uhom}) {
  500: 		$servers{$uhom}.='&'.$id.'='.$unam;
  501:             } else {
  502:                 $servers{$uhom}=$id.'='.$unam;
  503:             }
  504:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
  505:         }
  506:     }
  507:     foreach (keys %servers) {
  508:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  509:     }
  510: }
  511: 
  512: # ------------------------------------- Find the section of student in a course
  513: 
  514: sub usection {
  515:     my ($udom,$unam,$courseid)=@_;
  516:     $courseid=~s/\_/\//g;
  517:     $courseid=~s/^(\w)/\/$1/;
  518:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  519:                         &homeserver($unam,$udom)))) {
  520:         my ($key,$value)=split(/\=/,$_);
  521:         $key=&unescape($key);
  522:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
  523:             my $section=$1;
  524:             if ($key eq $courseid.'_st') { $section=''; }
  525: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  526:             my $now=time;
  527:             my $notactive=0;
  528:             if ($start) {
  529: 		if ($now<$start) { $notactive=1; }
  530:             }
  531:             if ($end) {
  532:                 if ($now>$end) { $notactive=1; }
  533:             } 
  534:             unless ($notactive) { return $section; }
  535:         }
  536:     }
  537:     return '-1';
  538: }
  539: 
  540: # ------------------------------------- Read an entry from a user's environment
  541: 
  542: sub userenvironment {
  543:     my ($udom,$unam,@what)=@_;
  544:     my %returnhash=();
  545:     my @answer=split(/\&/,
  546:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  547:                       &homeserver($unam,$udom)));
  548:     my $i;
  549:     for ($i=0;$i<=$#what;$i++) {
  550: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  551:     }
  552:     return %returnhash;
  553: }
  554: 
  555: # ----------------------------- Subscribe to a resource, return URL if possible
  556: 
  557: sub subscribe {
  558:     my $fname=shift;
  559:     my $author=$fname;
  560:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  561:     my ($udom,$uname)=split(/\//,$author);
  562:     my $home=homeserver($uname,$udom);
  563:     if (($home eq 'no_host') || ($home eq $perlvar{'lonHostID'})) { 
  564:         return 'not_found'; 
  565:     }
  566:     my $answer=reply("sub:$fname",$home);
  567:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  568: 	$answer.=' by '.$home;
  569:     }
  570:     return $answer;
  571: }
  572:     
  573: # -------------------------------------------------------------- Replicate file
  574: 
  575: sub repcopy {
  576:     my $filename=shift;
  577:     $filename=~s/\/+/\//g;
  578:     my $transname="$filename.in.transfer";
  579:     if ((-e $filename) || (-e $transname)) { return OK; }
  580:     my $remoteurl=subscribe($filename);
  581:     if ($remoteurl =~ /^con_lost by/) {
  582: 	   &logthis("Subscribe returned $remoteurl: $filename");
  583:            return HTTP_SERVICE_UNAVAILABLE;
  584:     } elsif ($remoteurl eq 'not_found') {
  585: 	   &logthis("Subscribe returned not_found: $filename");
  586: 	   return HTTP_NOT_FOUND;
  587:     } elsif ($remoteurl =~ /^rejected by/) {
  588: 	   &logthis("Subscribe returned $remoteurl: $filename");
  589:            return FORBIDDEN;
  590:     } elsif ($remoteurl eq 'directory') {
  591:            return OK;
  592:     } else {
  593:            my @parts=split(/\//,$filename);
  594:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  595:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
  596:                &logthis("Malconfiguration for replication: $filename");
  597: 	       return HTTP_BAD_REQUEST;
  598:            }
  599:            my $count;
  600:            for ($count=5;$count<$#parts;$count++) {
  601:                $path.="/$parts[$count]";
  602:                if ((-e $path)!=1) {
  603: 		   mkdir($path,0777);
  604:                }
  605:            }
  606:            my $ua=new LWP::UserAgent;
  607:            my $request=new HTTP::Request('GET',"$remoteurl");
  608:            my $response=$ua->request($request,$transname);
  609:            if ($response->is_error()) {
  610: 	       unlink($transname);
  611:                my $message=$response->status_line;
  612:                &logthis("<font color=blue>WARNING:"
  613:                        ." LWP get: $message: $filename</font>");
  614:                return HTTP_SERVICE_UNAVAILABLE;
  615:            } else {
  616: 	       if ($remoteurl!~/\.meta$/) {
  617:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
  618:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
  619:                   if ($mresponse->is_error()) {
  620: 		      unlink($filename.'.meta');
  621:                       &logthis(
  622:                      "<font color=yellow>INFO: No metadata: $filename</font>");
  623:                   }
  624: 	       }
  625:                rename($transname,$filename);
  626:                return OK;
  627:            }
  628:     }
  629: }
  630: 
  631: # --------------------------------------------------------- Server Side Include
  632: 
  633: sub ssi {
  634: 
  635:     my ($fn,%form)=@_;
  636: 
  637:     my $ua=new LWP::UserAgent;
  638:     
  639:     my $request;
  640:     
  641:     if (%form) {
  642:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
  643:       $request->content(join '&', map { "$_=$form{$_}" } keys %form);
  644:     } else {
  645:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
  646:     }
  647: 
  648:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
  649:     my $response=$ua->request($request);
  650: 
  651:     return $response->content;
  652: }
  653: 
  654: # ------------------------------------------------------------------------- Log
  655: 
  656: sub log {
  657:     my ($dom,$nam,$hom,$what)=@_;
  658:     return critical("log:$dom:$nam:$what",$hom);
  659: }
  660: 
  661: # ------------------------------------------------------------------ Course Log
  662: 
  663: sub flushcourselogs {
  664:     &logthis('Flushing course log buffers');
  665:     foreach (keys %courselogs) {
  666:         my $crsid=$_;
  667:         if (&reply('log:'.$coursedombuf{$crsid}.':'.
  668: 		          &escape($courselogs{$crsid}),
  669: 		          $coursehombuf{$crsid}) eq 'ok') {
  670: 	    delete $courselogs{$crsid};
  671:         } else {
  672:             &logthis('Failed to flush log buffer for '.$crsid);
  673:             if (length($courselogs{$crsid})>40000) {
  674:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
  675:                         " exceeded maximum size, deleting.</font>");
  676:                delete $courselogs{$crsid};
  677:             }
  678:         }        
  679:     }
  680:     &logthis('Flushing access logs');
  681:     foreach (keys %accesshash) {
  682:         my $entry=$_;
  683:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
  684:         my %temphash=($entry => $accesshash{$entry});
  685:         if (&Apache::lonnet::put('resevaldata',\%temphash,$1,$2) eq 'ok') {
  686: 	    delete $accesshash{$entry};
  687:         }
  688:     }
  689:     $dumpcount++;
  690: }
  691: 
  692: sub courselog {
  693:     my $what=shift;
  694:     $what=time.':'.$what;
  695:     unless ($ENV{'request.course.id'}) { return ''; }
  696:     $coursedombuf{$ENV{'request.course.id'}}=
  697:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
  698:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
  699:     $coursehombuf{$ENV{'request.course.id'}}=
  700:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
  701:     if (defined $courselogs{$ENV{'request.course.id'}}) {
  702: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
  703:     } else {
  704: 	$courselogs{$ENV{'request.course.id'}}.=$what;
  705:     }
  706:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
  707: 	&flushcourselogs();
  708:     }
  709: }
  710: 
  711: sub courseacclog {
  712:     my $fnsymb=shift;
  713:     unless ($ENV{'request.course.id'}) { return ''; }
  714:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
  715:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
  716:         $what.=':POST';
  717: 	foreach (keys %ENV) {
  718:             if ($_=~/^form\.(.*)/) {
  719: 		$what.=':'.$1.'='.$ENV{$_};
  720:             }
  721:         }
  722:     }
  723:     &courselog($what);
  724: }
  725: 
  726: sub countacc {
  727:     my $url=&declutter(shift);
  728:     unless ($ENV{'request.course.id'}) { return ''; }
  729:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
  730:     my $key=$processmarker.'_'.$dumpcount.'___'.$url.'___count';
  731:     if (defined($accesshash{$key})) {
  732: 	$accesshash{$key}++;
  733:     } else {
  734:         $accesshash{$key}=1;
  735:     }
  736: }
  737:     
  738: # ----------------------------------------------------------- Check out an item
  739: 
  740: sub checkout {
  741:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  742:     my $now=time;
  743:     my $lonhost=$perlvar{'lonHostID'};
  744:     my $infostr=&escape(
  745:                  $tuname.'&'.
  746:                  $tudom.'&'.
  747:                  $tcrsid.'&'.
  748:                  $symb.'&'.
  749: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
  750:     my $token=&reply('tmpput:'.$infostr,$lonhost);
  751:     if ($token=~/^error\:/) { 
  752:         &logthis("<font color=blue>WARNING: ".
  753:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
  754:                  "</font>");
  755:         return ''; 
  756:     }
  757: 
  758:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
  759:     $token=~tr/a-z/A-Z/;
  760: 
  761:     my %infohash=('resource.0.outtoken' => $token,
  762:                   'resource.0.checkouttime' => $now,
  763:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
  764: 
  765:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
  766:        return '';
  767:     } else {
  768:         &logthis("<font color=blue>WARNING: ".
  769:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
  770:                  "</font>");
  771:     }    
  772: 
  773:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
  774:                          &escape('Checkout '.$infostr.' - '.
  775:                                                  $token)) ne 'ok') {
  776: 	return '';
  777:     } else {
  778:         &logthis("<font color=blue>WARNING: ".
  779:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
  780:                  "</font>");
  781:     }
  782:     return $token;
  783: }
  784: 
  785: # ------------------------------------------------------------ Check in an item
  786: 
  787: sub checkin {
  788:     my $token=shift;
  789:     my $now=time;
  790:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
  791:     $lonhost=~tr/A-Z/a-z/;
  792:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
  793:     $dtoken=~s/\W/\_/g;
  794:     my ($tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
  795:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
  796: 
  797:     unless (($tuname) && ($tudom)) {
  798:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
  799:         return '';
  800:     }
  801:     
  802:     unless (&allowed('mgr',$tcrsid)) {
  803:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
  804:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
  805:         return '';
  806:     }
  807: 
  808:     my %infohash=('resource.0.intoken' => $token,
  809:                   'resource.0.checkintime' => $now,
  810:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
  811: 
  812:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
  813:        return '';
  814:     }    
  815: 
  816:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
  817:                          &escape('Checkin - '.$token)) ne 'ok') {
  818: 	return '';
  819:     }
  820: 
  821:     return ($symb,$tuname,$tudom,$tcrsid);    
  822: }
  823: 
  824: # --------------------------------------------- Set Expire Date for Spreadsheet
  825: 
  826: sub expirespread {
  827:     my ($uname,$udom,$stype,$usymb)=@_;
  828:     my $cid=$ENV{'request.course.id'}; 
  829:     if ($cid) {
  830:        my $now=time;
  831:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
  832:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
  833:                             $ENV{'course.'.$cid.'.num'}.
  834: 	        	    ':nohist_expirationdates:'.
  835:                             &escape($key).'='.$now,
  836:                             $ENV{'course.'.$cid.'.home'})
  837:     }
  838:     return 'ok';
  839: }
  840: 
  841: # ----------------------------------------------------- Devalidate Spreadsheets
  842: 
  843: sub devalidate {
  844:     my $symb=shift;
  845:     my $cid=$ENV{'request.course.id'}; 
  846:     if ($cid) {
  847: 	my $key=$ENV{'user.name'}.':'.$ENV{'user.domain'}.':';
  848:         my $status=
  849: 	    &del('nohist_calculatedsheet',
  850: 		 [$key.'studentcalc'],
  851: 		 $ENV{'course.'.$cid.'.domain'},
  852: 		 $ENV{'course.'.$cid.'.num'})
  853: 		.' '.
  854: 	    &del('nohist_calculatedsheets_'.$cid,
  855: 		 [$key.'assesscalc:'.$symb]);
  856:         unless ($status eq 'ok ok') {
  857:            &logthis('Could not devalidate spreadsheet '.
  858:                     $ENV{'user.name'}.' at '.$ENV{'user.domain'}.' for '.
  859: 		    $symb.': '.$status);
  860:         }
  861:     }
  862: }
  863: 
  864: sub hash2str {
  865:   my (%hash)=@_;
  866:   my $result='';
  867:   foreach (keys %hash) { $result.=escape($_).'='.escape($hash{$_}).'&'; }
  868:   $result=~s/\&$//;
  869:   return $result;
  870: }
  871: 
  872: sub str2hash {
  873:   my ($string) = @_;
  874:   my %returnhash;
  875:   foreach (split(/\&/,$string)) {
  876:     my ($name,$value)=split(/\=/,$_);
  877:     $returnhash{&unescape($name)}=&unescape($value);
  878:   }
  879:   return %returnhash;
  880: }
  881: 
  882: # -------------------------------------------------------------------Temp Store
  883: 
  884: sub tmpreset {
  885:   my ($symb,$namespace,$domain,$stuname) = @_;
  886:   if (!$symb) {
  887:     $symb=&symbread();
  888:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
  889:   }
  890:   $symb=escape($symb);
  891: 
  892:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
  893:   $namespace=~s/\//\_/g;
  894:   $namespace=~s/\W//g;
  895: 
  896:   #FIXME needs to do something for /pub resources
  897:   if (!$domain) { $domain=$ENV{'user.domain'}; }
  898:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
  899:   my $path=$perlvar{'lonDaemons'}.'/tmp';
  900:   my %hash;
  901:   if (tie(%hash,'GDBM_File',
  902: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
  903: 	  &GDBM_WRCREAT,0640)) {
  904:     foreach my $key (keys %hash) {
  905:       if ($key=~ /:$symb/) {
  906: 	delete($hash{$key});
  907:       }
  908:     }
  909:   }
  910: }
  911: 
  912: sub tmpstore {
  913:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
  914: 
  915:   if (!$symb) {
  916:     $symb=&symbread();
  917:     if (!$symb) { $symb= $ENV{'request.url'}; }
  918:   }
  919:   $symb=escape($symb);
  920: 
  921:   if (!$namespace) {
  922:     # I don't think we would ever want to store this for a course.
  923:     # it seems this will only be used if we don't have a course.
  924:     #$namespace=$ENV{'request.course.id'};
  925:     #if (!$namespace) {
  926:       $namespace=$ENV{'request.state'};
  927:     #}
  928:   }
  929:   $namespace=~s/\//\_/g;
  930:   $namespace=~s/\W//g;
  931: #FIXME needs to do something for /pub resources
  932:   if (!$domain) { $domain=$ENV{'user.domain'}; }
  933:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
  934:   my $now=time;
  935:   my %hash;
  936:   my $path=$perlvar{'lonDaemons'}.'/tmp';
  937:   if (tie(%hash,'GDBM_File',
  938: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
  939: 	  &GDBM_WRCREAT,0640)) {
  940:     $hash{"version:$symb"}++;
  941:     my $version=$hash{"version:$symb"};
  942:     my $allkeys=''; 
  943:     foreach my $key (keys(%$storehash)) {
  944:       $allkeys.=$key.':';
  945:       $hash{"$version:$symb:$key"}=$$storehash{$key};
  946:     }
  947:     $hash{"$version:$symb:timestamp"}=$now;
  948:     $allkeys.='timestamp';
  949:     $hash{"$version:keys:$symb"}=$allkeys;
  950:     if (untie(%hash)) {
  951:       return 'ok';
  952:     } else {
  953:       return "error:$!";
  954:     }
  955:   } else {
  956:     return "error:$!";
  957:   }
  958: }
  959: 
  960: # -----------------------------------------------------------------Temp Restore
  961: 
  962: sub tmprestore {
  963:   my ($symb,$namespace,$domain,$stuname) = @_;
  964: 
  965:   if (!$symb) {
  966:     $symb=&symbread();
  967:     if (!$symb) { $symb= $ENV{'request.url'}; }
  968:   }
  969:   $symb=escape($symb);
  970: 
  971:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
  972:   #FIXME needs to do something for /pub resources
  973:   if (!$domain) { $domain=$ENV{'user.domain'}; }
  974:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
  975: 
  976:   my %returnhash;
  977:   $namespace=~s/\//\_/g;
  978:   $namespace=~s/\W//g;
  979:   my %hash;
  980:   my $path=$perlvar{'lonDaemons'}.'/tmp';
  981:   if (tie(%hash,'GDBM_File',
  982: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
  983: 	  &GDBM_READER,0640)) {
  984:     my $version=$hash{"version:$symb"};
  985:     $returnhash{'version'}=$version;
  986:     my $scope;
  987:     for ($scope=1;$scope<=$version;$scope++) {
  988:       my $vkeys=$hash{"$scope:keys:$symb"};
  989:       my @keys=split(/:/,$vkeys);
  990:       my $key;
  991:       $returnhash{"$scope:keys"}=$vkeys;
  992:       foreach $key (@keys) {
  993: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
  994: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
  995:       }
  996:     }
  997:     if (!(untie(%hash))) {
  998:       return "error:$!";
  999:     }
 1000:   } else {
 1001:     return "error:$!";
 1002:   }
 1003:   return %returnhash;
 1004: }
 1005: 
 1006: # ----------------------------------------------------------------------- Store
 1007: 
 1008: sub store {
 1009:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1010:     my $home='';
 1011: 
 1012:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1013: 
 1014:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1015: 
 1016:     &devalidate($symb);
 1017: 
 1018:     $symb=escape($symb);
 1019:     if (!$namespace) { 
 1020:        unless ($namespace=$ENV{'request.course.id'}) { 
 1021:           return ''; 
 1022:        } 
 1023:     }
 1024:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1025:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1026:     if (!$home) { $home=$ENV{'user.home'}; }
 1027:     my $namevalue='';
 1028:     foreach (keys %$storehash) {
 1029:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1030:     }
 1031:     $namevalue=~s/\&$//;
 1032:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 1033:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1034: }
 1035: 
 1036: # -------------------------------------------------------------- Critical Store
 1037: 
 1038: sub cstore {
 1039:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1040:     my $home='';
 1041: 
 1042:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1043: 
 1044:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1045: 
 1046:     &devalidate($symb);
 1047: 
 1048:     $symb=escape($symb);
 1049:     if (!$namespace) { 
 1050:        unless ($namespace=$ENV{'request.course.id'}) { 
 1051:           return ''; 
 1052:        } 
 1053:     }
 1054:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1055:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1056:     if (!$home) { $home=$ENV{'user.home'}; }
 1057: 
 1058:     my $namevalue='';
 1059:     foreach (keys %$storehash) {
 1060:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1061:     }
 1062:     $namevalue=~s/\&$//;
 1063:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 1064:     return critical
 1065:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1066: }
 1067: 
 1068: # --------------------------------------------------------------------- Restore
 1069: 
 1070: sub restore {
 1071:     my ($symb,$namespace,$domain,$stuname) = @_;
 1072:     my $home='';
 1073: 
 1074:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1075: 
 1076:     if (!$symb) {
 1077:       unless ($symb=escape(&symbread())) { return ''; }
 1078:     } else {
 1079:       $symb=&escape($symb);
 1080:     }
 1081:     if (!$namespace) { 
 1082:        unless ($namespace=$ENV{'request.course.id'}) { 
 1083:           return ''; 
 1084:        } 
 1085:     }
 1086:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1087:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1088:     if (!$home) { $home=$ENV{'user.home'}; }
 1089:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 1090: 
 1091:     my %returnhash=();
 1092:     foreach (split(/\&/,$answer)) {
 1093: 	my ($name,$value)=split(/\=/,$_);
 1094:         $returnhash{&unescape($name)}=&unescape($value);
 1095:     }
 1096:     my $version;
 1097:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 1098:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 1099:           $returnhash{$_}=$returnhash{$version.':'.$_};
 1100:        }
 1101:     }
 1102:     return %returnhash;
 1103: }
 1104: 
 1105: # ---------------------------------------------------------- Course Description
 1106: 
 1107: sub coursedescription {
 1108:     my $courseid=shift;
 1109:     $courseid=~s/^\///;
 1110:     $courseid=~s/\_/\//g;
 1111:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1112:     my $chome=&homeserver($cnum,$cdomain);
 1113:     if ($chome ne 'no_host') {
 1114:        my %returnhash=&dump('environment',$cdomain,$cnum);
 1115:        if (!exists($returnhash{'con_lost'})) {
 1116:            my $normalid=$cdomain.'_'.$cnum;
 1117:            my %envhash=();
 1118:            $returnhash{'home'}= $chome;
 1119: 	   $returnhash{'domain'} = $cdomain;
 1120: 	   $returnhash{'num'} = $cnum;
 1121:            while (my ($name,$value) = each %returnhash) {
 1122:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 1123:            }
 1124:            $returnhash{'url'}='/res/'.declutter($returnhash{'url'});
 1125:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 1126: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
 1127:            $envhash{'course.'.$normalid.'.last_cache'}=time;
 1128:            $envhash{'course.'.$normalid.'.home'}=$chome;
 1129:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 1130:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 1131:            &appenv(%envhash);
 1132:            return %returnhash;
 1133:        }
 1134:     }
 1135:     return ();
 1136: }
 1137: 
 1138: # -------------------------------------------------------- Get user privileges
 1139: 
 1140: sub rolesinit {
 1141:     my ($domain,$username,$authhost)=@_;
 1142:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 1143:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 1144:     my %allroles=();
 1145:     my %thesepriv=();
 1146:     my $now=time;
 1147:     my $userroles="user.login.time=$now\n";
 1148:     my $thesestr;
 1149: 
 1150:     if ($rolesdump ne '') {
 1151:         foreach (split(/&/,$rolesdump)) {
 1152: 	  if ($_!~/^rolesdef\&/) {
 1153:             my ($area,$role)=split(/=/,$_);
 1154:             $area=~s/\_\w\w$//;
 1155:             my ($trole,$tend,$tstart)=split(/_/,$role);
 1156:             $userroles.='user.role.'.$trole.'.'.$area.'='.
 1157:                         $tstart.'.'.$tend."\n";
 1158:             if ($tend!=0) {
 1159: 	        if ($tend<$now) {
 1160: 	            $trole='';
 1161:                 } 
 1162:             }
 1163:             if ($tstart!=0) {
 1164:                 if ($tstart>$now) {
 1165:                    $trole='';        
 1166:                 }
 1167:             }
 1168:             if (($area ne '') && ($trole ne '')) {
 1169: 	       my $spec=$trole.'.'.$area;
 1170:                my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 1171:                if ($trole =~ /^cr\//) {
 1172: 		   my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 1173:                    my $homsvr=homeserver($rauthor,$rdomain);
 1174:                    if ($hostname{$homsvr} ne '') {
 1175:                       my $roledef=
 1176: 			  reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
 1177:                                 $homsvr);
 1178:                       if (($roledef ne 'con_lost') && ($roledef ne '')) {
 1179:                          my ($syspriv,$dompriv,$coursepriv)=
 1180: 			     split(/\_/,unescape($roledef));
 1181:  	                 $allroles{'cm./'}.=':'.$syspriv;
 1182:                          $allroles{$spec.'./'}.=':'.$syspriv;
 1183:                          if ($tdomain ne '') {
 1184:                              $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 1185:                              $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 1186:                              if ($trest ne '') {
 1187: 		                $allroles{'cm.'.$area}.=':'.$coursepriv;
 1188: 		                $allroles{$spec.'.'.$area}.=':'.$coursepriv;
 1189:                              }
 1190: 	                 }
 1191:                       }
 1192:                    }
 1193:                } else {
 1194: 	           $allroles{'cm./'}.=':'.$pr{$trole.':s'};
 1195: 	           $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 1196:                    if ($tdomain ne '') {
 1197:                      $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1198:                      $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1199:                       if ($trest ne '') {
 1200: 		          $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 1201: 		          $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 1202:                       }
 1203: 	           }
 1204: 	       }
 1205:             }
 1206:           } 
 1207:         }
 1208:         my $adv=0;
 1209:         my $author=0;
 1210:         foreach (keys %allroles) {
 1211:             %thesepriv=();
 1212:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
 1213:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 1214:             foreach (split(/:/,$allroles{$_})) {
 1215:                 if ($_ ne '') {
 1216: 		    my ($privilege,$restrictions)=split(/&/,$_);
 1217:                     if ($restrictions eq '') {
 1218: 			$thesepriv{$privilege}='F';
 1219:                     } else {
 1220:                         if ($thesepriv{$privilege} ne 'F') {
 1221: 			    $thesepriv{$privilege}.=$restrictions;
 1222:                         }
 1223:                     }
 1224:                 }
 1225:             }
 1226:             $thesestr='';
 1227:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 1228:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
 1229:         }
 1230:         $userroles.='user.adv='.$adv."\n".
 1231: 	            'user.author='.$author."\n";
 1232:         $ENV{'user.adv'}=$adv;
 1233:     }
 1234:     return $userroles;  
 1235: }
 1236: 
 1237: # --------------------------------------------------------------- get interface
 1238: 
 1239: sub get {
 1240:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1241:    my $items='';
 1242:    foreach (@$storearr) {
 1243:        $items.=escape($_).'&';
 1244:    }
 1245:    $items=~s/\&$//;
 1246:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1247:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1248:    my $uhome=&homeserver($uname,$udomain);
 1249: 
 1250:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 1251:    my @pairs=split(/\&/,$rep);
 1252:    my %returnhash=();
 1253:    my $i=0;
 1254:    foreach (@$storearr) {
 1255:       $returnhash{$_}=unescape($pairs[$i]);
 1256:       $i++;
 1257:    }
 1258:    return %returnhash;
 1259: }
 1260: 
 1261: # --------------------------------------------------------------- del interface
 1262: 
 1263: sub del {
 1264:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1265:    my $items='';
 1266:    foreach (@$storearr) {
 1267:        $items.=escape($_).'&';
 1268:    }
 1269:    $items=~s/\&$//;
 1270:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1271:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1272:    my $uhome=&homeserver($uname,$udomain);
 1273: 
 1274:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 1275: }
 1276: 
 1277: # -------------------------------------------------------------- dump interface
 1278: 
 1279: sub dump {
 1280:    my ($namespace,$udomain,$uname,$regexp)=@_;
 1281:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1282:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1283:    my $uhome=&homeserver($uname,$udomain);
 1284:    if ($regexp) {
 1285:        $regexp=&escape($regexp);
 1286:    } else {
 1287:        $regexp='.';
 1288:    }
 1289:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 1290:    my @pairs=split(/\&/,$rep);
 1291:    my %returnhash=();
 1292:    foreach (@pairs) {
 1293:       my ($key,$value)=split(/=/,$_);
 1294:       $returnhash{unescape($key)}=unescape($value);
 1295:    }
 1296:    return %returnhash;
 1297: }
 1298: 
 1299: # --------------------------------------------------------------- put interface
 1300: 
 1301: sub put {
 1302:    my ($namespace,$storehash,$udomain,$uname)=@_;
 1303:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1304:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1305:    my $uhome=&homeserver($uname,$udomain);
 1306:    my $items='';
 1307:    foreach (keys %$storehash) {
 1308:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
 1309:    }
 1310:    $items=~s/\&$//;
 1311:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 1312: }
 1313: 
 1314: # ------------------------------------------------------ critical put interface
 1315: 
 1316: sub cput {
 1317:    my ($namespace,$storehash,$udomain,$uname)=@_;
 1318:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1319:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1320:    my $uhome=&homeserver($uname,$udomain);
 1321:    my $items='';
 1322:    foreach (keys %$storehash) {
 1323:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
 1324:    }
 1325:    $items=~s/\&$//;
 1326:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 1327: }
 1328: 
 1329: # -------------------------------------------------------------- eget interface
 1330: 
 1331: sub eget {
 1332:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1333:    my $items='';
 1334:    foreach (@$storearr) {
 1335:        $items.=escape($_).'&';
 1336:    }
 1337:    $items=~s/\&$//;
 1338:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1339:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1340:    my $uhome=&homeserver($uname,$udomain);
 1341:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 1342:    my @pairs=split(/\&/,$rep);
 1343:    my %returnhash=();
 1344:    my $i=0;
 1345:    foreach (@$storearr) {
 1346:       $returnhash{$_}=unescape($pairs[$i]);
 1347:       $i++;
 1348:    }
 1349:    return %returnhash;
 1350: }
 1351: 
 1352: # ------------------------------------------------- Check for a user privilege
 1353: 
 1354: sub allowed {
 1355:     my ($priv,$uri)=@_;
 1356: 
 1357:     my $orguri=$uri;
 1358:     $uri=&declutter($uri);
 1359: 
 1360: # Free bre access to adm and meta resources
 1361: 
 1362:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 1363: 	return 'F';
 1364:     }
 1365: 
 1366: # Free bre to public access
 1367: 
 1368:     if ($priv eq 'bre') {
 1369: 	if (&metadata($uri,'copyright') eq 'public') { return 'F'; }
 1370:     }
 1371: 
 1372:     my $thisallowed='';
 1373:     my $statecond=0;
 1374:     my $courseprivid='';
 1375: 
 1376: # Course
 1377: 
 1378:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
 1379:        $thisallowed.=$1;
 1380:     }
 1381: 
 1382: # Domain
 1383: 
 1384:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 1385:        =~/$priv\&([^\:]*)/) {
 1386:        $thisallowed.=$1;
 1387:     }
 1388: 
 1389: # Course: uri itself is a course
 1390:     my $courseuri=$uri;
 1391:     $courseuri=~s/\_(\d)/\/$1/;
 1392:     $courseuri=~s/^([^\/])/\/$1/;
 1393: 
 1394:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 1395:        =~/$priv\&([^\:]*)/) {
 1396:        $thisallowed.=$1;
 1397:     }
 1398: 
 1399: # Full access at system, domain or course-wide level? Exit.
 1400: 
 1401:     if ($thisallowed=~/F/) {
 1402: 	return 'F';
 1403:     }
 1404: 
 1405: # If this is generating or modifying users, exit with special codes
 1406: 
 1407:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
 1408: 	return $thisallowed;
 1409:     }
 1410: #
 1411: # Gathered so far: system, domain and course wide privileges
 1412: #
 1413: # Course: See if uri or referer is an individual resource that is part of 
 1414: # the course
 1415: 
 1416:     if ($ENV{'request.course.id'}) {
 1417:        $courseprivid=$ENV{'request.course.id'};
 1418:        if ($ENV{'request.course.sec'}) {
 1419:           $courseprivid.='/'.$ENV{'request.course.sec'};
 1420:        }
 1421:        $courseprivid=~s/\_/\//;
 1422:        my $checkreferer=1;
 1423:        my @uriparts=split(/\//,$uri);
 1424:        my $filename=$uriparts[$#uriparts];
 1425:        my $pathname=$uri;
 1426:        $pathname=~s/\/$filename$//;
 1427:        if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 1428:            /\&$filename\:([\d\|]+)\&/) {
 1429:            $statecond=$1;
 1430:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 1431:                =~/$priv\&([^\:]*)/) {
 1432:                $thisallowed.=$1;
 1433:                $checkreferer=0;
 1434:            }
 1435:        }
 1436:        
 1437:        if ($checkreferer) {
 1438: 	  my $refuri=$ENV{'httpref.'.$orguri};
 1439: 
 1440:             unless ($refuri) {
 1441:                 foreach (keys %ENV) {
 1442: 		    if ($_=~/^httpref\..*\*/) {
 1443: 			my $pattern=$_;
 1444:                         $pattern=~s/^httpref\.\/res\///;
 1445:                         $pattern=~s/\*/\[\^\/\]\+/g;
 1446:                         $pattern=~s/\//\\\//g;
 1447:                         if ($orguri=~/$pattern/) {
 1448: 			    $refuri=$ENV{$_};
 1449:                         }
 1450:                     }
 1451:                 }
 1452:             }
 1453:          if ($refuri) { 
 1454: 	  $refuri=&declutter($refuri);
 1455:           my @uriparts=split(/\//,$refuri);
 1456:           my $filename=$uriparts[$#uriparts];
 1457:           my $pathname=$refuri;
 1458:           $pathname=~s/\/$filename$//;
 1459:             if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 1460:               /\&$filename\:([\d\|]+)\&/) {
 1461:               my $refstatecond=$1;
 1462:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 1463:                   =~/$priv\&([^\:]*)/) {
 1464:                   $thisallowed.=$1;
 1465:                   $uri=$refuri;
 1466:                   $statecond=$refstatecond;
 1467:               }
 1468:           }
 1469:         }
 1470:        }
 1471:    }
 1472: 
 1473: #
 1474: # Gathered now: all privileges that could apply, and condition number
 1475: # 
 1476: #
 1477: # Full or no access?
 1478: #
 1479: 
 1480:     if ($thisallowed=~/F/) {
 1481: 	return 'F';
 1482:     }
 1483: 
 1484:     unless ($thisallowed) {
 1485:         return '';
 1486:     }
 1487: 
 1488: # Restrictions exist, deal with them
 1489: #
 1490: #   C:according to course preferences
 1491: #   R:according to resource settings
 1492: #   L:unless locked
 1493: #   X:according to user session state
 1494: #
 1495: 
 1496: # Possibly locked functionality, check all courses
 1497: # Locks might take effect only after 10 minutes cache expiration for other
 1498: # courses, and 2 minutes for current course
 1499: 
 1500:     my $envkey;
 1501:     if ($thisallowed=~/L/) {
 1502:         foreach $envkey (keys %ENV) {
 1503:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 1504:                my $courseid=$2;
 1505:                my $roleid=$1.'.'.$2;
 1506:                $courseid=~s/^\///;
 1507:                my $expiretime=600;
 1508:                if ($ENV{'request.role'} eq $roleid) {
 1509: 		  $expiretime=120;
 1510:                }
 1511: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 1512:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 1513:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 1514: 		   &coursedescription($courseid);
 1515:                }
 1516:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
 1517:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 1518: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 1519:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 1520:                             $ENV{'user.host'},
 1521:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 1522:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 1523:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 1524: 		       return '';
 1525:                    }
 1526:                }
 1527:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
 1528:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 1529: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 1530:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 1531:                             $ENV{'user.host'},
 1532:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 1533:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 1534:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 1535: 		       return '';
 1536:                    }
 1537:                }
 1538: 	   }
 1539:        }
 1540:     }
 1541:    
 1542: #
 1543: # Rest of the restrictions depend on selected course
 1544: #
 1545: 
 1546:     unless ($ENV{'request.course.id'}) {
 1547:        return '1';
 1548:     }
 1549: 
 1550: #
 1551: # Now user is definitely in a course
 1552: #
 1553: 
 1554: 
 1555: # Course preferences
 1556: 
 1557:    if ($thisallowed=~/C/) {
 1558:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 1559:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 1560: 	   =~/$rolecode/) {
 1561:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 1562:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 1563:                 $ENV{'request.course.id'});
 1564:            return '';
 1565:        }
 1566:    }
 1567: 
 1568: # Resource preferences
 1569: 
 1570:    if ($thisallowed=~/R/) {
 1571:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 1572:        my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
 1573:        if (-e $filename) {
 1574:            my @content;
 1575:            {
 1576: 	     my $fh=Apache::File->new($filename);
 1577:              @content=<$fh>;
 1578: 	   }
 1579:            if (join('',@content)=~
 1580:                     /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
 1581: 	       &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 1582:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 1583:            return '';
 1584: 
 1585:            }
 1586:        }
 1587:    }
 1588: 
 1589: # Restricted by state?
 1590: 
 1591:    if ($thisallowed=~/X/) {
 1592:       if (&condval($statecond)) {
 1593: 	 return '2';
 1594:       } else {
 1595:          return '';
 1596:       }
 1597:    }
 1598: 
 1599:    return 'F';
 1600: }
 1601: 
 1602: # ----------------------------------------------------------------- Define Role
 1603: 
 1604: sub definerole {
 1605:   if (allowed('mcr','/')) {
 1606:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 1607:     foreach (split('/',$sysrole)) {
 1608: 	my ($crole,$cqual)=split(/\&/,$_);
 1609:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
 1610:         if ($pr{'cr:s'}=~/$crole\&/) {
 1611: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
 1612:                return "refused:s:$crole&$cqual"; 
 1613:             }
 1614:         }
 1615:     }
 1616:     foreach (split('/',$domrole)) {
 1617: 	my ($crole,$cqual)=split(/\&/,$_);
 1618:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
 1619:         if ($pr{'cr:d'}=~/$crole\&/) {
 1620: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
 1621:                return "refused:d:$crole&$cqual"; 
 1622:             }
 1623:         }
 1624:     }
 1625:     foreach (split('/',$courole)) {
 1626: 	my ($crole,$cqual)=split(/\&/,$_);
 1627:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
 1628:         if ($pr{'cr:c'}=~/$crole\&/) {
 1629: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
 1630:                return "refused:c:$crole&$cqual"; 
 1631:             }
 1632:         }
 1633:     }
 1634:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 1635:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 1636: 	        "rolesdef_$rolename=".
 1637:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 1638:     return reply($command,$ENV{'user.home'});
 1639:   } else {
 1640:     return 'refused';
 1641:   }
 1642: }
 1643: 
 1644: # ---------------- Make a metadata query against the network of library servers
 1645: 
 1646: sub metadata_query {
 1647:     my ($query,$custom,$customshow)=@_;
 1648:     my %rhash;
 1649:     for my $server (keys %libserv) {
 1650: 	unless ($custom or $customshow) {
 1651: 	    my $reply=&reply("querysend:".&escape($query),$server);
 1652: 	    $rhash{$server}=$reply;
 1653: 	}
 1654: 	else {
 1655: 	    my $reply=&reply("querysend:".&escape($query).':'.
 1656: 			     &escape($custom).':'.&escape($customshow),
 1657: 			     $server);
 1658: 	    $rhash{$server}=$reply;
 1659: 	}
 1660:     }
 1661:     return \%rhash;
 1662: }
 1663: 
 1664: # ------------------------------------------------------------------ Plain Text
 1665: 
 1666: sub plaintext {
 1667:     my $short=shift;
 1668:     return $prp{$short};
 1669: }
 1670: 
 1671: # ----------------------------------------------------------------- Assign Role
 1672: 
 1673: sub assignrole {
 1674:     my ($udom,$uname,$url,$role,$end,$start)=@_;
 1675:     my $mrole;
 1676:     if ($role =~ /^cr\//) {
 1677: 	unless (&allowed('ccr',$url)) {
 1678:            &logthis('Refused custom assignrole: '.
 1679:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 1680: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 1681:            return 'refused'; 
 1682:         }
 1683:         $mrole='cr';
 1684:     } else {
 1685:         my $cwosec=$url;
 1686:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 1687:         unless (&allowed('c'.$role,$cwosec)) { 
 1688:            &logthis('Refused assignrole: '.
 1689:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 1690: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 1691:            return 'refused'; 
 1692:         }
 1693:         $mrole=$role;
 1694:     }
 1695:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 1696:                 "$udom:$uname:$url".'_'."$mrole=$role";
 1697:     if ($end) { $command.='_'.$end; }
 1698:     if ($start) {
 1699: 	if ($end) { 
 1700:            $command.='_'.$start; 
 1701:         } else {
 1702:            $command.='_0_'.$start;
 1703:         }
 1704:     }
 1705:     return &reply($command,&homeserver($uname,$udom));
 1706: }
 1707: 
 1708: # -------------------------------------------------- Modify user authentication
 1709: sub modifyuserauth {
 1710:     my ($udom,$uname,$umode,$upass)=@_;
 1711:     my $uhome=&homeserver($uname,$udom);
 1712:     &logthis('Call to modify user authentication'.$udom.', '.$uname.', '.
 1713:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'});  
 1714:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 1715: 		     &escape($upass),$uhome);
 1716:     unless ($reply eq 'ok') {
 1717: 	return 'error: '.$reply;
 1718:     }   
 1719:     return 'ok';
 1720: }
 1721: 
 1722: # --------------------------------------------------------------- Modify a user
 1723: 
 1724: 
 1725: sub modifyuser {
 1726:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 1727:         $forceid)=@_;
 1728:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 1729:              $umode.', '.$first.', '.$middle.', '.
 1730: 	     $last.', '.$gene.'(forceid: '.$forceid.') by '.
 1731:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});  
 1732:     my $uhome=&homeserver($uname,$udom);
 1733: # ----------------------------------------------------------------- Create User
 1734:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
 1735:         my $unhome='';
 1736: 	if ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 1737: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1738:         } else {
 1739:             my $tryserver;
 1740:             my $loadm=10000000;
 1741:             foreach $tryserver (keys %libserv) {
 1742: 	       if ($hostdom{$tryserver} eq $udom) {
 1743:                   my $answer=reply('load',$tryserver);
 1744:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 1745: 		      $loadm=$answer;
 1746:                       $unhome=$tryserver;
 1747:                   }
 1748: 	       }
 1749: 	    }
 1750:         }
 1751:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 1752: 	    return 'error: find home';
 1753:         }
 1754:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 1755:                          &escape($upass),$unhome);
 1756: 	unless ($reply eq 'ok') {
 1757:             return 'error: '.$reply;
 1758:         }   
 1759:         $uhome=&homeserver($uname,$udom);
 1760:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 1761: 	    return 'error: verify home';
 1762:         }
 1763:     }
 1764: # ---------------------------------------------------------------------- Add ID
 1765:     if ($uid) {
 1766:        $uid=~tr/A-Z/a-z/;
 1767:        my %uidhash=&idrget($udom,$uname);
 1768:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 1769:          && (!$forceid)) {
 1770: 	  unless ($uid eq $uidhash{$uname}) {
 1771: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
 1772:           }
 1773:        } else {
 1774: 	  &idput($udom,($uname => $uid));
 1775:        }
 1776:     }
 1777: # -------------------------------------------------------------- Add names, etc
 1778:     my %names=&get('environment',
 1779: 		   ['firstname','middlename','lastname','generation'],
 1780: 		   $udom,$uname);
 1781:     if ($first)  { $names{'firstname'}  = $first; }
 1782:     if ($middle) { $names{'middlename'} = $middle; }
 1783:     if ($last)   { $names{'lastname'}   = $last; }
 1784:     if ($gene)   { $names{'generation'} = $gene; }
 1785:     my $reply = &put('environment', \%names, $udom,$uname);
 1786:     if ($reply ne 'ok') { return 'error: '.$reply; }
 1787:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 1788:              $umode.', '.$first.', '.$middle.', '.
 1789: 	     $last.', '.$gene.' by '.
 1790:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 1791:     return 'ok';
 1792: }
 1793: 
 1794: # -------------------------------------------------------------- Modify student
 1795: 
 1796: sub modifystudent {
 1797:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 1798:         $end,$start)=@_;
 1799:     my $cid='';
 1800:     unless ($cid=$ENV{'request.course.id'}) {
 1801: 	return 'not_in_class';
 1802:     }
 1803: # --------------------------------------------------------------- Make the user
 1804:     my $reply=&modifyuser
 1805: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene);
 1806:     unless ($reply eq 'ok') { return $reply; }
 1807:     my $uhome=&homeserver($uname,$udom);
 1808:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 1809: 	return 'error: no such user';
 1810:     }
 1811: # -------------------------------------------------- Add student to course list
 1812:     $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 1813: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
 1814:                       &escape($uname.':'.$udom).'='.
 1815:                       &escape($end.':'.$start),
 1816: 	              $ENV{'course.'.$cid.'.home'});
 1817:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 1818: 	return 'error: '.$reply;
 1819:     }
 1820: # ---------------------------------------------------- Add student role to user
 1821:     my $uurl='/'.$cid;
 1822:     $uurl=~s/\_/\//g;
 1823:     if ($usec) {
 1824: 	$uurl.='/'.$usec;
 1825:     }
 1826:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 1827: }
 1828: 
 1829: # ------------------------------------------------- Write to course preferences
 1830: 
 1831: sub writecoursepref {
 1832:     my ($courseid,%prefs)=@_;
 1833:     $courseid=~s/^\///;
 1834:     $courseid=~s/\_/\//g;
 1835:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1836:     my $chome=homeserver($cnum,$cdomain);
 1837:     if (($chome eq '') || ($chome eq 'no_host')) { 
 1838: 	return 'error: no such course';
 1839:     }
 1840:     my $cstring='';
 1841:     foreach (keys %prefs) {
 1842: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 1843:     }
 1844:     $cstring=~s/\&$//;
 1845:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 1846: }
 1847: 
 1848: # ---------------------------------------------------------- Make/modify course
 1849: 
 1850: sub createcourse {
 1851:     my ($udom,$description,$url)=@_;
 1852:     $url=&declutter($url);
 1853:     my $cid='';
 1854:     unless (&allowed('ccc',$ENV{'user.domain'})) {
 1855:         return 'refused';
 1856:     }
 1857:     unless ($udom eq $ENV{'user.domain'}) {
 1858:         return 'refused';
 1859:     }
 1860: # ------------------------------------------------------------------- Create ID
 1861:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 1862:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 1863: # ----------------------------------------------- Make sure that does not exist
 1864:    my $uhome=&homeserver($uname,$udom);
 1865:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 1866:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 1867:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 1868:        $uhome=&homeserver($uname,$udom);       
 1869:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 1870:            return 'error: unable to generate unique course-ID';
 1871:        } 
 1872:    }
 1873: # ------------------------------------------------------------- Make the course
 1874:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 1875:                       $ENV{'user.home'});
 1876:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 1877:     $uhome=&homeserver($uname,$udom);
 1878:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 1879: 	return 'error: no such course';
 1880:     }
 1881:     &writecoursepref($udom.'_'.$uname,
 1882:                      ('description' => $description,
 1883:                       'url'         => $url));
 1884:     return '/'.$udom.'/'.$uname;
 1885: }
 1886: 
 1887: # ---------------------------------------------------------- Assign Custom Role
 1888: 
 1889: sub assigncustomrole {
 1890:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
 1891:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 1892:                        $end,$start);
 1893: }
 1894: 
 1895: # ----------------------------------------------------------------- Revoke Role
 1896: 
 1897: sub revokerole {
 1898:     my ($udom,$uname,$url,$role)=@_;
 1899:     my $now=time;
 1900:     return &assignrole($udom,$uname,$url,$role,$now);
 1901: }
 1902: 
 1903: # ---------------------------------------------------------- Revoke Custom Role
 1904: 
 1905: sub revokecustomrole {
 1906:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
 1907:     my $now=time;
 1908:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
 1909: }
 1910: 
 1911: # ------------------------------------------------------------ Directory lister
 1912: 
 1913: sub dirlist {
 1914:     my $uri=shift;
 1915:     $uri=~s/^\///;
 1916:     $uri=~s/\/$//;
 1917:     my ($res,$udom,$uname,@rest)=split(/\//,$uri);
 1918:     if ($udom) {
 1919:      if ($uname) {
 1920:        my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/'.$uri,
 1921:                       homeserver($uname,$udom));
 1922:        return split(/:/,$listing);
 1923:      } else {
 1924:        my $tryserver;
 1925:        my %allusers=();
 1926:        foreach $tryserver (keys %libserv) {
 1927: 	  if ($hostdom{$tryserver} eq $udom) {
 1928:              my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.$udom,
 1929: 			       $tryserver);
 1930:              if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 1931:               && ($listing ne 'con_lost')) {
 1932:                 foreach (split(/:/,$listing)) {
 1933:                   my ($entry,@stat)=split(/&/,$_);
 1934:                   $allusers{$entry}=1;
 1935:                 }
 1936:              }
 1937: 	  }
 1938:        }
 1939:        my $alluserstr='';
 1940:        foreach (sort keys %allusers) {
 1941:            $alluserstr.=$_.'&user:';
 1942:        }
 1943:        $alluserstr=~s/:$//;
 1944:        return split(/:/,$alluserstr);
 1945:      } 
 1946:    } else {
 1947:        my $tryserver;
 1948:        my %alldom=();
 1949:        foreach $tryserver (keys %libserv) {
 1950: 	   $alldom{$hostdom{$tryserver}}=1;
 1951:        }
 1952:        my $alldomstr='';
 1953:        foreach (sort keys %alldom) {
 1954:           $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
 1955:        }
 1956:        $alldomstr=~s/:$//;
 1957:        return split(/:/,$alldomstr);       
 1958:    }
 1959: }
 1960: 
 1961: # -------------------------------------------------------- Value of a Condition
 1962: 
 1963: sub directcondval {
 1964:     my $number=shift;
 1965:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 1966:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 1967:     } else {
 1968:        return 2;
 1969:     }
 1970: }
 1971: 
 1972: sub condval {
 1973:     my $condidx=shift;
 1974:     my $result=0;
 1975:     my $allpathcond='';
 1976:     foreach (split(/\|/,$condidx)) {
 1977:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 1978: 	   $allpathcond.=
 1979:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 1980:        }
 1981:     }
 1982:     $allpathcond=~s/\|$//;
 1983:     if ($ENV{'request.course.id'}) {
 1984:        if ($allpathcond) {
 1985:           my $operand='|';
 1986: 	  my @stack;
 1987:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 1988:               if ($_ eq '(') {
 1989:                  push @stack,($operand,$result)
 1990:               } elsif ($_ eq ')') {
 1991:                   my $before=pop @stack;
 1992: 		  if (pop @stack eq '&') {
 1993: 		      $result=$result>$before?$before:$result;
 1994:                   } else {
 1995:                       $result=$result>$before?$result:$before;
 1996:                   }
 1997:               } elsif (($_ eq '&') || ($_ eq '|')) {
 1998:                   $operand=$_;
 1999:               } else {
 2000:                   my $new=directcondval($_);
 2001:                   if ($operand eq '&') {
 2002:                      $result=$result>$new?$new:$result;
 2003:                   } else {
 2004:                      $result=$result>$new?$result:$new;
 2005:                   }
 2006:               }
 2007:           }
 2008:        }
 2009:     }
 2010:     return $result;
 2011: }
 2012: 
 2013: # --------------------------------------------------------- Value of a Variable
 2014: 
 2015: sub EXT {
 2016:     my ($varname,$symbparm)=@_;
 2017:     unless ($varname) { return ''; }
 2018:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 2019:     my $rest;
 2020:     if ($therest[0]) {
 2021:        $rest=join('.',@therest);
 2022:     } else {
 2023:        $rest='';
 2024:     }
 2025:     my $qualifierrest=$qualifier;
 2026:     if ($rest) { $qualifierrest.='.'.$rest; }
 2027:     my $spacequalifierrest=$space;
 2028:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 2029:     if ($realm eq 'user') {
 2030: # --------------------------------------------------------------- user.resource
 2031: 	if ($space eq 'resource') {
 2032: 	    my %restored=&restore();
 2033:             return $restored{$qualifierrest};
 2034: # ----------------------------------------------------------------- user.access
 2035:         } elsif ($space eq 'access') {
 2036:             return &allowed($qualifier,$rest);
 2037: # ------------------------------------------ user.preferences, user.environment
 2038:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 2039:             return $ENV{join('.',('environment',$qualifierrest))};
 2040: # ----------------------------------------------------------------- user.course
 2041:         } elsif ($space eq 'course') {
 2042:             return $ENV{join('.',('request.course',$qualifier))};
 2043: # ------------------------------------------------------------------- user.role
 2044:         } elsif ($space eq 'role') {
 2045:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 2046:             if ($qualifier eq 'value') {
 2047: 		return $role;
 2048:             } elsif ($qualifier eq 'extent') {
 2049:                 return $where;
 2050:             }
 2051: # ----------------------------------------------------------------- user.domain
 2052:         } elsif ($space eq 'domain') {
 2053:             return $ENV{'user.domain'};
 2054: # ------------------------------------------------------------------- user.name
 2055:         } elsif ($space eq 'name') {
 2056:             return $ENV{'user.name'};
 2057: # ---------------------------------------------------- Any other user namespace
 2058:         } else {
 2059:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
 2060:             my %reply=&get($space,[$item]);
 2061:             return $reply{$item};
 2062:         }
 2063:     } elsif ($realm eq 'request') {
 2064: # ------------------------------------------------------------- request.browser
 2065:         if ($space eq 'browser') {
 2066: 	    return $ENV{'browser.'.$qualifier};
 2067: # ------------------------------------------------------------ request.filename
 2068:         } else {
 2069:             return $ENV{'request.'.$spacequalifierrest};
 2070:         }
 2071:     } elsif ($realm eq 'course') {
 2072: # ---------------------------------------------------------- course.description
 2073:         return $ENV{'course.'.$ENV{'request.course.id'}.'.'.
 2074:                               $spacequalifierrest};
 2075:     } elsif ($realm eq 'resource') {
 2076:        if ($ENV{'request.course.id'}) {
 2077: 
 2078: #	   print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 2079: 
 2080: 
 2081: # ----------------------------------------------------- Cascading lookup scheme
 2082:          my $symbp;
 2083:          if ($symbparm) {
 2084:             $symbp=$symbparm;
 2085: 	 } else {
 2086:             $symbp=&symbread();
 2087:          }            
 2088:          my $mapp=(split(/\_\_\_/,$symbp))[0];
 2089: 
 2090:          my $symbparm=$symbp.'.'.$spacequalifierrest;
 2091:          my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 2092: 
 2093:          my $seclevel=
 2094:             $ENV{'request.course.id'}.'.['.
 2095: 		$ENV{'request.course.sec'}.'].'.$spacequalifierrest;
 2096:          my $seclevelr=
 2097:             $ENV{'request.course.id'}.'.['.
 2098: 		$ENV{'request.course.sec'}.'].'.$symbparm;
 2099:          my $seclevelm=
 2100:             $ENV{'request.course.id'}.'.['.
 2101: 		$ENV{'request.course.sec'}.'].'.$mapparm;
 2102: 
 2103:          my $courselevel=
 2104:             $ENV{'request.course.id'}.'.'.$spacequalifierrest;
 2105:          my $courselevelr=
 2106:             $ENV{'request.course.id'}.'.'.$symbparm;
 2107:          my $courselevelm=
 2108:             $ENV{'request.course.id'}.'.'.$mapparm;
 2109: 
 2110: # ----------------------------------------------------------- first, check user
 2111:          my %resourcedata=get('resourcedata',
 2112:                            [$courselevelr,$courselevelm,$courselevel]);
 2113:          if (($resourcedata{$courselevelr}!~/^error\:/) &&
 2114:              ($resourcedata{$courselevelr}!~/^con_lost/)) {
 2115: 
 2116:          if ($resourcedata{$courselevelr}) { 
 2117:             return $resourcedata{$courselevelr}; }
 2118:          if ($resourcedata{$courselevelm}) { 
 2119:             return $resourcedata{$courselevelm}; }
 2120:          if ($resourcedata{$courselevel}) { return $resourcedata{$courselevel}; }
 2121: 
 2122:       } else {
 2123: 	  if ($resourcedata{$courselevelr}!~/No such file/) {
 2124: 	    &logthis("<font color=blue>WARNING:".
 2125: 		   " Trying to get resource data for ".$ENV{'user.name'}." at "
 2126:                    .$ENV{'user.domain'}.": ".$resourcedata{$courselevelr}.
 2127:                  "</font>");
 2128: 	  }
 2129:       }
 2130: 
 2131: # -------------------------------------------------------- second, check course
 2132: 
 2133:         my $reply=&reply('get:'.
 2134:               $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
 2135:               $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
 2136: 	      ':resourcedata:'.
 2137:    &escape($seclevelr).'&'.&escape($seclevelm).'&'.&escape($seclevel).'&'.
 2138:    &escape($courselevelr).'&'.&escape($courselevelm).'&'.&escape($courselevel),
 2139: 		   $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
 2140:       if ($reply!~/^error\:/) {
 2141: 	  foreach (split(/\&/,$reply)) {
 2142: 	      if ($_) { return &unescape($_); }
 2143:           }
 2144:       }
 2145:       if (($reply=~/^con_lost/) || ($reply=~/^error\:/)) {
 2146: 	  &logthis("<font color=blue>WARNING:".
 2147:                 " Getting ".$reply." asking for ".$varname." for ".
 2148:                 $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
 2149:                 ' at '.
 2150:                 $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
 2151:                 ' from '.
 2152:                 $ENV{'course.'.$ENV{'request.course.id'}.'.home'}.
 2153:                  "</font>");
 2154:       }
 2155: # ------------------------------------------------------ third, check map parms
 2156:        my %parmhash=();
 2157:        my $thisparm='';       
 2158:        if (tie(%parmhash,'GDBM_File',
 2159:           $ENV{'request.course.fn'}.'_parms.db',&GDBM_READER,0640)) {
 2160:            $thisparm=$parmhash{$symbparm};
 2161: 	   untie(%parmhash);
 2162:        }
 2163:        if ($thisparm) { return $thisparm; }
 2164:      }
 2165:      
 2166: # --------------------------------------------- last, look in resource metadata
 2167: 
 2168:       $spacequalifierrest=~s/\./\_/;
 2169:       my $metadata=&metadata($ENV{'request.filename'},$spacequalifierrest);
 2170:       if ($metadata) { return $metadata; }
 2171:       $metadata=&metadata($ENV{'request.filename'},
 2172:                                          'parameter_'.$spacequalifierrest);
 2173:       if ($metadata) { return $metadata; }
 2174: 
 2175: # ------------------------------------------------------------------ Cascade up
 2176: 
 2177:       unless ($space eq '0') {
 2178:           my ($part,$id)=split(/\_/,$space);
 2179:           if ($id) {
 2180: 	      my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 2181:                                    $symbparm);
 2182:               if ($partgeneral) { return $partgeneral; }
 2183:           } else {
 2184:               my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
 2185:                                        $symbparm);
 2186:               if ($resourcegeneral) { return $resourcegeneral; }
 2187:           }
 2188:       }
 2189: 
 2190: # ---------------------------------------------------- Any other user namespace
 2191:     } elsif ($realm eq 'environment') {
 2192: # ----------------------------------------------------------------- environment
 2193:         return $ENV{'environment.'.$spacequalifierrest};
 2194:     } elsif ($realm eq 'system') {
 2195: # ----------------------------------------------------------------- system.time
 2196: 	if ($space eq 'time') {
 2197: 	    return time;
 2198:         }
 2199:     }
 2200:     return '';
 2201: }
 2202: 
 2203: # ---------------------------------------------------------------- Get metadata
 2204: 
 2205: sub metadata {
 2206:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 2207: 
 2208:     $uri=&declutter($uri);
 2209:     my $filename=$uri;
 2210:     $uri=~s/\.meta$//;
 2211: #
 2212: # Is the metadata already cached?
 2213: # Look at timestamp of caching
 2214: # Everything is cached by the main uri, libraries are never directly cached
 2215: #
 2216:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600) {
 2217: #
 2218: # Is this a recursive call for a library?
 2219: #
 2220:         if ($liburi) {
 2221: 	    $liburi=&declutter($liburi);
 2222:             $filename=$liburi;
 2223:         }
 2224:         my %metathesekeys=();
 2225:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 2226: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
 2227:         my $parser=HTML::TokeParser->new(\$metastring);
 2228:         my $token;
 2229:         undef %metathesekeys;
 2230:         while ($token=$parser->get_token) {
 2231:            if ($token->[0] eq 'S') {
 2232: 	     if (defined($token->[2]->{'package'})) {
 2233: #
 2234: # This is a package - get package info
 2235: #
 2236: 	      my $package=$token->[2]->{'package'};
 2237: 	      my $keyroot='';
 2238:               if ($prefix) {
 2239: 		  $keyroot.='_'.$prefix;
 2240:               } else {
 2241:                 if (defined($token->[2]->{'part'})) { 
 2242:                    $keyroot.='_'.$token->[2]->{'part'}; 
 2243: 	        }
 2244: 	      }
 2245:               if (defined($token->[2]->{'id'})) { 
 2246:                  $keyroot.='_'.$token->[2]->{'id'}; 
 2247: 	      }
 2248:               if ($metacache{$uri.':packages'}) {
 2249:                  $metacache{$uri.':packages'}.=','.$package.$keyroot;
 2250:               } else {
 2251:                  $metacache{$uri.':packages'}=$package.$keyroot;
 2252: 	      }
 2253:               foreach (keys %packagetab) {
 2254: 		  if ($_=~/^$package\&/) {
 2255: 		      my ($pack,$name,$subp)=split(/\&/,$_);
 2256:                       my $value=$packagetab{$_};
 2257: 		      my $part=$keyroot;
 2258:                       $part=~s/^\_//;
 2259:                       if ($subp eq 'display') {
 2260: 			  $value.=' [Part: '.$part.']';
 2261:                       }
 2262:                       my $unikey='parameter'.$keyroot.'_'.$name;
 2263:                       $metathesekeys{$unikey}=1;
 2264:                       $metacache{$uri.':'.$unikey.'.part'}=$part;
 2265:                       unless 
 2266:                        (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
 2267:                          $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
 2268: 		      }
 2269:                   }
 2270:               }
 2271:              } else {
 2272: #
 2273: # This is not a package - some other kind of start tag
 2274: # 
 2275:               my $entry=$token->[1];
 2276:               my $unikey;
 2277:               if ($entry eq 'import') {
 2278:                  $unikey='';
 2279:               } else {
 2280:                  $unikey=$entry;
 2281: 	      }
 2282:               if ($prefix) {
 2283: 		  $unikey.=$prefix;
 2284:               } else {
 2285:                 if (defined($token->[2]->{'part'})) { 
 2286:                    $unikey.='_'.$token->[2]->{'part'}; 
 2287: 	        }
 2288: 	      }
 2289:               if (defined($token->[2]->{'id'})) { 
 2290:                  $unikey.='_'.$token->[2]->{'id'}; 
 2291: 	      }
 2292: 
 2293:              if ($entry eq 'import') {
 2294: #
 2295: # Importing a library here
 2296: #                
 2297: 		 if (defined($depthcount)) { $depthcount++; } else 
 2298:                                            { $depthcount=0; }
 2299:                  if ($depthcount<20) {
 2300: 		     foreach (split(/\,/,&metadata($uri,'keys',
 2301:                                   $parser->get_text('/import'),$unikey,
 2302:                                   $depthcount))) {
 2303:                          $metathesekeys{$_}=1;
 2304: 		     }
 2305: 		 }
 2306:              } else { 
 2307: 
 2308:               if (defined($token->[2]->{'name'})) { 
 2309:                  $unikey.='_'.$token->[2]->{'name'}; 
 2310: 	      }
 2311:               $metathesekeys{$unikey}=1;
 2312:               foreach (@{$token->[3]}) {
 2313: 		  $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
 2314:               }
 2315:               unless (
 2316:                  $metacache{$uri.':'.$unikey}=$parser->get_text('/'.$entry)
 2317: 		      ) { $metacache{$uri.':'.$unikey}=
 2318: 			      $metacache{$uri.':'.$unikey.'.default'};
 2319: 		      }
 2320: # end of not-a-package not-a-library import
 2321: 	   }
 2322: # end of not-a-package start tag
 2323: 	  }
 2324: # the next is the end of "start tag"
 2325: 	 }
 2326:        }
 2327:        $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
 2328:        $metacache{$uri.':cachedtimestamp'}=time;
 2329: # this is the end of "was not already recently cached
 2330:     }
 2331:     return $metacache{$uri.':'.$what};
 2332: }
 2333: 
 2334: # ------------------------------------------------- Update symbolic store links
 2335: 
 2336: sub symblist {
 2337:     my ($mapname,%newhash)=@_;
 2338:     $mapname=declutter($mapname);
 2339:     my %hash;
 2340:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 2341:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 2342:                       &GDBM_WRCREAT,0640)) {
 2343: 	    foreach (keys %newhash) {
 2344:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
 2345:             }
 2346:             if (untie(%hash)) {
 2347: 		return 'ok';
 2348:             }
 2349:         }
 2350:     }
 2351:     return 'error';
 2352: }
 2353: 
 2354: # ------------------------------------------------------ Return symb list entry
 2355: 
 2356: sub symbread {
 2357:     my $thisfn=shift;
 2358:     unless ($thisfn) {
 2359:         if ($ENV{'request.symb'}) { return $ENV{'request.symb'}; }
 2360: 	$thisfn=$ENV{'request.filename'};
 2361:     }
 2362:     $thisfn=declutter($thisfn);
 2363:     my %hash;
 2364:     my %bighash;
 2365:     my $syval='';
 2366:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 2367:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 2368:                       &GDBM_READER,0640)) {
 2369: 	    $syval=$hash{$thisfn};
 2370:             untie(%hash);
 2371:         }
 2372: # ---------------------------------------------------------- There was an entry
 2373:         if ($syval) {
 2374:            unless ($syval=~/\_\d+$/) {
 2375: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 2376:                   &appenv('request.ambiguous' => $thisfn);
 2377:                   return '';
 2378:                }    
 2379:                $syval.=$1;
 2380: 	   }
 2381:         } else {
 2382: # ------------------------------------------------------- Was not in symb table
 2383:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 2384:                             &GDBM_READER,0640)) {
 2385: # ---------------------------------------------- Get ID(s) for current resource
 2386:               my $ids=$bighash{'ids_/res/'.$thisfn};
 2387:               unless ($ids) { 
 2388:                  $ids=$bighash{'ids_/'.$thisfn};
 2389:               }
 2390:               if ($ids) {
 2391: # ------------------------------------------------------------------- Has ID(s)
 2392:                  my @possibilities=split(/\,/,$ids);
 2393:                  if ($#possibilities==0) {
 2394: # ----------------------------------------------- There is only one possibility
 2395: 		     my ($mapid,$resid)=split(/\./,$ids);
 2396:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 2397:                  } else {
 2398: # ------------------------------------------ There is more than one possibility
 2399:                      my $realpossible=0;
 2400:                      foreach (@possibilities) {
 2401: 			 my $file=$bighash{'src_'.$_};
 2402:                          if (&allowed('bre',$file)) {
 2403:          		    my ($mapid,$resid)=split(/\./,$_);
 2404:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 2405: 				$realpossible++;
 2406:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 2407:                                        '___'.$resid;
 2408:                             }
 2409: 			 }
 2410:                      }
 2411: 		     if ($realpossible!=1) { $syval=''; }
 2412:                  }
 2413: 	      }
 2414:               untie(%bighash)
 2415:            } 
 2416:         }
 2417:         if ($syval) {
 2418:            return $syval.'___'.$thisfn; 
 2419:         }
 2420:     }
 2421:     &appenv('request.ambiguous' => $thisfn);
 2422:     return '';
 2423: }
 2424: 
 2425: # ---------------------------------------------------------- Return random seed
 2426: 
 2427: sub numval {
 2428:     my $txt=shift;
 2429:     $txt=~tr/A-J/0-9/;
 2430:     $txt=~tr/a-j/0-9/;
 2431:     $txt=~tr/K-T/0-9/;
 2432:     $txt=~tr/k-t/0-9/;
 2433:     $txt=~tr/U-Z/0-5/;
 2434:     $txt=~tr/u-z/0-5/;
 2435:     $txt=~s/\D//g;
 2436:     return int($txt);
 2437: }    
 2438: 
 2439: sub rndseed {
 2440:     my ($symb,$courseid,$domain,$username)=@_;
 2441:     if (!$symb) {
 2442:       unless ($symb=&symbread()) { return time; }
 2443:     }
 2444:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
 2445:     if (!$domain) {$domain=$ENV{'user.domain'};}
 2446:     if (!$username) {$username=$ENV{'user.name'};}
 2447:     {
 2448:       use integer;
 2449:       my $symbchck=unpack("%32C*",$symb) << 27;
 2450:       my $symbseed=numval($symb) << 22;
 2451:       my $namechck=unpack("%32C*",$username) << 17;
 2452:       my $nameseed=numval($username) << 12;
 2453:       my $domainseed=unpack("%32C*",$domain) << 7;
 2454:       my $courseseed=unpack("%32C*",$courseid);
 2455:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 2456:       #uncommenting these lines can break things!
 2457:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 2458:       #&Apache::lonxml::debug("rndseed :$num:$symb");
 2459:       return $num;
 2460:     }
 2461: }
 2462: 
 2463: sub ireceipt {
 2464:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
 2465:     my $cuname=unpack("%32C*",$funame);
 2466:     my $cudom=unpack("%32C*",$fudom);
 2467:     my $cucourseid=unpack("%32C*",$fucourseid);
 2468:     my $cusymb=unpack("%32C*",$fusymb);
 2469:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
 2470:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
 2471:            ($cunique%$cuname+
 2472:             $cunique%$cudom+
 2473:             $cusymb%$cuname+
 2474:             $cusymb%$cudom+
 2475:             $cucourseid%$cuname+
 2476:             $cucourseid%$cudom);
 2477: }
 2478: 
 2479: sub receipt {
 2480:     return &ireceipt($ENV{'user.name'},$ENV{'user.domain'},
 2481:                      $ENV{'request.course.id'},&symbread());
 2482: }
 2483:   
 2484: # ------------------------------------------------------------ Serves up a file
 2485: # returns either the contents of the file or a -1
 2486: sub getfile {
 2487:   my $file=shift;
 2488:   &repcopy($file);
 2489:   if (! -e $file ) { return -1; };
 2490:   my $fh=Apache::File->new($file);
 2491:   my $a='';
 2492:   while (<$fh>) { $a .=$_; }
 2493:   return $a
 2494: }
 2495: 
 2496: sub filelocation {
 2497:   my ($dir,$file) = @_;
 2498:   my $location;
 2499:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 2500:   if ($file=~m:^/~:) { # is a contruction space reference
 2501:     $location = $file;
 2502:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 2503:   } else {
 2504:     $file=~s/^$perlvar{'lonDocRoot'}//;
 2505:     $file=~s:^/*res::;
 2506:     if ( !( $file =~ m:^/:) ) {
 2507:       $location = $dir. '/'.$file;
 2508:     } else {
 2509:       $location = '/home/httpd/html/res'.$file;
 2510:     }
 2511:   }
 2512:   $location=~s://+:/:g; # remove duplicate /
 2513:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 2514:   return $location;
 2515: }
 2516: 
 2517: sub hreflocation {
 2518:     my ($dir,$file)=@_;
 2519:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
 2520:        my $finalpath=filelocation($dir,$file);
 2521:        $finalpath=~s/^\/home\/httpd\/html//;
 2522:        return $finalpath;
 2523:     } else {
 2524:        return $file;
 2525:     }
 2526: }
 2527: 
 2528: # ------------------------------------------------------------- Declutters URLs
 2529: 
 2530: sub declutter {
 2531:     my $thisfn=shift;
 2532:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 2533:     $thisfn=~s/^\///;
 2534:     $thisfn=~s/^res\///;
 2535:     return $thisfn;
 2536: }
 2537: 
 2538: # -------------------------------------------------------- Escape Special Chars
 2539: 
 2540: sub escape {
 2541:     my $str=shift;
 2542:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 2543:     return $str;
 2544: }
 2545: 
 2546: # ----------------------------------------------------- Un-Escape Special Chars
 2547: 
 2548: sub unescape {
 2549:     my $str=shift;
 2550:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2551:     return $str;
 2552: }
 2553: 
 2554: # ================================================================ Main Program
 2555: 
 2556: sub goodbye {
 2557:    &flushcourselogs();
 2558:    &logthis("Shutting down");
 2559: }
 2560: 
 2561: BEGIN {
 2562: # ------------------------------------------------------------ Read access.conf
 2563:     unless ($readit) {
 2564: {
 2565:     my $config=Apache::File->new("/etc/httpd/conf/access.conf");
 2566: 
 2567:     while (my $configline=<$config>) {
 2568:         if ($configline =~ /PerlSetVar/) {
 2569: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 2570:            chomp($varvalue);
 2571:            $perlvar{$varname}=$varvalue;
 2572:         }
 2573:     }
 2574: }
 2575: 
 2576: # ------------------------------------------------------------- Read hosts file
 2577: {
 2578:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
 2579: 
 2580:     while (my $configline=<$config>) {
 2581:        chomp($configline);
 2582:        my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
 2583:        $hostname{$id}=$name;
 2584:        $hostdom{$id}=$domain;
 2585:        $hostip{$id}=$ip;
 2586:        if ($role eq 'library') { $libserv{$id}=$name; }
 2587:     }
 2588: }
 2589: 
 2590: # ------------------------------------------------------ Read spare server file
 2591: {
 2592:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
 2593: 
 2594:     while (my $configline=<$config>) {
 2595:        chomp($configline);
 2596:        if (($configline) && ($configline ne $perlvar{'lonHostID'})) {
 2597:           $spareid{$configline}=1;
 2598:        }
 2599:     }
 2600: }
 2601: # ------------------------------------------------------------ Read permissions
 2602: {
 2603:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
 2604: 
 2605:     while (my $configline=<$config>) {
 2606:        chomp($configline);
 2607:       if ($configline) {
 2608:        my ($role,$perm)=split(/ /,$configline);
 2609:        if ($perm ne '') { $pr{$role}=$perm; }
 2610:       }
 2611:     }
 2612: }
 2613: 
 2614: # -------------------------------------------- Read plain texts for permissions
 2615: {
 2616:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
 2617: 
 2618:     while (my $configline=<$config>) {
 2619:        chomp($configline);
 2620:       if ($configline) {
 2621:        my ($short,$plain)=split(/:/,$configline);
 2622:        if ($plain ne '') { $prp{$short}=$plain; }
 2623:       }
 2624:     }
 2625: }
 2626: 
 2627: # ---------------------------------------------------------- Read package table
 2628: {
 2629:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
 2630: 
 2631:     while (my $configline=<$config>) {
 2632:        chomp($configline);
 2633:        my ($short,$plain)=split(/:/,$configline);
 2634:        my ($pack,$name)=split(/\&/,$short);
 2635:        if ($plain ne '') {
 2636:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
 2637:           $packagetab{$short}=$plain; 
 2638:        }
 2639:     }
 2640: }
 2641: 
 2642: %metacache=();
 2643: 
 2644: $processmarker=$$.'_'.time.'_'.$perlvar{'lonHostID'};
 2645: $dumpcount=0;
 2646: 
 2647: &logtouch();
 2648: &logthis('<font color=yellow>INFO: Read configuration</font>');
 2649: $readit=1;
 2650: }
 2651: }
 2652: 
 2653: 1;
 2654: __END__
 2655: 
 2656: =head1 NAME
 2657: 
 2658: Apache::lonnet - TCP networking package
 2659: 
 2660: =head1 SYNOPSIS
 2661: 
 2662: Invoked by other LON-CAPA modules.
 2663: 
 2664:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 2665: 
 2666: =head1 INTRODUCTION
 2667: 
 2668: This module provides subroutines which interact with the
 2669: lonc/lond (TCP) network layer of LON-CAPA.
 2670: 
 2671: This is part of the LearningOnline Network with CAPA project
 2672: described at http://www.lon-capa.org.
 2673: 
 2674: =head1 HANDLER SUBROUTINE
 2675: 
 2676: There is no handler routine for this module.
 2677: 
 2678: =head1 OTHER SUBROUTINES
 2679: 
 2680: =over 4
 2681: 
 2682: =item *
 2683: 
 2684: logtouch() : make sure the logfile, lonnet.log, exists
 2685: 
 2686: =item *
 2687: 
 2688: logthis() : append message to lonnet.log
 2689: 
 2690: =item *
 2691: 
 2692: logperm() : append a permanent message to lonnet.perm.log
 2693: 
 2694: =item *
 2695: 
 2696: subreply() : non-critical communication, called by &reply
 2697: 
 2698: =item *
 2699: 
 2700: reply() : makes two attempts to pass message; logs refusals and rejections
 2701: 
 2702: =item *
 2703: 
 2704: reconlonc() : tries to reconnect lonc client processes.
 2705: 
 2706: =item *
 2707: 
 2708: critical() : passes a critical message to another server; if cannot get
 2709: through then place message in connection buffer
 2710: 
 2711: =item *
 2712: 
 2713: appenv(%hash) : read in current user environment, append new environment
 2714: values to make new user environment
 2715: 
 2716: =item *
 2717: 
 2718: delenv($varname) : read in current user environment, remove all values
 2719: beginning with $varname, write new user environment (note: flock is used
 2720: to prevent conflicting shared read/writes with file)
 2721: 
 2722: =item *
 2723: 
 2724: spareserver() : find server with least workload from spare.tab
 2725: 
 2726: =item *
 2727: 
 2728: queryauthenticate($uname,$udom) : try to determine user's current
 2729: authentication scheme
 2730: 
 2731: =item *
 2732: 
 2733: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
 2734: servers (first use the current one)
 2735: 
 2736: =item *
 2737: 
 2738: homeserver($uname,$udom) : find the homebase for a user from domain's lib
 2739: servers
 2740: 
 2741: =item *
 2742: 
 2743: idget($udom,@ids) : find the usernames behind a list of IDs (returns hash:
 2744: id=>name,id=>name)
 2745: 
 2746: =item *
 2747: 
 2748: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
 2749: name=>id,name=>id)
 2750: 
 2751: =item *
 2752: 
 2753: idput($udom,%ids) : store away a list of names and associated IDs
 2754: 
 2755: =item *
 2756: 
 2757: usection($domain,$user,$courseid) : output of section name/number or '' for
 2758: "not in course" and '-1' for "no section"
 2759: 
 2760: =item *
 2761: 
 2762: userenvironment($domain,$user,$what) : puts out any environment parameter 
 2763: for a user
 2764: 
 2765: =item *
 2766: 
 2767: subscribe($fname) : subscribe to a resource, return URL if possible
 2768: 
 2769: =item *
 2770: 
 2771: repcopy($filename) : replicate file
 2772: 
 2773: =item *
 2774: 
 2775: ssi($url,%hash) : server side include, does a complete request cycle on url to
 2776: localhost, posts hash
 2777: 
 2778: =item *
 2779: 
 2780: log($domain,$name,$home,$message) : write to permanent log for user; use
 2781: critical subroutine
 2782: 
 2783: =item *
 2784: 
 2785: flushcourselogs() : flush (save) buffer logs and access logs
 2786: 
 2787: =item *
 2788: 
 2789: courselog($what) : save message for course in hash
 2790: 
 2791: =item *
 2792: 
 2793: courseacclog($what) : save message for course using &courselog().  Perform
 2794: special processing for specific resource types (problems, exams, quizzes, etc).
 2795: 
 2796: =item *
 2797: 
 2798: countacc($url) : count the number of accesses to a given URL
 2799: 
 2800: =item *
 2801: 
 2802: sub checkout($symb,$tuname,$tudom,$tcrsid) : check out an item
 2803: 
 2804: =item *
 2805: 
 2806: sub checkin($token) : check in an item
 2807: 
 2808: =item *
 2809: 
 2810: sub expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 2811: 
 2812: =item *
 2813: 
 2814: devalidate($symb) : devalidate spreadsheets
 2815: 
 2816: =item *
 2817: 
 2818: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 2819: and '&' separators
 2820: 
 2821: =item *
 2822: 
 2823: str2hash($string) : convert string to hash using unescaping and splitting on
 2824: '=' and '&'
 2825: 
 2826: =item *
 2827: 
 2828: tmpreset($symb,$namespace,$domain,$stuname) : temporary storage
 2829: 
 2830: =item *
 2831: 
 2832: tmprestore($symb,$namespace,$domain,$stuname) : temporary restore
 2833: 
 2834: =item *
 2835: 
 2836: store($storehash,$symb,$namespace,$domain,$stuname) : stores hash permanently
 2837: for this url; hashref needs to be given and should be a \%hashname; the
 2838: remaining args aren't required and if they aren't passed or are '' they will
 2839: be derived from the ENV
 2840: 
 2841: =item *
 2842: 
 2843: cstore($storehash,$symb,$namespace,$domain,$stuname) : same as store but
 2844: uses critical subroutine
 2845: 
 2846: =item *
 2847: 
 2848: restore($symb,$namespace,$domain,$stuname) : returns hash for this symb;
 2849: all args are optional
 2850: 
 2851: =item *
 2852: 
 2853: coursedescription($courseid) : course description
 2854: 
 2855: =item *
 2856: 
 2857: rolesinit($domain,$username,$authhost) : get user privileges
 2858: 
 2859: =item *
 2860: 
 2861: get($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
 2862: reference filled in from namesp ($udomain and $uname are optional)
 2863: 
 2864: =item *
 2865: 
 2866: del($namespace,$storearr,$udomain,$uname) : deletes keys out of array from
 2867: namesp ($udomain and $uname are optional)
 2868: 
 2869: =item *
 2870: 
 2871: dump($namespace,$udomain,$uname,$regexp) : 
 2872: dumps the complete (or key matching regexp) namespace into a hash
 2873: ($udomain, $uname and $regexp are optional)
 2874: 
 2875: =item *
 2876: 
 2877: put($namespace,$storehash,$udomain,$uname) : stores hash in namesp
 2878: ($udomain and $uname are optional)
 2879: 
 2880: =item *
 2881: 
 2882: cput($namespace,$storehash,$udomain,$uname) : critical put
 2883: ($udomain and $uname are optional)
 2884: 
 2885: =item *
 2886: 
 2887: eget($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
 2888: reference filled in from namesp (encrypts the return communication)
 2889: ($udomain and $uname are optional)
 2890: 
 2891: =item *
 2892: 
 2893: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 2894: actions
 2895:  F: full access
 2896:  U,I,K: authentication modes (cxx only)
 2897:  '': forbidden
 2898:  1: user needs to choose course
 2899:  2: browse allowed
 2900: 
 2901: =item *
 2902: 
 2903: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 2904: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 2905: and course level
 2906: 
 2907: =item *
 2908: 
 2909: metadata_query($query,$custom,$customshow) : make a metadata query against the
 2910: network of library servers; returns file handle of where SQL and regex results
 2911: will be stored for query
 2912: 
 2913: =item *
 2914: 
 2915: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 2916: explanation of a user role term
 2917: 
 2918: =item *
 2919: 
 2920: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 2921: user for the level given by URL.  Optional start and end dates (leave empty
 2922: string or zero for "no date")
 2923: 
 2924: =item *
 2925: 
 2926: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 2927: 
 2928: =item *
 2929: 
 2930: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 2931: modify user
 2932: 
 2933: =item *
 2934: 
 2935: modifystudent($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 2936: $end,$start) : modify student
 2937: 
 2938: =item *
 2939: 
 2940: writecoursepref($courseid,%prefs) : write preferences for a course
 2941: 
 2942: =item *
 2943: 
 2944: createcourse($udom,$description,$url) : make/modify course
 2945: 
 2946: =item *
 2947: 
 2948: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 2949: custom role; give a custom role to a user for the level given by URL.  Specify
 2950: name and domain of role author, and role name
 2951: 
 2952: =item *
 2953: 
 2954: revokerole($udom,$uname,$url,$role) : revoke a role for url
 2955: 
 2956: =item *
 2957: 
 2958: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 2959: 
 2960: =item *
 2961: 
 2962: dirlist($uri) : return directory list based on URI
 2963: 
 2964: =item *
 2965: 
 2966: directcondval($number) : get current value of a condition; reads from a state
 2967: string
 2968: 
 2969: =item *
 2970: 
 2971: condval($condidx) : value of condition index based on state
 2972: 
 2973: =item *
 2974: 
 2975: EXT($varname,$symbparm) : value of a variable
 2976: 
 2977: =item *
 2978: 
 2979: metadata($uri,$what,$liburi,$prefix,$depthcount) : get metadata; returns the
 2980: metadata entry for a file; entry='keys', returns a comma separated list of keys
 2981: 
 2982: =item *
 2983: 
 2984: symblist($mapname,%newhash) : update symbolic storage links
 2985: 
 2986: =item *
 2987: 
 2988: symbread($filename) : return symbolic list entry (filename argument optional);
 2989: returns the data handle
 2990: 
 2991: =item *
 2992: 
 2993: numval($salt) : return random seed value (addend for rndseed)
 2994: 
 2995: =item *
 2996: 
 2997: rndseed($symb,$courseid,$domain,$username) : create a random sum; returns
 2998: a random seed, all arguments are optional, if they aren't sent it uses the
 2999: environment to derive them. Note: if symb isn't sent and it can't get one
 3000: from &symbread it will use the current time as its return value
 3001: 
 3002: =item *
 3003: 
 3004: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 3005: unfakeable, receipt
 3006: 
 3007: =item *
 3008: 
 3009: receipt() : API to ireceipt working off of ENV values; given out to users
 3010: 
 3011: =item *
 3012: 
 3013: getfile($file) : serves up a file, returns the contents of a file or -1;
 3014: replicates and subscribes to the file
 3015: 
 3016: =item *
 3017: 
 3018: filelocation($dir,$file) : returns file system location of a file based on URI;
 3019: meant to be "fairly clean" absolute reference
 3020: 
 3021: =item *
 3022: 
 3023: hreflocation($dir,$file) : returns file system location or a URL; same as
 3024: filelocation except for hrefs
 3025: 
 3026: =item *
 3027: 
 3028: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 3029: 
 3030: =item *
 3031: 
 3032: escape() : unpack non-word characters into CGI-compatible hex codes
 3033: 
 3034: =item *
 3035: 
 3036: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 3037: 
 3038: =item *
 3039: 
 3040: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 3041: as a PerlChildExitHandler
 3042: 
 3043: =back
 3044: 
 3045: =cut

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