File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.273: download - view: text, annotated - select for diffs
Fri Aug 23 21:31:09 2002 UTC (21 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- lonnet::get reports errors correctly now (BUG#644)

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

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