File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.194: download - view: text, annotated - select for diffs
Thu Dec 27 17:00:30 2001 UTC (22 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Set "course preference roles denied" and bugfix in lonnet.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.194 2001/12/27 17:00:30 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
   29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
   30: # 11/8,11/16,11/18,11/22,11/23,12/22,
   31: # 01/06,01/13,02/24,02/28,02/29,
   32: # 03/01,03/02,03/06,03/07,03/13,
   33: # 04/05,05/29,05/31,06/01,
   34: # 06/05,06/26 Gerd Kortemeyer
   35: # 06/26 Ben Tyszka
   36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
   37: # 08/14 Ben Tyszka
   38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
   39: # 10/04 Gerd Kortemeyer
   40: # 10/04 Guy Albertelli
   41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
   42: # 10/30,10/31,
   43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
   44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
   45: # 05/01/01 Guy Albertelli
   46: # 05/01,06/01,09/01 Gerd Kortemeyer
   47: # 09/01 Guy Albertelli
   48: # 09/01,10/01,11/01 Gerd Kortemeyer
   49: # YEAR=2001
   50: # 02/27/01 Scott Harrison
   51: # 3/2 Gerd Kortemeyer
   52: # 3/15,3/19 Scott Harrison
   53: # 3/19,3/20 Gerd Kortemeyer
   54: # 3/22,3/27,4/2,4/16,4/17 Scott Harrison
   55: # 5/26,5/28 Gerd Kortemeyer
   56: # 5/30 H. K. Ng
   57: # 6/1 Gerd Kortemeyer
   58: # July Guy Albertelli
   59: # 8/4,8/7,8/8,8/9,8/11,8/16,8/17,8/18,8/20,8/23,9/20,9/21,9/26,
   60: # 10/2 Gerd Kortemeyer
   61: # 10/5,10/10,11/13,11/15 Scott Harrison
   62: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
   63: # 12/5 Matthew Hall
   64: # 12/5 Guy Albertelli
   65: # 12/6,12/7,12/12 Gerd Kortemeyer
   66: # 12/18 Scott Harrison
   67: # 12/21,12/22,12/27 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,$regexp)=@_;
 1278:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1279:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1280:    my $uhome=&homeserver($uname,$udomain);
 1281:    if ($regexp) {
 1282:        $regexp=&escape($regexp);
 1283:    } else {
 1284:        $regexp='.';
 1285:    }
 1286:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 1287:    my @pairs=split(/\&/,$rep);
 1288:    my %returnhash=();
 1289:    foreach (@pairs) {
 1290:       my ($key,$value)=split(/=/,$_);
 1291:       $returnhash{unescape($key)}=unescape($value);
 1292:    }
 1293:    return %returnhash;
 1294: }
 1295: 
 1296: # --------------------------------------------------------------- put interface
 1297: 
 1298: sub put {
 1299:    my ($namespace,$storehash,$udomain,$uname)=@_;
 1300:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1301:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1302:    my $uhome=&homeserver($uname,$udomain);
 1303:    my $items='';
 1304:    foreach (keys %$storehash) {
 1305:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
 1306:    }
 1307:    $items=~s/\&$//;
 1308:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 1309: }
 1310: 
 1311: # ------------------------------------------------------ critical put interface
 1312: 
 1313: sub cput {
 1314:    my ($namespace,$storehash,$udomain,$uname)=@_;
 1315:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1316:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1317:    my $uhome=&homeserver($uname,$udomain);
 1318:    my $items='';
 1319:    foreach (keys %$storehash) {
 1320:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
 1321:    }
 1322:    $items=~s/\&$//;
 1323:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 1324: }
 1325: 
 1326: # -------------------------------------------------------------- eget interface
 1327: 
 1328: sub eget {
 1329:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1330:    my $items='';
 1331:    foreach (@$storearr) {
 1332:        $items.=escape($_).'&';
 1333:    }
 1334:    $items=~s/\&$//;
 1335:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1336:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1337:    my $uhome=&homeserver($uname,$udomain);
 1338:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 1339:    my @pairs=split(/\&/,$rep);
 1340:    my %returnhash=();
 1341:    my $i=0;
 1342:    foreach (@$storearr) {
 1343:       $returnhash{$_}=unescape($pairs[$i]);
 1344:       $i++;
 1345:    }
 1346:    return %returnhash;
 1347: }
 1348: 
 1349: # ------------------------------------------------- Check for a user privilege
 1350: 
 1351: sub allowed {
 1352:     my ($priv,$uri)=@_;
 1353: 
 1354:     my $orguri=$uri;
 1355:     $uri=&declutter($uri);
 1356: 
 1357: # Free bre access to adm and meta resources
 1358: 
 1359:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 1360: 	return 'F';
 1361:     }
 1362: 
 1363: # Free bre to public access
 1364: 
 1365:     if ($priv eq 'bre') {
 1366: 	if (&metadata($uri,'copyright') eq 'public') { return 'F'; }
 1367:     }
 1368: 
 1369:     my $thisallowed='';
 1370:     my $statecond=0;
 1371:     my $courseprivid='';
 1372: 
 1373: # Course
 1374: 
 1375:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
 1376:        $thisallowed.=$1;
 1377:     }
 1378: 
 1379: # Domain
 1380: 
 1381:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 1382:        =~/$priv\&([^\:]*)/) {
 1383:        $thisallowed.=$1;
 1384:     }
 1385: 
 1386: # Course: uri itself is a course
 1387:     my $courseuri=$uri;
 1388:     $courseuri=~s/\_(\d)/\/$1/;
 1389:     $courseuri=~s/^([^\/])/\/$1/;
 1390: 
 1391:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 1392:        =~/$priv\&([^\:]*)/) {
 1393:        $thisallowed.=$1;
 1394:     }
 1395: 
 1396: # Full access at system, domain or course-wide level? Exit.
 1397: 
 1398:     if ($thisallowed=~/F/) {
 1399: 	return 'F';
 1400:     }
 1401: 
 1402: # If this is generating or modifying users, exit with special codes
 1403: 
 1404:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
 1405: 	return $thisallowed;
 1406:     }
 1407: #
 1408: # Gathered so far: system, domain and course wide privileges
 1409: #
 1410: # Course: See if uri or referer is an individual resource that is part of 
 1411: # the course
 1412: 
 1413:     if ($ENV{'request.course.id'}) {
 1414:        $courseprivid=$ENV{'request.course.id'};
 1415:        if ($ENV{'request.course.sec'}) {
 1416:           $courseprivid.='/'.$ENV{'request.course.sec'};
 1417:        }
 1418:        $courseprivid=~s/\_/\//;
 1419:        my $checkreferer=1;
 1420:        my @uriparts=split(/\//,$uri);
 1421:        my $filename=$uriparts[$#uriparts];
 1422:        my $pathname=$uri;
 1423:        $pathname=~s/\/$filename$//;
 1424:        if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 1425:            /\&$filename\:([\d\|]+)\&/) {
 1426:            $statecond=$1;
 1427:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 1428:                =~/$priv\&([^\:]*)/) {
 1429:                $thisallowed.=$1;
 1430:                $checkreferer=0;
 1431:            }
 1432:        }
 1433:        
 1434:        if ($checkreferer) {
 1435: 	  my $refuri=$ENV{'httpref.'.$orguri};
 1436: 
 1437:             unless ($refuri) {
 1438:                 foreach (keys %ENV) {
 1439: 		    if ($_=~/^httpref\..*\*/) {
 1440: 			my $pattern=$_;
 1441:                         $pattern=~s/^httpref\.\/res\///;
 1442:                         $pattern=~s/\*/\[\^\/\]\+/g;
 1443:                         $pattern=~s/\//\\\//g;
 1444:                         if ($orguri=~/$pattern/) {
 1445: 			    $refuri=$ENV{$_};
 1446:                         }
 1447:                     }
 1448:                 }
 1449:             }
 1450:          if ($refuri) { 
 1451: 	  $refuri=&declutter($refuri);
 1452:           my @uriparts=split(/\//,$refuri);
 1453:           my $filename=$uriparts[$#uriparts];
 1454:           my $pathname=$refuri;
 1455:           $pathname=~s/\/$filename$//;
 1456:             if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 1457:               /\&$filename\:([\d\|]+)\&/) {
 1458:               my $refstatecond=$1;
 1459:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 1460:                   =~/$priv\&([^\:]*)/) {
 1461:                   $thisallowed.=$1;
 1462:                   $uri=$refuri;
 1463:                   $statecond=$refstatecond;
 1464:               }
 1465:           }
 1466:         }
 1467:        }
 1468:    }
 1469: 
 1470: #
 1471: # Gathered now: all privileges that could apply, and condition number
 1472: # 
 1473: #
 1474: # Full or no access?
 1475: #
 1476: 
 1477:     if ($thisallowed=~/F/) {
 1478: 	return 'F';
 1479:     }
 1480: 
 1481:     unless ($thisallowed) {
 1482:         return '';
 1483:     }
 1484: 
 1485: # Restrictions exist, deal with them
 1486: #
 1487: #   C:according to course preferences
 1488: #   R:according to resource settings
 1489: #   L:unless locked
 1490: #   X:according to user session state
 1491: #
 1492: 
 1493: # Possibly locked functionality, check all courses
 1494: # Locks might take effect only after 10 minutes cache expiration for other
 1495: # courses, and 2 minutes for current course
 1496: 
 1497:     my $envkey;
 1498:     if ($thisallowed=~/L/) {
 1499:         foreach $envkey (keys %ENV) {
 1500:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 1501:                my $courseid=$2;
 1502:                my $roleid=$1.'.'.$2;
 1503:                $courseid=~s/^\///;
 1504:                my $expiretime=600;
 1505:                if ($ENV{'request.role'} eq $roleid) {
 1506: 		  $expiretime=120;
 1507:                }
 1508: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 1509:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 1510:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 1511: 		   &coursedescription($courseid);
 1512:                }
 1513:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
 1514:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 1515: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 1516:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 1517:                             $ENV{'user.host'},
 1518:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 1519:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 1520:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 1521: 		       return '';
 1522:                    }
 1523:                }
 1524:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
 1525:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 1526: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 1527:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 1528:                             $ENV{'user.host'},
 1529:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 1530:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 1531:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 1532: 		       return '';
 1533:                    }
 1534:                }
 1535: 	   }
 1536:        }
 1537:     }
 1538:    
 1539: #
 1540: # Rest of the restrictions depend on selected course
 1541: #
 1542: 
 1543:     unless ($ENV{'request.course.id'}) {
 1544:        return '1';
 1545:     }
 1546: 
 1547: #
 1548: # Now user is definitely in a course
 1549: #
 1550: 
 1551: 
 1552: # Course preferences
 1553: 
 1554:    if ($thisallowed=~/C/) {
 1555:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 1556:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 1557: 	   =~/$rolecode/) {
 1558:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 1559:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 1560:                 $ENV{'request.course.id'});
 1561:            return '';
 1562:        }
 1563:    }
 1564: 
 1565: # Resource preferences
 1566: 
 1567:    if ($thisallowed=~/R/) {
 1568:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 1569:        my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
 1570:        if (-e $filename) {
 1571:            my @content;
 1572:            {
 1573: 	     my $fh=Apache::File->new($filename);
 1574:              @content=<$fh>;
 1575: 	   }
 1576:            if (join('',@content)=~
 1577:                     /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
 1578: 	       &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 1579:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 1580:            return '';
 1581: 
 1582:            }
 1583:        }
 1584:    }
 1585: 
 1586: # Restricted by state?
 1587: 
 1588:    if ($thisallowed=~/X/) {
 1589:       if (&condval($statecond)) {
 1590: 	 return '2';
 1591:       } else {
 1592:          return '';
 1593:       }
 1594:    }
 1595: 
 1596:    return 'F';
 1597: }
 1598: 
 1599: # ----------------------------------------------------------------- Define Role
 1600: 
 1601: sub definerole {
 1602:   if (allowed('mcr','/')) {
 1603:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 1604:     foreach (split('/',$sysrole)) {
 1605: 	my ($crole,$cqual)=split(/\&/,$_);
 1606:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
 1607:         if ($pr{'cr:s'}=~/$crole\&/) {
 1608: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
 1609:                return "refused:s:$crole&$cqual"; 
 1610:             }
 1611:         }
 1612:     }
 1613:     foreach (split('/',$domrole)) {
 1614: 	my ($crole,$cqual)=split(/\&/,$_);
 1615:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
 1616:         if ($pr{'cr:d'}=~/$crole\&/) {
 1617: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
 1618:                return "refused:d:$crole&$cqual"; 
 1619:             }
 1620:         }
 1621:     }
 1622:     foreach (split('/',$courole)) {
 1623: 	my ($crole,$cqual)=split(/\&/,$_);
 1624:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
 1625:         if ($pr{'cr:c'}=~/$crole\&/) {
 1626: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
 1627:                return "refused:c:$crole&$cqual"; 
 1628:             }
 1629:         }
 1630:     }
 1631:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 1632:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 1633: 	        "rolesdef_$rolename=".
 1634:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 1635:     return reply($command,$ENV{'user.home'});
 1636:   } else {
 1637:     return 'refused';
 1638:   }
 1639: }
 1640: 
 1641: # ---------------- Make a metadata query against the network of library servers
 1642: 
 1643: sub metadata_query {
 1644:     my ($query,$custom,$customshow)=@_;
 1645:     my %rhash;
 1646:     for my $server (keys %libserv) {
 1647: 	unless ($custom or $customshow) {
 1648: 	    my $reply=&reply("querysend:".&escape($query),$server);
 1649: 	    $rhash{$server}=$reply;
 1650: 	}
 1651: 	else {
 1652: 	    my $reply=&reply("querysend:".&escape($query).':'.
 1653: 			     &escape($custom).':'.&escape($customshow),
 1654: 			     $server);
 1655: 	    $rhash{$server}=$reply;
 1656: 	}
 1657:     }
 1658:     return \%rhash;
 1659: }
 1660: 
 1661: # ------------------------------------------------------------------ Plain Text
 1662: 
 1663: sub plaintext {
 1664:     my $short=shift;
 1665:     return $prp{$short};
 1666: }
 1667: 
 1668: # ----------------------------------------------------------------- Assign Role
 1669: 
 1670: sub assignrole {
 1671:     my ($udom,$uname,$url,$role,$end,$start)=@_;
 1672:     my $mrole;
 1673:     if ($role =~ /^cr\//) {
 1674: 	unless (&allowed('ccr',$url)) {
 1675:            &logthis('Refused custom assignrole: '.
 1676:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 1677: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 1678:            return 'refused'; 
 1679:         }
 1680:         $mrole='cr';
 1681:     } else {
 1682:         my $cwosec=$url;
 1683:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 1684:         unless (&allowed('c'.$role,$cwosec)) { 
 1685:            &logthis('Refused assignrole: '.
 1686:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 1687: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 1688:            return 'refused'; 
 1689:         }
 1690:         $mrole=$role;
 1691:     }
 1692:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 1693:                 "$udom:$uname:$url".'_'."$mrole=$role";
 1694:     if ($end) { $command.='_'.$end; }
 1695:     if ($start) {
 1696: 	if ($end) { 
 1697:            $command.='_'.$start; 
 1698:         } else {
 1699:            $command.='_0_'.$start;
 1700:         }
 1701:     }
 1702:     return &reply($command,&homeserver($uname,$udom));
 1703: }
 1704: 
 1705: # -------------------------------------------------- Modify user authentication
 1706: sub modifyuserauth {
 1707:     my ($udom,$uname,$umode,$upass)=@_;
 1708:     my $uhome=&homeserver($uname,$udom);
 1709:     &logthis('Call to modify user authentication'.$udom.', '.$uname.', '.
 1710:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'});  
 1711:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 1712: 		     &escape($upass),$uhome);
 1713:     unless ($reply eq 'ok') {
 1714: 	return 'error: '.$reply;
 1715:     }   
 1716:     return 'ok';
 1717: }
 1718: 
 1719: # --------------------------------------------------------------- Modify a user
 1720: 
 1721: 
 1722: sub modifyuser {
 1723:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene)=@_;
 1724:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 1725:              $umode.', '.$first.', '.$middle.', '.
 1726: 	     $last.', '.$gene.' by '.
 1727:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});  
 1728:     my $uhome=&homeserver($uname,$udom);
 1729: # ----------------------------------------------------------------- Create User
 1730:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
 1731:         my $unhome='';
 1732: 	if ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 1733: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1734:         } else {
 1735:             my $tryserver;
 1736:             my $loadm=10000000;
 1737:             foreach $tryserver (keys %libserv) {
 1738: 	       if ($hostdom{$tryserver} eq $udom) {
 1739:                   my $answer=reply('load',$tryserver);
 1740:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 1741: 		      $loadm=$answer;
 1742:                       $unhome=$tryserver;
 1743:                   }
 1744: 	       }
 1745: 	    }
 1746:         }
 1747:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 1748: 	    return 'error: find home';
 1749:         }
 1750:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 1751:                          &escape($upass),$unhome);
 1752: 	unless ($reply eq 'ok') {
 1753:             return 'error: '.$reply;
 1754:         }   
 1755:         $uhome=&homeserver($uname,$udom);
 1756:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 1757: 	    return 'error: verify home';
 1758:         }
 1759:     }
 1760: # ---------------------------------------------------------------------- Add ID
 1761:     if ($uid) {
 1762:        $uid=~tr/A-Z/a-z/;
 1763:        my %uidhash=&idrget($udom,$uname);
 1764:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)) {
 1765: 	  unless ($uid eq $uidhash{$uname}) {
 1766: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
 1767:           }
 1768:        } else {
 1769: 	  &idput($udom,($uname => $uid));
 1770:        }
 1771:     }
 1772: # -------------------------------------------------------------- Add names, etc
 1773:     my %names=&get('environment',
 1774: 		   ['firstname','middlename','lastname','generation'],
 1775: 		   $udom,$uname);
 1776:     if ($first)  { $names{'firstname'}  = $first; }
 1777:     if ($middle) { $names{'middlename'} = $middle; }
 1778:     if ($last)   { $names{'lastname'}   = $last; }
 1779:     if ($gene)   { $names{'generation'} = $gene; }
 1780:     my $reply = &put('environment', \%names, $udom,$uname);
 1781:     if ($reply ne 'ok') { return 'error: '.$reply; }
 1782:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 1783:              $umode.', '.$first.', '.$middle.', '.
 1784: 	     $last.', '.$gene.' by '.
 1785:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 1786:     return 'ok';
 1787: }
 1788: 
 1789: # -------------------------------------------------------------- Modify student
 1790: 
 1791: sub modifystudent {
 1792:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 1793:         $end,$start)=@_;
 1794:     my $cid='';
 1795:     unless ($cid=$ENV{'request.course.id'}) {
 1796: 	return 'not_in_class';
 1797:     }
 1798: # --------------------------------------------------------------- Make the user
 1799:     my $reply=&modifyuser
 1800: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene);
 1801:     unless ($reply eq 'ok') { return $reply; }
 1802:     my $uhome=&homeserver($uname,$udom);
 1803:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 1804: 	return 'error: no such user';
 1805:     }
 1806: # -------------------------------------------------- Add student to course list
 1807:     $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 1808: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
 1809:                       &escape($uname.':'.$udom).'='.
 1810:                       &escape($end.':'.$start),
 1811: 	              $ENV{'course.'.$cid.'.home'});
 1812:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 1813: 	return 'error: '.$reply;
 1814:     }
 1815: # ---------------------------------------------------- Add student role to user
 1816:     my $uurl='/'.$cid;
 1817:     $uurl=~s/\_/\//g;
 1818:     if ($usec) {
 1819: 	$uurl.='/'.$usec;
 1820:     }
 1821:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 1822: }
 1823: 
 1824: # ------------------------------------------------- Write to course preferences
 1825: 
 1826: sub writecoursepref {
 1827:     my ($courseid,%prefs)=@_;
 1828:     $courseid=~s/^\///;
 1829:     $courseid=~s/\_/\//g;
 1830:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1831:     my $chome=homeserver($cnum,$cdomain);
 1832:     if (($chome eq '') || ($chome eq 'no_host')) { 
 1833: 	return 'error: no such course';
 1834:     }
 1835:     my $cstring='';
 1836:     foreach (keys %prefs) {
 1837: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 1838:     }
 1839:     $cstring=~s/\&$//;
 1840:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 1841: }
 1842: 
 1843: # ---------------------------------------------------------- Make/modify course
 1844: 
 1845: sub createcourse {
 1846:     my ($udom,$description,$url)=@_;
 1847:     $url=&declutter($url);
 1848:     my $cid='';
 1849:     unless (&allowed('ccc',$ENV{'user.domain'})) {
 1850:         return 'refused';
 1851:     }
 1852:     unless ($udom eq $ENV{'user.domain'}) {
 1853:         return 'refused';
 1854:     }
 1855: # ------------------------------------------------------------------- Create ID
 1856:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 1857:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 1858: # ----------------------------------------------- Make sure that does not exist
 1859:    my $uhome=&homeserver($uname,$udom);
 1860:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 1861:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 1862:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 1863:        $uhome=&homeserver($uname,$udom);       
 1864:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 1865:            return 'error: unable to generate unique course-ID';
 1866:        } 
 1867:    }
 1868: # ------------------------------------------------------------- Make the course
 1869:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 1870:                       $ENV{'user.home'});
 1871:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 1872:     $uhome=&homeserver($uname,$udom);
 1873:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 1874: 	return 'error: no such course';
 1875:     }
 1876:     &writecoursepref($udom.'_'.$uname,
 1877:                      ('description' => $description,
 1878:                       'url'         => $url));
 1879:     return '/'.$udom.'/'.$uname;
 1880: }
 1881: 
 1882: # ---------------------------------------------------------- Assign Custom Role
 1883: 
 1884: sub assigncustomrole {
 1885:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
 1886:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 1887:                        $end,$start);
 1888: }
 1889: 
 1890: # ----------------------------------------------------------------- Revoke Role
 1891: 
 1892: sub revokerole {
 1893:     my ($udom,$uname,$url,$role)=@_;
 1894:     my $now=time;
 1895:     return &assignrole($udom,$uname,$url,$role,$now);
 1896: }
 1897: 
 1898: # ---------------------------------------------------------- Revoke Custom Role
 1899: 
 1900: sub revokecustomrole {
 1901:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
 1902:     my $now=time;
 1903:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
 1904: }
 1905: 
 1906: # ------------------------------------------------------------ Directory lister
 1907: 
 1908: sub dirlist {
 1909:     my $uri=shift;
 1910:     $uri=~s/^\///;
 1911:     $uri=~s/\/$//;
 1912:     my ($res,$udom,$uname,@rest)=split(/\//,$uri);
 1913:     if ($udom) {
 1914:      if ($uname) {
 1915:        my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/'.$uri,
 1916:                       homeserver($uname,$udom));
 1917:        return split(/:/,$listing);
 1918:      } else {
 1919:        my $tryserver;
 1920:        my %allusers=();
 1921:        foreach $tryserver (keys %libserv) {
 1922: 	  if ($hostdom{$tryserver} eq $udom) {
 1923:              my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.$udom,
 1924: 			       $tryserver);
 1925:              if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 1926:               && ($listing ne 'con_lost')) {
 1927:                 foreach (split(/:/,$listing)) {
 1928:                   my ($entry,@stat)=split(/&/,$_);
 1929:                   $allusers{$entry}=1;
 1930:                 }
 1931:              }
 1932: 	  }
 1933:        }
 1934:        my $alluserstr='';
 1935:        foreach (sort keys %allusers) {
 1936:            $alluserstr.=$_.'&user:';
 1937:        }
 1938:        $alluserstr=~s/:$//;
 1939:        return split(/:/,$alluserstr);
 1940:      } 
 1941:    } else {
 1942:        my $tryserver;
 1943:        my %alldom=();
 1944:        foreach $tryserver (keys %libserv) {
 1945: 	   $alldom{$hostdom{$tryserver}}=1;
 1946:        }
 1947:        my $alldomstr='';
 1948:        foreach (sort keys %alldom) {
 1949:           $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
 1950:        }
 1951:        $alldomstr=~s/:$//;
 1952:        return split(/:/,$alldomstr);       
 1953:    }
 1954: }
 1955: 
 1956: # -------------------------------------------------------- Value of a Condition
 1957: 
 1958: sub directcondval {
 1959:     my $number=shift;
 1960:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 1961:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 1962:     } else {
 1963:        return 2;
 1964:     }
 1965: }
 1966: 
 1967: sub condval {
 1968:     my $condidx=shift;
 1969:     my $result=0;
 1970:     my $allpathcond='';
 1971:     foreach (split(/\|/,$condidx)) {
 1972:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 1973: 	   $allpathcond.=
 1974:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 1975:        }
 1976:     }
 1977:     $allpathcond=~s/\|$//;
 1978:     if ($ENV{'request.course.id'}) {
 1979:        if ($allpathcond) {
 1980:           my $operand='|';
 1981: 	  my @stack;
 1982:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 1983:               if ($_ eq '(') {
 1984:                  push @stack,($operand,$result)
 1985:               } elsif ($_ eq ')') {
 1986:                   my $before=pop @stack;
 1987: 		  if (pop @stack eq '&') {
 1988: 		      $result=$result>$before?$before:$result;
 1989:                   } else {
 1990:                       $result=$result>$before?$result:$before;
 1991:                   }
 1992:               } elsif (($_ eq '&') || ($_ eq '|')) {
 1993:                   $operand=$_;
 1994:               } else {
 1995:                   my $new=directcondval($_);
 1996:                   if ($operand eq '&') {
 1997:                      $result=$result>$new?$new:$result;
 1998:                   } else {
 1999:                      $result=$result>$new?$result:$new;
 2000:                   }
 2001:               }
 2002:           }
 2003:        }
 2004:     }
 2005:     return $result;
 2006: }
 2007: 
 2008: # --------------------------------------------------------- Value of a Variable
 2009: 
 2010: sub EXT {
 2011:     my ($varname,$symbparm)=@_;
 2012:     unless ($varname) { return ''; }
 2013:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 2014:     my $rest;
 2015:     if ($therest[0]) {
 2016:        $rest=join('.',@therest);
 2017:     } else {
 2018:        $rest='';
 2019:     }
 2020:     my $qualifierrest=$qualifier;
 2021:     if ($rest) { $qualifierrest.='.'.$rest; }
 2022:     my $spacequalifierrest=$space;
 2023:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 2024:     if ($realm eq 'user') {
 2025: # --------------------------------------------------------------- user.resource
 2026: 	if ($space eq 'resource') {
 2027: 	    my %restored=&restore();
 2028:             return $restored{$qualifierrest};
 2029: # ----------------------------------------------------------------- user.access
 2030:         } elsif ($space eq 'access') {
 2031:             return &allowed($qualifier,$rest);
 2032: # ------------------------------------------ user.preferences, user.environment
 2033:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 2034:             return $ENV{join('.',('environment',$qualifierrest))};
 2035: # ----------------------------------------------------------------- user.course
 2036:         } elsif ($space eq 'course') {
 2037:             return $ENV{join('.',('request.course',$qualifier))};
 2038: # ------------------------------------------------------------------- user.role
 2039:         } elsif ($space eq 'role') {
 2040:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 2041:             if ($qualifier eq 'value') {
 2042: 		return $role;
 2043:             } elsif ($qualifier eq 'extent') {
 2044:                 return $where;
 2045:             }
 2046: # ----------------------------------------------------------------- user.domain
 2047:         } elsif ($space eq 'domain') {
 2048:             return $ENV{'user.domain'};
 2049: # ------------------------------------------------------------------- user.name
 2050:         } elsif ($space eq 'name') {
 2051:             return $ENV{'user.name'};
 2052: # ---------------------------------------------------- Any other user namespace
 2053:         } else {
 2054:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
 2055:             my %reply=&get($space,[$item]);
 2056:             return $reply{$item};
 2057:         }
 2058:     } elsif ($realm eq 'request') {
 2059: # ------------------------------------------------------------- request.browser
 2060:         if ($space eq 'browser') {
 2061: 	    return $ENV{'browser.'.$qualifier};
 2062: # ------------------------------------------------------------ request.filename
 2063:         } else {
 2064:             return $ENV{'request.'.$spacequalifierrest};
 2065:         }
 2066:     } elsif ($realm eq 'course') {
 2067: # ---------------------------------------------------------- course.description
 2068:         return $ENV{'course.'.$ENV{'request.course.id'}.'.'.
 2069:                               $spacequalifierrest};
 2070:     } elsif ($realm eq 'resource') {
 2071:        if ($ENV{'request.course.id'}) {
 2072: 
 2073: #	   print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 2074: 
 2075: 
 2076: # ----------------------------------------------------- Cascading lookup scheme
 2077:          my $symbp;
 2078:          if ($symbparm) {
 2079:             $symbp=$symbparm;
 2080: 	 } else {
 2081:             $symbp=&symbread();
 2082:          }            
 2083:          my $mapp=(split(/\_\_\_/,$symbp))[0];
 2084: 
 2085:          my $symbparm=$symbp.'.'.$spacequalifierrest;
 2086:          my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 2087: 
 2088:          my $seclevel=
 2089:             $ENV{'request.course.id'}.'.['.
 2090: 		$ENV{'request.course.sec'}.'].'.$spacequalifierrest;
 2091:          my $seclevelr=
 2092:             $ENV{'request.course.id'}.'.['.
 2093: 		$ENV{'request.course.sec'}.'].'.$symbparm;
 2094:          my $seclevelm=
 2095:             $ENV{'request.course.id'}.'.['.
 2096: 		$ENV{'request.course.sec'}.'].'.$mapparm;
 2097: 
 2098:          my $courselevel=
 2099:             $ENV{'request.course.id'}.'.'.$spacequalifierrest;
 2100:          my $courselevelr=
 2101:             $ENV{'request.course.id'}.'.'.$symbparm;
 2102:          my $courselevelm=
 2103:             $ENV{'request.course.id'}.'.'.$mapparm;
 2104: 
 2105: # ----------------------------------------------------------- first, check user
 2106:          my %resourcedata=get('resourcedata',
 2107:                            [$courselevelr,$courselevelm,$courselevel]);
 2108:          if (($resourcedata{$courselevelr}!~/^error\:/) &&
 2109:              ($resourcedata{$courselevelr}!~/^con_lost/)) {
 2110: 
 2111:          if ($resourcedata{$courselevelr}) { 
 2112:             return $resourcedata{$courselevelr}; }
 2113:          if ($resourcedata{$courselevelm}) { 
 2114:             return $resourcedata{$courselevelm}; }
 2115:          if ($resourcedata{$courselevel}) { return $resourcedata{$courselevel}; }
 2116: 
 2117:       } else {
 2118: 	  if ($resourcedata{$courselevelr}!~/No such file/) {
 2119: 	    &logthis("<font color=blue>WARNING:".
 2120: 		   " Trying to get resource data for ".$ENV{'user.name'}." at "
 2121:                    .$ENV{'user.domain'}.": ".$resourcedata{$courselevelr}.
 2122:                  "</font>");
 2123: 	  }
 2124:       }
 2125: 
 2126: # -------------------------------------------------------- second, check course
 2127: 
 2128:         my $reply=&reply('get:'.
 2129:               $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
 2130:               $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
 2131: 	      ':resourcedata:'.
 2132:    &escape($seclevelr).'&'.&escape($seclevelm).'&'.&escape($seclevel).'&'.
 2133:    &escape($courselevelr).'&'.&escape($courselevelm).'&'.&escape($courselevel),
 2134: 		   $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
 2135:       if ($reply!~/^error\:/) {
 2136: 	  foreach (split(/\&/,$reply)) {
 2137: 	      if ($_) { return &unescape($_); }
 2138:           }
 2139:       }
 2140:       if (($reply=~/^con_lost/) || ($reply=~/^error\:/)) {
 2141: 	  &logthis("<font color=blue>WARNING:".
 2142:                 " Getting ".$reply." asking for ".$varname." for ".
 2143:                 $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
 2144:                 ' at '.
 2145:                 $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
 2146:                 ' from '.
 2147:                 $ENV{'course.'.$ENV{'request.course.id'}.'.home'}.
 2148:                  "</font>");
 2149:       }
 2150: # ------------------------------------------------------ third, check map parms
 2151:        my %parmhash=();
 2152:        my $thisparm='';       
 2153:        if (tie(%parmhash,'GDBM_File',
 2154:           $ENV{'request.course.fn'}.'_parms.db',&GDBM_READER,0640)) {
 2155:            $thisparm=$parmhash{$symbparm};
 2156: 	   untie(%parmhash);
 2157:        }
 2158:        if ($thisparm) { return $thisparm; }
 2159:      }
 2160:      
 2161: # --------------------------------------------- last, look in resource metadata
 2162: 
 2163:       $spacequalifierrest=~s/\./\_/;
 2164:       my $metadata=&metadata($ENV{'request.filename'},$spacequalifierrest);
 2165:       if ($metadata) { return $metadata; }
 2166:       $metadata=&metadata($ENV{'request.filename'},
 2167:                                          'parameter_'.$spacequalifierrest);
 2168:       if ($metadata) { return $metadata; }
 2169: 
 2170: # ------------------------------------------------------------------ Cascade up
 2171: 
 2172:       unless ($space eq '0') {
 2173:           my ($part,$id)=split(/\_/,$space);
 2174:           if ($id) {
 2175: 	      my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 2176:                                    $symbparm);
 2177:               if ($partgeneral) { return $partgeneral; }
 2178:           } else {
 2179:               my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
 2180:                                        $symbparm);
 2181:               if ($resourcegeneral) { return $resourcegeneral; }
 2182:           }
 2183:       }
 2184: 
 2185: # ---------------------------------------------------- Any other user namespace
 2186:     } elsif ($realm eq 'environment') {
 2187: # ----------------------------------------------------------------- environment
 2188:         return $ENV{'environment.'.$spacequalifierrest};
 2189:     } elsif ($realm eq 'system') {
 2190: # ----------------------------------------------------------------- system.time
 2191: 	if ($space eq 'time') {
 2192: 	    return time;
 2193:         }
 2194:     }
 2195:     return '';
 2196: }
 2197: 
 2198: # ---------------------------------------------------------------- Get metadata
 2199: 
 2200: sub metadata {
 2201:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 2202: 
 2203:     $uri=&declutter($uri);
 2204:     my $filename=$uri;
 2205:     $uri=~s/\.meta$//;
 2206: #
 2207: # Is the metadata already cached?
 2208: # Look at timestamp of caching
 2209: # Everything is cached by the main uri, libraries are never directly cached
 2210: #
 2211:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600) {
 2212: #
 2213: # Is this a recursive call for a library?
 2214: #
 2215:         if ($liburi) {
 2216: 	    $liburi=&declutter($liburi);
 2217:             $filename=$liburi;
 2218:         }
 2219:         my %metathesekeys=();
 2220:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 2221: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
 2222:         my $parser=HTML::TokeParser->new(\$metastring);
 2223:         my $token;
 2224:         undef %metathesekeys;
 2225:         while ($token=$parser->get_token) {
 2226:            if ($token->[0] eq 'S') {
 2227: 	     if (defined($token->[2]->{'package'})) {
 2228: #
 2229: # This is a package - get package info
 2230: #
 2231: 	      my $package=$token->[2]->{'package'};
 2232: 	      my $keyroot='';
 2233:               if ($prefix) {
 2234: 		  $keyroot.='_'.$prefix;
 2235:               } else {
 2236:                 if (defined($token->[2]->{'part'})) { 
 2237:                    $keyroot.='_'.$token->[2]->{'part'}; 
 2238: 	        }
 2239: 	      }
 2240:               if (defined($token->[2]->{'id'})) { 
 2241:                  $keyroot.='_'.$token->[2]->{'id'}; 
 2242: 	      }
 2243:               if ($metacache{$uri.':packages'}) {
 2244:                  $metacache{$uri.':packages'}.=','.$package.$keyroot;
 2245:               } else {
 2246:                  $metacache{$uri.':packages'}=$package.$keyroot;
 2247: 	      }
 2248:               foreach (keys %packagetab) {
 2249: 		  if ($_=~/^$package\&/) {
 2250: 		      my ($pack,$name,$subp)=split(/\&/,$_);
 2251:                       my $value=$packagetab{$_};
 2252: 		      my $part=$keyroot;
 2253:                       $part=~s/^\_//;
 2254:                       if ($subp eq 'display') {
 2255: 			  $value.=' [Part: '.$part.']';
 2256:                       }
 2257:                       my $unikey='parameter'.$keyroot.'_'.$name;
 2258:                       $metathesekeys{$unikey}=1;
 2259:                       $metacache{$uri.':'.$unikey.'.part'}=$part;
 2260:                       unless 
 2261:                        (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
 2262:                          $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
 2263: 		      }
 2264:                   }
 2265:               }
 2266:              } else {
 2267: #
 2268: # This is not a package - some other kind of start tag
 2269: # 
 2270:               my $entry=$token->[1];
 2271:               my $unikey;
 2272:               if ($entry eq 'import') {
 2273:                  $unikey='';
 2274:               } else {
 2275:                  $unikey=$entry;
 2276: 	      }
 2277:               if ($prefix) {
 2278: 		  $unikey.=$prefix;
 2279:               } else {
 2280:                 if (defined($token->[2]->{'part'})) { 
 2281:                    $unikey.='_'.$token->[2]->{'part'}; 
 2282: 	        }
 2283: 	      }
 2284:               if (defined($token->[2]->{'id'})) { 
 2285:                  $unikey.='_'.$token->[2]->{'id'}; 
 2286: 	      }
 2287: 
 2288:              if ($entry eq 'import') {
 2289: #
 2290: # Importing a library here
 2291: #                
 2292: 		 if (defined($depthcount)) { $depthcount++; } else 
 2293:                                            { $depthcount=0; }
 2294:                  if ($depthcount<20) {
 2295: 		     foreach (split(/\,/,&metadata($uri,'keys',
 2296:                                   $parser->get_text('/import'),$unikey,
 2297:                                   $depthcount))) {
 2298:                          $metathesekeys{$_}=1;
 2299: 		     }
 2300: 		 }
 2301:              } else { 
 2302: 
 2303:               if (defined($token->[2]->{'name'})) { 
 2304:                  $unikey.='_'.$token->[2]->{'name'}; 
 2305: 	      }
 2306:               $metathesekeys{$unikey}=1;
 2307:               foreach (@{$token->[3]}) {
 2308: 		  $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
 2309:               }
 2310:               unless (
 2311:                  $metacache{$uri.':'.$unikey}=$parser->get_text('/'.$entry)
 2312: 		      ) { $metacache{$uri.':'.$unikey}=
 2313: 			      $metacache{$uri.':'.$unikey.'.default'};
 2314: 		      }
 2315: # end of not-a-package not-a-library import
 2316: 	   }
 2317: # end of not-a-package start tag
 2318: 	  }
 2319: # the next is the end of "start tag"
 2320: 	 }
 2321:        }
 2322:        $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
 2323:        $metacache{$uri.':cachedtimestamp'}=time;
 2324: # this is the end of "was not already recently cached
 2325:     }
 2326:     return $metacache{$uri.':'.$what};
 2327: }
 2328: 
 2329: # ------------------------------------------------- Update symbolic store links
 2330: 
 2331: sub symblist {
 2332:     my ($mapname,%newhash)=@_;
 2333:     $mapname=declutter($mapname);
 2334:     my %hash;
 2335:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 2336:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 2337:                       &GDBM_WRCREAT,0640)) {
 2338: 	    foreach (keys %newhash) {
 2339:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
 2340:             }
 2341:             if (untie(%hash)) {
 2342: 		return 'ok';
 2343:             }
 2344:         }
 2345:     }
 2346:     return 'error';
 2347: }
 2348: 
 2349: # ------------------------------------------------------ Return symb list entry
 2350: 
 2351: sub symbread {
 2352:     my $thisfn=shift;
 2353:     unless ($thisfn) {
 2354:         if ($ENV{'request.symb'}) { return $ENV{'request.symb'}; }
 2355: 	$thisfn=$ENV{'request.filename'};
 2356:     }
 2357:     $thisfn=declutter($thisfn);
 2358:     my %hash;
 2359:     my %bighash;
 2360:     my $syval='';
 2361:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 2362:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 2363:                       &GDBM_READER,0640)) {
 2364: 	    $syval=$hash{$thisfn};
 2365:             untie(%hash);
 2366:         }
 2367: # ---------------------------------------------------------- There was an entry
 2368:         if ($syval) {
 2369:            unless ($syval=~/\_\d+$/) {
 2370: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 2371:                   &appenv('request.ambiguous' => $thisfn);
 2372:                   return '';
 2373:                }    
 2374:                $syval.=$1;
 2375: 	   }
 2376:         } else {
 2377: # ------------------------------------------------------- Was not in symb table
 2378:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 2379:                             &GDBM_READER,0640)) {
 2380: # ---------------------------------------------- Get ID(s) for current resource
 2381:               my $ids=$bighash{'ids_/res/'.$thisfn};
 2382:               unless ($ids) { 
 2383:                  $ids=$bighash{'ids_/'.$thisfn};
 2384:               }
 2385:               if ($ids) {
 2386: # ------------------------------------------------------------------- Has ID(s)
 2387:                  my @possibilities=split(/\,/,$ids);
 2388:                  if ($#possibilities==0) {
 2389: # ----------------------------------------------- There is only one possibility
 2390: 		     my ($mapid,$resid)=split(/\./,$ids);
 2391:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 2392:                  } else {
 2393: # ------------------------------------------ There is more than one possibility
 2394:                      my $realpossible=0;
 2395:                      foreach (@possibilities) {
 2396: 			 my $file=$bighash{'src_'.$_};
 2397:                          if (&allowed('bre',$file)) {
 2398:          		    my ($mapid,$resid)=split(/\./,$_);
 2399:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 2400: 				$realpossible++;
 2401:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 2402:                                        '___'.$resid;
 2403:                             }
 2404: 			 }
 2405:                      }
 2406: 		     if ($realpossible!=1) { $syval=''; }
 2407:                  }
 2408: 	      }
 2409:               untie(%bighash)
 2410:            } 
 2411:         }
 2412:         if ($syval) {
 2413:            return $syval.'___'.$thisfn; 
 2414:         }
 2415:     }
 2416:     &appenv('request.ambiguous' => $thisfn);
 2417:     return '';
 2418: }
 2419: 
 2420: # ---------------------------------------------------------- Return random seed
 2421: 
 2422: sub numval {
 2423:     my $txt=shift;
 2424:     $txt=~tr/A-J/0-9/;
 2425:     $txt=~tr/a-j/0-9/;
 2426:     $txt=~tr/K-T/0-9/;
 2427:     $txt=~tr/k-t/0-9/;
 2428:     $txt=~tr/U-Z/0-5/;
 2429:     $txt=~tr/u-z/0-5/;
 2430:     $txt=~s/\D//g;
 2431:     return int($txt);
 2432: }    
 2433: 
 2434: sub rndseed {
 2435:     my ($symb,$courseid,$domain,$username)=@_;
 2436:     if (!$symb) {
 2437:       unless ($symb=&symbread()) { return time; }
 2438:     }
 2439:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
 2440:     if (!$domain) {$domain=$ENV{'user.domain'};}
 2441:     if (!$username) {$username=$ENV{'user.name'};}
 2442:     {
 2443:       use integer;
 2444:       my $symbchck=unpack("%32C*",$symb) << 27;
 2445:       my $symbseed=numval($symb) << 22;
 2446:       my $namechck=unpack("%32C*",$username) << 17;
 2447:       my $nameseed=numval($username) << 12;
 2448:       my $domainseed=unpack("%32C*",$domain) << 7;
 2449:       my $courseseed=unpack("%32C*",$courseid);
 2450:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 2451:       #uncommenting these lines can break things!
 2452:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 2453:       #&Apache::lonxml::debug("rndseed :$num:$symb");
 2454:       return $num;
 2455:     }
 2456: }
 2457: 
 2458: sub ireceipt {
 2459:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
 2460:     my $cuname=unpack("%32C*",$funame);
 2461:     my $cudom=unpack("%32C*",$fudom);
 2462:     my $cucourseid=unpack("%32C*",$fucourseid);
 2463:     my $cusymb=unpack("%32C*",$fusymb);
 2464:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
 2465:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
 2466:            ($cunique%$cuname+
 2467:             $cunique%$cudom+
 2468:             $cusymb%$cuname+
 2469:             $cusymb%$cudom+
 2470:             $cucourseid%$cuname+
 2471:             $cucourseid%$cudom);
 2472: }
 2473: 
 2474: sub receipt {
 2475:     return &ireceipt($ENV{'user.name'},$ENV{'user.domain'},
 2476:                      $ENV{'request.course.id'},&symbread());
 2477: }
 2478:   
 2479: # ------------------------------------------------------------ Serves up a file
 2480: # returns either the contents of the file or a -1
 2481: sub getfile {
 2482:   my $file=shift;
 2483:   &repcopy($file);
 2484:   if (! -e $file ) { return -1; };
 2485:   my $fh=Apache::File->new($file);
 2486:   my $a='';
 2487:   while (<$fh>) { $a .=$_; }
 2488:   return $a
 2489: }
 2490: 
 2491: sub filelocation {
 2492:   my ($dir,$file) = @_;
 2493:   my $location;
 2494:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 2495:   if ($file=~m:^/~:) { # is a contruction space reference
 2496:     $location = $file;
 2497:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 2498:   } else {
 2499:     $file=~s/^$perlvar{'lonDocRoot'}//;
 2500:     $file=~s:^/*res::;
 2501:     if ( !( $file =~ m:^/:) ) {
 2502:       $location = $dir. '/'.$file;
 2503:     } else {
 2504:       $location = '/home/httpd/html/res'.$file;
 2505:     }
 2506:   }
 2507:   $location=~s://+:/:g; # remove duplicate /
 2508:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 2509:   return $location;
 2510: }
 2511: 
 2512: sub hreflocation {
 2513:     my ($dir,$file)=@_;
 2514:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
 2515:        my $finalpath=filelocation($dir,$file);
 2516:        $finalpath=~s/^\/home\/httpd\/html//;
 2517:        return $finalpath;
 2518:     } else {
 2519:        return $file;
 2520:     }
 2521: }
 2522: 
 2523: # ------------------------------------------------------------- Declutters URLs
 2524: 
 2525: sub declutter {
 2526:     my $thisfn=shift;
 2527:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 2528:     $thisfn=~s/^\///;
 2529:     $thisfn=~s/^res\///;
 2530:     return $thisfn;
 2531: }
 2532: 
 2533: # -------------------------------------------------------- Escape Special Chars
 2534: 
 2535: sub escape {
 2536:     my $str=shift;
 2537:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 2538:     return $str;
 2539: }
 2540: 
 2541: # ----------------------------------------------------- Un-Escape Special Chars
 2542: 
 2543: sub unescape {
 2544:     my $str=shift;
 2545:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2546:     return $str;
 2547: }
 2548: 
 2549: # ================================================================ Main Program
 2550: 
 2551: sub goodbye {
 2552:    &flushcourselogs();
 2553:    &logthis("Shutting down");
 2554: }
 2555: 
 2556: BEGIN {
 2557: # ------------------------------------------------------------ Read access.conf
 2558: {
 2559:     my $config=Apache::File->new("/etc/httpd/conf/access.conf");
 2560: 
 2561:     while (my $configline=<$config>) {
 2562:         if ($configline =~ /PerlSetVar/) {
 2563: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 2564:            chomp($varvalue);
 2565:            $perlvar{$varname}=$varvalue;
 2566:         }
 2567:     }
 2568: }
 2569: 
 2570: # ------------------------------------------------------------- Read hosts file
 2571: {
 2572:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
 2573: 
 2574:     while (my $configline=<$config>) {
 2575:        chomp($configline);
 2576:        my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
 2577:        $hostname{$id}=$name;
 2578:        $hostdom{$id}=$domain;
 2579:        $hostip{$id}=$ip;
 2580:        if ($role eq 'library') { $libserv{$id}=$name; }
 2581:     }
 2582: }
 2583: 
 2584: # ------------------------------------------------------ Read spare server file
 2585: {
 2586:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
 2587: 
 2588:     while (my $configline=<$config>) {
 2589:        chomp($configline);
 2590:        if (($configline) && ($configline ne $perlvar{'lonHostID'})) {
 2591:           $spareid{$configline}=1;
 2592:        }
 2593:     }
 2594: }
 2595: # ------------------------------------------------------------ Read permissions
 2596: {
 2597:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
 2598: 
 2599:     while (my $configline=<$config>) {
 2600:        chomp($configline);
 2601:       if ($configline) {
 2602:        my ($role,$perm)=split(/ /,$configline);
 2603:        if ($perm ne '') { $pr{$role}=$perm; }
 2604:       }
 2605:     }
 2606: }
 2607: 
 2608: # -------------------------------------------- Read plain texts for permissions
 2609: {
 2610:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
 2611: 
 2612:     while (my $configline=<$config>) {
 2613:        chomp($configline);
 2614:       if ($configline) {
 2615:        my ($short,$plain)=split(/:/,$configline);
 2616:        if ($plain ne '') { $prp{$short}=$plain; }
 2617:       }
 2618:     }
 2619: }
 2620: 
 2621: # ---------------------------------------------------------- Read package table
 2622: {
 2623:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
 2624: 
 2625:     while (my $configline=<$config>) {
 2626:        chomp($configline);
 2627:        my ($short,$plain)=split(/:/,$configline);
 2628:        my ($pack,$name)=split(/\&/,$short);
 2629:        if ($plain ne '') {
 2630:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
 2631:           $packagetab{$short}=$plain; 
 2632:        }
 2633:     }
 2634: }
 2635: 
 2636: %metacache=();
 2637: 
 2638: $processmarker=$$.'_'.time.'_'.$perlvar{'lonHostID'};
 2639: $dumpcount=0;
 2640: 
 2641: &logtouch();
 2642: &logthis('<font color=yellow>INFO: Read configuration</font>');
 2643: }
 2644: 
 2645: 1;
 2646: __END__
 2647: 
 2648: =head1 NAME
 2649: 
 2650: Apache::lonnet - TCP networking package
 2651: 
 2652: =head1 SYNOPSIS
 2653: 
 2654: Invoked by other LON-CAPA modules.
 2655: 
 2656:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 2657: 
 2658: =head1 INTRODUCTION
 2659: 
 2660: This module provides subroutines which interact with the
 2661: lonc/lond (TCP) network layer of LON-CAPA.
 2662: 
 2663: This is part of the LearningOnline Network with CAPA project
 2664: described at http://www.lon-capa.org.
 2665: 
 2666: =head1 HANDLER SUBROUTINE
 2667: 
 2668: There is no handler routine for this module.
 2669: 
 2670: =head1 OTHER SUBROUTINES
 2671: 
 2672: =over 4
 2673: 
 2674: =item *
 2675: 
 2676: logtouch() : make sure the logfile, lonnet.log, exists
 2677: 
 2678: =item *
 2679: 
 2680: logthis() : append message to lonnet.log
 2681: 
 2682: =item *
 2683: 
 2684: logperm() : append a permanent message to lonnet.perm.log
 2685: 
 2686: =item *
 2687: 
 2688: subreply() : non-critical communication, called by &reply
 2689: 
 2690: =item *
 2691: 
 2692: reply() : makes two attempts to pass message; logs refusals and rejections
 2693: 
 2694: =item *
 2695: 
 2696: reconlonc() : tries to reconnect lonc client processes.
 2697: 
 2698: =item *
 2699: 
 2700: critical() : passes a critical message to another server; if cannot get
 2701: through then place message in connection buffer
 2702: 
 2703: =item *
 2704: 
 2705: appenv(%hash) : read in current user environment, append new environment
 2706: values to make new user environment
 2707: 
 2708: =item *
 2709: 
 2710: delenv($varname) : read in current user environment, remove all values
 2711: beginning with $varname, write new user environment (note: flock is used
 2712: to prevent conflicting shared read/writes with file)
 2713: 
 2714: =item *
 2715: 
 2716: spareserver() : find server with least workload from spare.tab
 2717: 
 2718: =item *
 2719: 
 2720: queryauthenticate($uname,$udom) : try to determine user's current
 2721: authentication scheme
 2722: 
 2723: =item *
 2724: 
 2725: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
 2726: servers (first use the current one)
 2727: 
 2728: =item *
 2729: 
 2730: homeserver($uname,$udom) : find the homebase for a user from domain's lib
 2731: servers
 2732: 
 2733: =item *
 2734: 
 2735: idget($udom,@ids) : find the usernames behind a list of IDs (returns hash:
 2736: id=>name,id=>name)
 2737: 
 2738: =item *
 2739: 
 2740: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
 2741: name=>id,name=>id)
 2742: 
 2743: =item *
 2744: 
 2745: idput($udom,%ids) : store away a list of names and associated IDs
 2746: 
 2747: =item *
 2748: 
 2749: usection($domain,$user,$courseid) : output of section name/number or '' for
 2750: "not in course" and '-1' for "no section"
 2751: 
 2752: =item *
 2753: 
 2754: userenvironment($domain,$user,$what) : puts out any environment parameter 
 2755: for a user
 2756: 
 2757: =item *
 2758: 
 2759: subscribe($fname) : subscribe to a resource, return URL if possible
 2760: 
 2761: =item *
 2762: 
 2763: repcopy($filename) : replicate file
 2764: 
 2765: =item *
 2766: 
 2767: ssi($url,%hash) : server side include, does a complete request cycle on url to
 2768: localhost, posts hash
 2769: 
 2770: =item *
 2771: 
 2772: log($domain,$name,$home,$message) : write to permanent log for user; use
 2773: critical subroutine
 2774: 
 2775: =item *
 2776: 
 2777: flushcourselogs() : flush (save) buffer logs and access logs
 2778: 
 2779: =item *
 2780: 
 2781: courselog($what) : save message for course in hash
 2782: 
 2783: =item *
 2784: 
 2785: courseacclog($what) : save message for course using &courselog().  Perform
 2786: special processing for specific resource types (problems, exams, quizzes, etc).
 2787: 
 2788: =item *
 2789: 
 2790: countacc($url) : count the number of accesses to a given URL
 2791: 
 2792: =item *
 2793: 
 2794: sub checkout($symb,$tuname,$tudom,$tcrsid) : check out an item
 2795: 
 2796: =item *
 2797: 
 2798: sub checkin($token) : check in an item
 2799: 
 2800: =item *
 2801: 
 2802: sub expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 2803: 
 2804: =item *
 2805: 
 2806: devalidate($symb) : devalidate spreadsheets
 2807: 
 2808: =item *
 2809: 
 2810: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 2811: and '&' separators
 2812: 
 2813: =item *
 2814: 
 2815: str2hash($string) : convert string to hash using unescaping and splitting on
 2816: '=' and '&'
 2817: 
 2818: =item *
 2819: 
 2820: tmpreset($symb,$namespace,$domain,$stuname) : temporary storage
 2821: 
 2822: =item *
 2823: 
 2824: tmprestore($symb,$namespace,$domain,$stuname) : temporary restore
 2825: 
 2826: =item *
 2827: 
 2828: store($storehash,$symb,$namespace,$domain,$stuname) : stores hash permanently
 2829: for this url; hashref needs to be given and should be a \%hashname; the
 2830: remaining args aren't required and if they aren't passed or are '' they will
 2831: be derived from the ENV
 2832: 
 2833: =item *
 2834: 
 2835: cstore($storehash,$symb,$namespace,$domain,$stuname) : same as store but
 2836: uses critical subroutine
 2837: 
 2838: =item *
 2839: 
 2840: restore($symb,$namespace,$domain,$stuname) : returns hash for this symb;
 2841: all args are optional
 2842: 
 2843: =item *
 2844: 
 2845: coursedescription($courseid) : course description
 2846: 
 2847: =item *
 2848: 
 2849: rolesinit($domain,$username,$authhost) : get user privileges
 2850: 
 2851: =item *
 2852: 
 2853: get($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
 2854: reference filled in from namesp ($udomain and $uname are optional)
 2855: 
 2856: =item *
 2857: 
 2858: del($namespace,$storearr,$udomain,$uname) : deletes keys out of array from
 2859: namesp ($udomain and $uname are optional)
 2860: 
 2861: =item *
 2862: 
 2863: dump($namespace,$udomain,$uname,$regexp) : 
 2864: dumps the complete (or key matching regexp) namespace into a hash
 2865: ($udomain, $uname and $regexp are optional)
 2866: 
 2867: =item *
 2868: 
 2869: put($namespace,$storehash,$udomain,$uname) : stores hash in namesp
 2870: ($udomain and $uname are optional)
 2871: 
 2872: =item *
 2873: 
 2874: cput($namespace,$storehash,$udomain,$uname) : critical put
 2875: ($udomain and $uname are optional)
 2876: 
 2877: =item *
 2878: 
 2879: eget($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
 2880: reference filled in from namesp (encrypts the return communication)
 2881: ($udomain and $uname are optional)
 2882: 
 2883: =item *
 2884: 
 2885: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 2886: actions
 2887:  F: full access
 2888:  U,I,K: authentication modes (cxx only)
 2889:  '': forbidden
 2890:  1: user needs to choose course
 2891:  2: browse allowed
 2892: 
 2893: =item *
 2894: 
 2895: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 2896: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 2897: and course level
 2898: 
 2899: =item *
 2900: 
 2901: metadata_query($query,$custom,$customshow) : make a metadata query against the
 2902: network of library servers; returns file handle of where SQL and regex results
 2903: will be stored for query
 2904: 
 2905: =item *
 2906: 
 2907: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 2908: explanation of a user role term
 2909: 
 2910: =item *
 2911: 
 2912: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 2913: user for the level given by URL.  Optional start and end dates (leave empty
 2914: string or zero for "no date")
 2915: 
 2916: =item *
 2917: 
 2918: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 2919: 
 2920: =item *
 2921: 
 2922: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 2923: modify user
 2924: 
 2925: =item *
 2926: 
 2927: modifystudent($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 2928: $end,$start) : modify student
 2929: 
 2930: =item *
 2931: 
 2932: writecoursepref($courseid,%prefs) : write preferences for a course
 2933: 
 2934: =item *
 2935: 
 2936: createcourse($udom,$description,$url) : make/modify course
 2937: 
 2938: =item *
 2939: 
 2940: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 2941: custom role; give a custom role to a user for the level given by URL.  Specify
 2942: name and domain of role author, and role name
 2943: 
 2944: =item *
 2945: 
 2946: revokerole($udom,$uname,$url,$role) : revoke a role for url
 2947: 
 2948: =item *
 2949: 
 2950: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 2951: 
 2952: =item *
 2953: 
 2954: dirlist($uri) : return directory list based on URI
 2955: 
 2956: =item *
 2957: 
 2958: directcondval($number) : get current value of a condition; reads from a state
 2959: string
 2960: 
 2961: =item *
 2962: 
 2963: condval($condidx) : value of condition index based on state
 2964: 
 2965: =item *
 2966: 
 2967: EXT($varname,$symbparm) : value of a variable
 2968: 
 2969: =item *
 2970: 
 2971: metadata($uri,$what,$liburi,$prefix,$depthcount) : get metadata; returns the
 2972: metadata entry for a file; entry='keys', returns a comma separated list of keys
 2973: 
 2974: =item *
 2975: 
 2976: symblist($mapname,%newhash) : update symbolic storage links
 2977: 
 2978: =item *
 2979: 
 2980: symbread($filename) : return symbolic list entry (filename argument optional);
 2981: returns the data handle
 2982: 
 2983: =item *
 2984: 
 2985: numval($salt) : return random seed value (addend for rndseed)
 2986: 
 2987: =item *
 2988: 
 2989: rndseed($symb,$courseid,$domain,$username) : create a random sum; returns
 2990: a random seed, all arguments are optional, if they aren't sent it uses the
 2991: environment to derive them. Note: if symb isn't sent and it can't get one
 2992: from &symbread it will use the current time as its return value
 2993: 
 2994: =item *
 2995: 
 2996: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 2997: unfakeable, receipt
 2998: 
 2999: =item *
 3000: 
 3001: receipt() : API to ireceipt working off of ENV values; given out to users
 3002: 
 3003: =item *
 3004: 
 3005: getfile($file) : serves up a file, returns the contents of a file or -1;
 3006: replicates and subscribes to the file
 3007: 
 3008: =item *
 3009: 
 3010: filelocation($dir,$file) : returns file system location of a file based on URI;
 3011: meant to be "fairly clean" absolute reference
 3012: 
 3013: =item *
 3014: 
 3015: hreflocation($dir,$file) : returns file system location or a URL; same as
 3016: filelocation except for hrefs
 3017: 
 3018: =item *
 3019: 
 3020: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 3021: 
 3022: =item *
 3023: 
 3024: escape() : unpack non-word characters into CGI-compatible hex codes
 3025: 
 3026: =item *
 3027: 
 3028: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 3029: 
 3030: =item *
 3031: 
 3032: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 3033: as a PerlChildExitHandler
 3034: 
 3035: =back
 3036: 
 3037: =cut

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