File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.192: download - view: text, annotated - select for diffs
Fri Dec 21 17:02:35 2001 UTC (22 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Debug log of POSTs, remove extra filetypes-read (should be in loncommon now)

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

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