File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.350: download - view: text, annotated - select for diffs
Mon Mar 24 19:57:35 2003 UTC (21 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Also encode section

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

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