File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.354: download - view: text, annotated - select for diffs
Wed Mar 26 15:49:02 2003 UTC (21 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Now correctly calls lond's courseiddump

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.354 2003/03/26 15:49:02 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
   29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
   30: # 11/8,11/16,11/18,11/22,11/23,12/22,
   31: # 01/06,01/13,02/24,02/28,02/29,
   32: # 03/01,03/02,03/06,03/07,03/13,
   33: # 04/05,05/29,05/31,06/01,
   34: # 06/05,06/26 Gerd Kortemeyer
   35: # 06/26 Ben Tyszka
   36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
   37: # 08/14 Ben Tyszka
   38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
   39: # 10/04 Gerd Kortemeyer
   40: # 10/04 Guy Albertelli
   41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
   42: # 10/30,10/31,
   43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
   44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
   45: # 05/01/01 Guy Albertelli
   46: # 05/01,06/01,09/01 Gerd Kortemeyer
   47: # 09/01 Guy Albertelli
   48: # 09/01,10/01,11/01 Gerd Kortemeyer
   49: # YEAR=2001
   50: # 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 %coursenumbuf %coursehombuf %coursedescrbuf %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: # This routine flushes several buffers of non-mission-critical nature
 1032: #
 1033: 
 1034: sub flushcourselogs {
 1035:     &logthis('Flushing log buffers');
 1036: #
 1037: # course logs
 1038: # This is a log of all transactions in a course, which can be used
 1039: # for data mining purposes
 1040: #
 1041: # It also collects the courseid database, which lists last transaction
 1042: # times and course titles for all courseids
 1043: #
 1044:     my %courseidbuffer=();
 1045:     foreach (keys %courselogs) {
 1046:         my $crsid=$_;
 1047:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1048: 		          &escape($courselogs{$crsid}),
 1049: 		          $coursehombuf{$crsid}) eq 'ok') {
 1050: 	    delete $courselogs{$crsid};
 1051:         } else {
 1052:             &logthis('Failed to flush log buffer for '.$crsid);
 1053:             if (length($courselogs{$crsid})>40000) {
 1054:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
 1055:                         " exceeded maximum size, deleting.</font>");
 1056:                delete $courselogs{$crsid};
 1057:             }
 1058:         }
 1059:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1060:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1061: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
 1062:         } else {
 1063:            $courseidbuffer{$coursehombuf{$crsid}}=
 1064: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
 1065:         }    
 1066:     }
 1067: #
 1068: # Write course id database (reverse lookup) to homeserver of courses 
 1069: # Is used in pickcourse
 1070: #
 1071:     foreach (keys %courseidbuffer) {
 1072:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1073:     }
 1074: #
 1075: # File accesses
 1076: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1077: #
 1078:     foreach (keys %accesshash) {
 1079:         my $entry=$_;
 1080:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
 1081:         my %temphash=($entry => $accesshash{$entry});
 1082:         if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
 1083: 	    delete $accesshash{$entry};
 1084:         }
 1085:     }
 1086: #
 1087: # Roles
 1088: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1089: #
 1090:     foreach (keys %userrolehash) {
 1091:         my $entry=$_;
 1092:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1093: 	    split(/\:/,$entry);
 1094:         if (&Apache::lonnet::put('nohist_userroles',
 1095:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1096:                 $rudom,$runame) eq 'ok') {
 1097: 	    delete $userrolehash{$entry};
 1098:         }
 1099:     }
 1100:     $dumpcount++;
 1101: }
 1102: 
 1103: sub courselog {
 1104:     my $what=shift;
 1105:     $what=time.':'.$what;
 1106:     unless ($ENV{'request.course.id'}) { return ''; }
 1107:     $coursedombuf{$ENV{'request.course.id'}}=
 1108:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1109:     $coursenumbuf{$ENV{'request.course.id'}}=
 1110:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1111:     $coursehombuf{$ENV{'request.course.id'}}=
 1112:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1113:     $coursedescrbuf{$ENV{'request.course.id'}}=
 1114:        $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1115:     if (defined $courselogs{$ENV{'request.course.id'}}) {
 1116: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
 1117:     } else {
 1118: 	$courselogs{$ENV{'request.course.id'}}.=$what;
 1119:     }
 1120:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
 1121: 	&flushcourselogs();
 1122:     }
 1123: }
 1124: 
 1125: sub courseacclog {
 1126:     my $fnsymb=shift;
 1127:     unless ($ENV{'request.course.id'}) { return ''; }
 1128:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
 1129:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
 1130:         $what.=':POST';
 1131: 	foreach (keys %ENV) {
 1132:             if ($_=~/^form\.(.*)/) {
 1133: 		$what.=':'.$1.'='.$ENV{$_};
 1134:             }
 1135:         }
 1136:     }
 1137:     &courselog($what);
 1138: }
 1139: 
 1140: sub countacc {
 1141:     my $url=&declutter(shift);
 1142:     unless ($ENV{'request.course.id'}) { return ''; }
 1143:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
 1144:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1145:     if (defined($accesshash{$key})) {
 1146: 	$accesshash{$key}++;
 1147:     } else {
 1148:         $accesshash{$key}=1;
 1149:     }
 1150: }
 1151: 
 1152: sub userrolelog {
 1153:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1154:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
 1155:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
 1156:         ($trole=~/^cr/)) {
 1157:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1158:        $userrolehash
 1159:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1160:                     =$tend.':'.$tstart;
 1161:    }
 1162: }
 1163: 
 1164: sub get_course_adv_roles {
 1165:     my $cid=shift;
 1166:     $cid=$ENV{'request.course.id'} unless (defined($cid));
 1167:     my %coursehash=&coursedescription($cid);
 1168:     my %returnhash=();
 1169:     my %dumphash=
 1170:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1171:     my $now=time;
 1172:     foreach (keys %dumphash) {
 1173: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1174:         if (($tstart) && ($tstart<0)) { next; }
 1175:         if (($tend) && ($tend<$now)) { next; }
 1176:         if (($tstart) && ($now<$tstart)) { next; }
 1177:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1178:         my $key=&plaintext($role);
 1179:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1180:         if ($returnhash{$key}) {
 1181: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1182:         } else {
 1183:             $returnhash{$key}=$username.':'.$domain;
 1184:         }
 1185:     }
 1186:     return sort %returnhash;
 1187: }
 1188: 
 1189: # ---------------------------------------------------------- Course ID routines
 1190: # Deal with domain's nohist_courseid.db files
 1191: #
 1192: 
 1193: sub courseidput {
 1194:     my ($domain,$what,$coursehome)=@_;
 1195:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1196: }
 1197: 
 1198: sub courseiddump {
 1199:     my ($domfilter,$descfilter,$sincefilter)=@_;
 1200:     my %returnhash=();
 1201:     foreach my $tryserver (keys %libserv) {
 1202: 	if ($hostdom{$tryserver}=~/$domfilter/) {
 1203: 	    foreach (
 1204:              split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1205: 			       $sincefilter.':'.&escape($descfilter),
 1206:                                $tryserver))) {
 1207: 		my ($key,$value)=split(/\=/,$_);
 1208:                 if (($key) && ($value)) {
 1209: 		    $returnhash{&unescape($key)}=&unescape($value);
 1210:                 }
 1211:             }
 1212: 
 1213:         }
 1214:     }
 1215:     return %returnhash;
 1216: }
 1217: 
 1218: #
 1219: # ----------------------------------------------------------- Check out an item
 1220: 
 1221: sub checkout {
 1222:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 1223:     my $now=time;
 1224:     my $lonhost=$perlvar{'lonHostID'};
 1225:     my $infostr=&escape(
 1226:                  'CHECKOUTTOKEN&'.
 1227:                  $tuname.'&'.
 1228:                  $tudom.'&'.
 1229:                  $tcrsid.'&'.
 1230:                  $symb.'&'.
 1231: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 1232:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 1233:     if ($token=~/^error\:/) { 
 1234:         &logthis("<font color=blue>WARNING: ".
 1235:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 1236:                  "</font>");
 1237:         return ''; 
 1238:     }
 1239: 
 1240:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 1241:     $token=~tr/a-z/A-Z/;
 1242: 
 1243:     my %infohash=('resource.0.outtoken' => $token,
 1244:                   'resource.0.checkouttime' => $now,
 1245:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 1246: 
 1247:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1248:        return '';
 1249:     } else {
 1250:         &logthis("<font color=blue>WARNING: ".
 1251:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 1252:                  "</font>");
 1253:     }    
 1254: 
 1255:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1256:                          &escape('Checkout '.$infostr.' - '.
 1257:                                                  $token)) ne 'ok') {
 1258: 	return '';
 1259:     } else {
 1260:         &logthis("<font color=blue>WARNING: ".
 1261:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 1262:                  "</font>");
 1263:     }
 1264:     return $token;
 1265: }
 1266: 
 1267: # ------------------------------------------------------------ Check in an item
 1268: 
 1269: sub checkin {
 1270:     my $token=shift;
 1271:     my $now=time;
 1272:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 1273:     $lonhost=~tr/A-Z/a-z/;
 1274:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
 1275:     $dtoken=~s/\W/\_/g;
 1276:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 1277:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 1278: 
 1279:     unless (($tuname) && ($tudom)) {
 1280:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 1281:         return '';
 1282:     }
 1283:     
 1284:     unless (&allowed('mgr',$tcrsid)) {
 1285:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 1286:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
 1287:         return '';
 1288:     }
 1289: 
 1290:     my %infohash=('resource.0.intoken' => $token,
 1291:                   'resource.0.checkintime' => $now,
 1292:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 1293: 
 1294:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1295:        return '';
 1296:     }    
 1297: 
 1298:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1299:                          &escape('Checkin - '.$token)) ne 'ok') {
 1300: 	return '';
 1301:     }
 1302: 
 1303:     return ($symb,$tuname,$tudom,$tcrsid);    
 1304: }
 1305: 
 1306: # --------------------------------------------- Set Expire Date for Spreadsheet
 1307: 
 1308: sub expirespread {
 1309:     my ($uname,$udom,$stype,$usymb)=@_;
 1310:     my $cid=$ENV{'request.course.id'}; 
 1311:     if ($cid) {
 1312:        my $now=time;
 1313:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 1314:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 1315:                             $ENV{'course.'.$cid.'.num'}.
 1316: 	        	    ':nohist_expirationdates:'.
 1317:                             &escape($key).'='.$now,
 1318:                             $ENV{'course.'.$cid.'.home'})
 1319:     }
 1320:     return 'ok';
 1321: }
 1322: 
 1323: # ----------------------------------------------------- Devalidate Spreadsheets
 1324: 
 1325: sub devalidate {
 1326:     my ($symb,$uname,$udom)=@_;
 1327:     my $cid=$ENV{'request.course.id'}; 
 1328:     if ($cid) {
 1329: # delete the stored spreadsheets for
 1330: # - the student level sheet of this user in course's homespace
 1331: # - the assessment level sheet for this resource 
 1332: #   for this user in user's homespace
 1333: 	my $key=$uname.':'.$udom.':';
 1334:         my $status=
 1335: 	    &del('nohist_calculatedsheets',
 1336: 		 [$key.'studentcalc'],
 1337: 		 $ENV{'course.'.$cid.'.domain'},
 1338: 		 $ENV{'course.'.$cid.'.num'})
 1339: 		.' '.
 1340: 	    &del('nohist_calculatedsheets_'.$cid,
 1341: 		 [$key.'assesscalc:'.$symb]);
 1342:         unless ($status eq 'ok ok') {
 1343:            &logthis('Could not devalidate spreadsheet '.
 1344:                     $uname.' at '.$udom.' for '.
 1345: 		    $symb.': '.$status);
 1346:         }
 1347:     }
 1348: }
 1349: 
 1350: sub get_scalar {
 1351:     my ($string,$end) = @_;
 1352:     my $value;
 1353:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 1354: 	$value = $1;
 1355:     } elsif ($$string =~ s/^([^&]*?)&//) {
 1356: 	$value = $1;
 1357:     }
 1358:     return &unescape($value);
 1359: }
 1360: 
 1361: sub array2str {
 1362:   my (@array) = @_;
 1363:   my $result=&arrayref2str(\@array);
 1364:   $result=~s/^__ARRAY_REF__//;
 1365:   $result=~s/__END_ARRAY_REF__$//;
 1366:   return $result;
 1367: }
 1368: 
 1369: sub arrayref2str {
 1370:   my ($arrayref) = @_;
 1371:   my $result='__ARRAY_REF__';
 1372:   foreach my $elem (@$arrayref) {
 1373:     if(ref($elem) eq 'ARRAY') {
 1374:       $result.=&arrayref2str($elem).'&';
 1375:     } elsif(ref($elem) eq 'HASH') {
 1376:       $result.=&hashref2str($elem).'&';
 1377:     } elsif(ref($elem)) {
 1378:       #print("Got a ref of ".(ref($elem))." skipping.");
 1379:     } else {
 1380:       $result.=&escape($elem).'&';
 1381:     }
 1382:   }
 1383:   $result=~s/\&$//;
 1384:   $result .= '__END_ARRAY_REF__';
 1385:   return $result;
 1386: }
 1387: 
 1388: sub hash2str {
 1389:   my (%hash) = @_;
 1390:   my $result=&hashref2str(\%hash);
 1391:   $result=~s/^__HASH_REF__//;
 1392:   $result=~s/__END_HASH_REF__$//;
 1393:   return $result;
 1394: }
 1395: 
 1396: sub hashref2str {
 1397:   my ($hashref)=@_;
 1398:   my $result='__HASH_REF__';
 1399:   foreach (keys(%$hashref)) {
 1400:     if (ref($_) eq 'ARRAY') {
 1401:       $result.=&arrayref2str($_).'=';
 1402:     } elsif (ref($_) eq 'HASH') {
 1403:       $result.=&hashref2str($_).'=';
 1404:     } elsif (ref($_)) {
 1405:       $result.='=';
 1406:       #print("Got a ref of ".(ref($_))." skipping.");
 1407:     } else {
 1408: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 1409:     }
 1410: 
 1411:     if(ref($hashref->{$_}) eq 'ARRAY') {
 1412:       $result.=&arrayref2str($hashref->{$_}).'&';
 1413:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 1414:       $result.=&hashref2str($hashref->{$_}).'&';
 1415:     } elsif(ref($hashref->{$_})) {
 1416:        $result.='&';
 1417:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 1418:     } else {
 1419:       $result.=&escape($hashref->{$_}).'&';
 1420:     }
 1421:   }
 1422:   $result=~s/\&$//;
 1423:   $result .= '__END_HASH_REF__';
 1424:   return $result;
 1425: }
 1426: 
 1427: sub str2hash {
 1428:     my ($string)=@_;
 1429:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 1430:     return %$hash;
 1431: }
 1432: 
 1433: sub str2hashref {
 1434:   my ($string) = @_;
 1435: 
 1436:   my %hash;
 1437: 
 1438:   if($string !~ /^__HASH_REF__/) {
 1439:       if (! ($string eq '' || !defined($string))) {
 1440: 	  $hash{'error'}='Not hash reference';
 1441:       }
 1442:       return (\%hash, $string);
 1443:   }
 1444: 
 1445:   $string =~ s/^__HASH_REF__//;
 1446: 
 1447:   while($string !~ /^__END_HASH_REF__/) {
 1448:       #key
 1449:       my $key='';
 1450:       if($string =~ /^__HASH_REF__/) {
 1451:           ($key, $string)=&str2hashref($string);
 1452:           if(defined($key->{'error'})) {
 1453:               $hash{'error'}='Bad data';
 1454:               return (\%hash, $string);
 1455:           }
 1456:       } elsif($string =~ /^__ARRAY_REF__/) {
 1457:           ($key, $string)=&str2arrayref($string);
 1458:           if($key->[0] eq 'Array reference error') {
 1459:               $hash{'error'}='Bad data';
 1460:               return (\%hash, $string);
 1461:           }
 1462:       } else {
 1463:           $string =~ s/^(.*?)=//;
 1464: 	  $key=&unescape($1);
 1465:       }
 1466:       $string =~ s/^=//;
 1467: 
 1468:       #value
 1469:       my $value='';
 1470:       if($string =~ /^__HASH_REF__/) {
 1471:           ($value, $string)=&str2hashref($string);
 1472:           if(defined($value->{'error'})) {
 1473:               $hash{'error'}='Bad data';
 1474:               return (\%hash, $string);
 1475:           }
 1476:       } elsif($string =~ /^__ARRAY_REF__/) {
 1477:           ($value, $string)=&str2arrayref($string);
 1478:           if($value->[0] eq 'Array reference error') {
 1479:               $hash{'error'}='Bad data';
 1480:               return (\%hash, $string);
 1481:           }
 1482:       } else {
 1483: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 1484:       }
 1485:       $string =~ s/^&//;
 1486: 
 1487:       $hash{$key}=$value;
 1488:   }
 1489: 
 1490:   $string =~ s/^__END_HASH_REF__//;
 1491: 
 1492:   return (\%hash, $string);
 1493: }
 1494: 
 1495: sub str2array {
 1496:     my ($string)=@_;
 1497:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 1498:     return @$array;
 1499: }
 1500: 
 1501: sub str2arrayref {
 1502:   my ($string) = @_;
 1503:   my @array;
 1504: 
 1505:   if($string !~ /^__ARRAY_REF__/) {
 1506:       if (! ($string eq '' || !defined($string))) {
 1507: 	  $array[0]='Array reference error';
 1508:       }
 1509:       return (\@array, $string);
 1510:   }
 1511: 
 1512:   $string =~ s/^__ARRAY_REF__//;
 1513: 
 1514:   while($string !~ /^__END_ARRAY_REF__/) {
 1515:       my $value='';
 1516:       if($string =~ /^__HASH_REF__/) {
 1517:           ($value, $string)=&str2hashref($string);
 1518:           if(defined($value->{'error'})) {
 1519:               $array[0] ='Array reference error';
 1520:               return (\@array, $string);
 1521:           }
 1522:       } elsif($string =~ /^__ARRAY_REF__/) {
 1523:           ($value, $string)=&str2arrayref($string);
 1524:           if($value->[0] eq 'Array reference error') {
 1525:               $array[0] ='Array reference error';
 1526:               return (\@array, $string);
 1527:           }
 1528:       } else {
 1529: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 1530:       }
 1531:       $string =~ s/^&//;
 1532: 
 1533:       push(@array, $value);
 1534:   }
 1535: 
 1536:   $string =~ s/^__END_ARRAY_REF__//;
 1537: 
 1538:   return (\@array, $string);
 1539: }
 1540: 
 1541: # -------------------------------------------------------------------Temp Store
 1542: 
 1543: sub tmpreset {
 1544:   my ($symb,$namespace,$domain,$stuname) = @_;
 1545:   if (!$symb) {
 1546:     $symb=&symbread();
 1547:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
 1548:   }
 1549:   $symb=escape($symb);
 1550: 
 1551:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1552:   $namespace=~s/\//\_/g;
 1553:   $namespace=~s/\W//g;
 1554: 
 1555:   #FIXME needs to do something for /pub resources
 1556:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1557:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1558:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1559:   my %hash;
 1560:   if (tie(%hash,'GDBM_File',
 1561: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1562: 	  &GDBM_WRCREAT(),0640)) {
 1563:     foreach my $key (keys %hash) {
 1564:       if ($key=~ /:$symb/) {
 1565: 	delete($hash{$key});
 1566:       }
 1567:     }
 1568:   }
 1569: }
 1570: 
 1571: sub tmpstore {
 1572:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1573: 
 1574:   if (!$symb) {
 1575:     $symb=&symbread();
 1576:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1577:   }
 1578:   $symb=escape($symb);
 1579: 
 1580:   if (!$namespace) {
 1581:     # I don't think we would ever want to store this for a course.
 1582:     # it seems this will only be used if we don't have a course.
 1583:     #$namespace=$ENV{'request.course.id'};
 1584:     #if (!$namespace) {
 1585:       $namespace=$ENV{'request.state'};
 1586:     #}
 1587:   }
 1588:   $namespace=~s/\//\_/g;
 1589:   $namespace=~s/\W//g;
 1590: #FIXME needs to do something for /pub resources
 1591:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1592:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1593:   my $now=time;
 1594:   my %hash;
 1595:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1596:   if (tie(%hash,'GDBM_File',
 1597: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1598: 	  &GDBM_WRCREAT(),0640)) {
 1599:     $hash{"version:$symb"}++;
 1600:     my $version=$hash{"version:$symb"};
 1601:     my $allkeys=''; 
 1602:     foreach my $key (keys(%$storehash)) {
 1603:       $allkeys.=$key.':';
 1604:       $hash{"$version:$symb:$key"}=$$storehash{$key};
 1605:     }
 1606:     $hash{"$version:$symb:timestamp"}=$now;
 1607:     $allkeys.='timestamp';
 1608:     $hash{"$version:keys:$symb"}=$allkeys;
 1609:     if (untie(%hash)) {
 1610:       return 'ok';
 1611:     } else {
 1612:       return "error:$!";
 1613:     }
 1614:   } else {
 1615:     return "error:$!";
 1616:   }
 1617: }
 1618: 
 1619: # -----------------------------------------------------------------Temp Restore
 1620: 
 1621: sub tmprestore {
 1622:   my ($symb,$namespace,$domain,$stuname) = @_;
 1623: 
 1624:   if (!$symb) {
 1625:     $symb=&symbread();
 1626:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1627:   }
 1628:   $symb=escape($symb);
 1629: 
 1630:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1631:   #FIXME needs to do something for /pub resources
 1632:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1633:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1634: 
 1635:   my %returnhash;
 1636:   $namespace=~s/\//\_/g;
 1637:   $namespace=~s/\W//g;
 1638:   my %hash;
 1639:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1640:   if (tie(%hash,'GDBM_File',
 1641: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1642: 	  &GDBM_READER(),0640)) {
 1643:     my $version=$hash{"version:$symb"};
 1644:     $returnhash{'version'}=$version;
 1645:     my $scope;
 1646:     for ($scope=1;$scope<=$version;$scope++) {
 1647:       my $vkeys=$hash{"$scope:keys:$symb"};
 1648:       my @keys=split(/:/,$vkeys);
 1649:       my $key;
 1650:       $returnhash{"$scope:keys"}=$vkeys;
 1651:       foreach $key (@keys) {
 1652: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
 1653: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
 1654:       }
 1655:     }
 1656:     if (!(untie(%hash))) {
 1657:       return "error:$!";
 1658:     }
 1659:   } else {
 1660:     return "error:$!";
 1661:   }
 1662:   return %returnhash;
 1663: }
 1664: 
 1665: # ----------------------------------------------------------------------- Store
 1666: 
 1667: sub store {
 1668:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1669:     my $home='';
 1670: 
 1671:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1672: 
 1673:     $symb=&symbclean($symb);
 1674:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1675: 
 1676:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1677:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1678: 
 1679:     &devalidate($symb,$stuname,$domain);
 1680: 
 1681:     $symb=escape($symb);
 1682:     if (!$namespace) { 
 1683:        unless ($namespace=$ENV{'request.course.id'}) { 
 1684:           return ''; 
 1685:        } 
 1686:     }
 1687:     if (!$home) { $home=$ENV{'user.home'}; }
 1688:     my $namevalue='';
 1689:     foreach (keys %$storehash) {
 1690:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1691:     }
 1692:     $namevalue=~s/\&$//;
 1693:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 1694:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1695: }
 1696: 
 1697: # -------------------------------------------------------------- Critical Store
 1698: 
 1699: sub cstore {
 1700:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1701:     my $home='';
 1702: 
 1703:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1704: 
 1705:     $symb=&symbclean($symb);
 1706:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1707: 
 1708:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1709:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1710: 
 1711:     &devalidate($symb,$stuname,$domain);
 1712: 
 1713:     $symb=escape($symb);
 1714:     if (!$namespace) { 
 1715:        unless ($namespace=$ENV{'request.course.id'}) { 
 1716:           return ''; 
 1717:        } 
 1718:     }
 1719:     if (!$home) { $home=$ENV{'user.home'}; }
 1720: 
 1721:     my $namevalue='';
 1722:     foreach (keys %$storehash) {
 1723:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1724:     }
 1725:     $namevalue=~s/\&$//;
 1726:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 1727:     return critical
 1728:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1729: }
 1730: 
 1731: # --------------------------------------------------------------------- Restore
 1732: 
 1733: sub restore {
 1734:     my ($symb,$namespace,$domain,$stuname) = @_;
 1735:     my $home='';
 1736: 
 1737:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1738: 
 1739:     if (!$symb) {
 1740:       unless ($symb=escape(&symbread())) { return ''; }
 1741:     } else {
 1742:       $symb=&escape(&symbclean($symb));
 1743:     }
 1744:     if (!$namespace) { 
 1745:        unless ($namespace=$ENV{'request.course.id'}) { 
 1746:           return ''; 
 1747:        } 
 1748:     }
 1749:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1750:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1751:     if (!$home) { $home=$ENV{'user.home'}; }
 1752:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 1753: 
 1754:     my %returnhash=();
 1755:     foreach (split(/\&/,$answer)) {
 1756: 	my ($name,$value)=split(/\=/,$_);
 1757:         $returnhash{&unescape($name)}=&unescape($value);
 1758:     }
 1759:     my $version;
 1760:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 1761:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 1762:           $returnhash{$_}=$returnhash{$version.':'.$_};
 1763:        }
 1764:     }
 1765:     return %returnhash;
 1766: }
 1767: 
 1768: # ---------------------------------------------------------- Course Description
 1769: 
 1770: sub coursedescription {
 1771:     my $courseid=shift;
 1772:     $courseid=~s/^\///;
 1773:     $courseid=~s/\_/\//g;
 1774:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1775:     my $chome=&homeserver($cnum,$cdomain);
 1776:     my $normalid=$cdomain.'_'.$cnum;
 1777:     # need to always cache even if we get errors otherwise we keep 
 1778:     # trying and trying and trying to get the course description.
 1779:     my %envhash=();
 1780:     my %returnhash=();
 1781:     $envhash{'course.'.$normalid.'.last_cache'}=time;
 1782:     if ($chome ne 'no_host') {
 1783:        %returnhash=&dump('environment',$cdomain,$cnum);
 1784:        if (!exists($returnhash{'con_lost'})) {
 1785:            $returnhash{'home'}= $chome;
 1786: 	   $returnhash{'domain'} = $cdomain;
 1787: 	   $returnhash{'num'} = $cnum;
 1788:            while (my ($name,$value) = each %returnhash) {
 1789:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 1790:            }
 1791:            $returnhash{'url'}=&clutter($returnhash{'url'});
 1792:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 1793: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
 1794:            $envhash{'course.'.$normalid.'.home'}=$chome;
 1795:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 1796:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 1797:        }
 1798:     }
 1799:     &appenv(%envhash);
 1800:     return %returnhash;
 1801: }
 1802: 
 1803: # -------------------------------------------------------- Get user privileges
 1804: 
 1805: sub rolesinit {
 1806:     my ($domain,$username,$authhost)=@_;
 1807:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 1808:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 1809:     my %allroles=();
 1810:     my %thesepriv=();
 1811:     my $now=time;
 1812:     my $userroles="user.login.time=$now\n";
 1813:     my $thesestr;
 1814: 
 1815:     if ($rolesdump ne '') {
 1816:         foreach (split(/&/,$rolesdump)) {
 1817: 	  if ($_!~/^rolesdef\&/) {
 1818:             my ($area,$role)=split(/=/,$_);
 1819:             $area=~s/\_\w\w$//;
 1820:             my ($trole,$tend,$tstart)=split(/_/,$role);
 1821:             $userroles.='user.role.'.$trole.'.'.$area.'='.
 1822:                         $tstart.'.'.$tend."\n";
 1823: # log the associated role with the area
 1824:             &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 1825:             if ($tend!=0) {
 1826: 	        if ($tend<$now) {
 1827: 	            $trole='';
 1828:                 } 
 1829:             }
 1830:             if ($tstart!=0) {
 1831:                 if ($tstart>$now) {
 1832:                    $trole='';        
 1833:                 }
 1834:             }
 1835:             if (($area ne '') && ($trole ne '')) {
 1836: 		my $spec=$trole.'.'.$area;
 1837: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 1838: 		if ($trole =~ /^cr\//) {
 1839: 		    my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 1840: 		    my $homsvr=homeserver($rauthor,$rdomain);
 1841: 		    if ($hostname{$homsvr} ne '') {
 1842: 			my $roledef=
 1843: 			    reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
 1844: 				  $homsvr);
 1845: 			if (($roledef ne 'con_lost') && ($roledef ne '')) {
 1846: 			    my ($syspriv,$dompriv,$coursepriv)=
 1847: 				split(/\_/,unescape($roledef));
 1848: 			    if (defined($syspriv)) {
 1849: 				$allroles{'cm./'}.=':'.$syspriv;
 1850: 				$allroles{$spec.'./'}.=':'.$syspriv;
 1851: 			    }
 1852: 			    if ($tdomain ne '') {
 1853: 				if (defined($dompriv)) {
 1854: 				    $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 1855: 				    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 1856: 				}
 1857: 				if ($trest ne '') {
 1858: 				    if (defined($coursepriv)) {
 1859: 					$allroles{'cm.'.$area}.=':'.$coursepriv;
 1860: 					$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 1861: 				    }
 1862: 				}
 1863: 			    }
 1864: 			}
 1865: 		    }
 1866: 		} else {
 1867: 		    if (defined($pr{$trole.':s'})) {
 1868: 			$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 1869: 			$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 1870: 		    }
 1871: 		    if ($tdomain ne '') {
 1872: 			if (defined($pr{$trole.':d'})) {
 1873: 			    $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1874: 			    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1875: 			}
 1876: 			if ($trest ne '') {
 1877: 			    if (defined($pr{$trole.':c'})) {
 1878: 				$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 1879: 				$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 1880: 			    }
 1881: 			}
 1882: 		    }
 1883: 		}
 1884:             }
 1885:           } 
 1886:         }
 1887:         my $adv=0;
 1888:         my $author=0;
 1889:         foreach (keys %allroles) {
 1890:             %thesepriv=();
 1891:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
 1892:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 1893:             foreach (split(/:/,$allroles{$_})) {
 1894:                 if ($_ ne '') {
 1895: 		    my ($privilege,$restrictions)=split(/&/,$_);
 1896:                     if ($restrictions eq '') {
 1897: 			$thesepriv{$privilege}='F';
 1898:                     } else {
 1899:                         if ($thesepriv{$privilege} ne 'F') {
 1900: 			    $thesepriv{$privilege}.=$restrictions;
 1901:                         }
 1902:                     }
 1903:                 }
 1904:             }
 1905:             $thesestr='';
 1906:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 1907:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
 1908:         }
 1909:         $userroles.='user.adv='.$adv."\n".
 1910: 	            'user.author='.$author."\n";
 1911:         $ENV{'user.adv'}=$adv;
 1912:     }
 1913:     return $userroles;  
 1914: }
 1915: 
 1916: # --------------------------------------------------------------- get interface
 1917: 
 1918: sub get {
 1919:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1920:    my $items='';
 1921:    foreach (@$storearr) {
 1922:        $items.=escape($_).'&';
 1923:    }
 1924:    $items=~s/\&$//;
 1925:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1926:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1927:    my $uhome=&homeserver($uname,$udomain);
 1928: 
 1929:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 1930:    my @pairs=split(/\&/,$rep);
 1931:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1932:      return @pairs;
 1933:    }
 1934:    my %returnhash=();
 1935:    my $i=0;
 1936:    foreach (@$storearr) {
 1937:       $returnhash{$_}=unescape($pairs[$i]);
 1938:       $i++;
 1939:    }
 1940:    return %returnhash;
 1941: }
 1942: 
 1943: # --------------------------------------------------------------- del interface
 1944: 
 1945: sub del {
 1946:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1947:    my $items='';
 1948:    foreach (@$storearr) {
 1949:        $items.=escape($_).'&';
 1950:    }
 1951:    $items=~s/\&$//;
 1952:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1953:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1954:    my $uhome=&homeserver($uname,$udomain);
 1955: 
 1956:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 1957: }
 1958: 
 1959: # -------------------------------------------------------------- dump interface
 1960: 
 1961: sub dump {
 1962:    my ($namespace,$udomain,$uname,$regexp)=@_;
 1963:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1964:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1965:    my $uhome=&homeserver($uname,$udomain);
 1966:    if ($regexp) {
 1967:        $regexp=&escape($regexp);
 1968:    } else {
 1969:        $regexp='.';
 1970:    }
 1971:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 1972:    my @pairs=split(/\&/,$rep);
 1973:    my %returnhash=();
 1974:    foreach (@pairs) {
 1975:       my ($key,$value)=split(/=/,$_);
 1976:       $returnhash{unescape($key)}=unescape($value);
 1977:    }
 1978:    return %returnhash;
 1979: }
 1980: 
 1981: # --------------------------------------------------------------- currentdump
 1982: sub currentdump {
 1983:    my ($courseid,$sdom,$sname)=@_;
 1984:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1985:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
 1986:    $sname    = $ENV{'user.name'}         if (! defined($sname));
 1987:    my $uhome = &homeserver($sname,$sdom);
 1988:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 1989:    return if ($rep =~ /^(error:|no_such_host)/);
 1990:    #
 1991:    my %returnhash=();
 1992:    #
 1993:    if ($rep eq "unknown_cmd") { 
 1994:        # an old lond will not know currentdump
 1995:        # Do a dump and make it look like a currentdump
 1996:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 1997:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 1998:        my %hash = @tmp;
 1999:        @tmp=();
 2000:        # Code ripped from lond, essentially.  The only difference
 2001:        # here is the unescaping done by lonnet::dump().  Conceivably
 2002:        # we might run in to problems with parameter names =~ /^v\./
 2003:        while (my ($key,$value) = each(%hash)) {
 2004:            my ($v,$symb,$param) = split(/:/,$key);
 2005:            next if ($v eq 'version' || $symb eq 'keys');
 2006:            next if (exists($returnhash{$symb}) &&
 2007:                     exists($returnhash{$symb}->{$param}) &&
 2008:                     $returnhash{$symb}->{'v.'.$param} > $v);
 2009:            $returnhash{$symb}->{$param}=$value;
 2010:            $returnhash{$symb}->{'v.'.$param}=$v;
 2011:        }
 2012:        #
 2013:        # Remove all of the keys in the hashes which keep track of
 2014:        # the version of the parameter.
 2015:        while (my ($symb,$param_hash) = each(%returnhash)) {
 2016:            # use a foreach because we are going to delete from the hash.
 2017:            foreach my $key (keys(%$param_hash)) {
 2018:                delete($param_hash->{$key}) if ($key =~ /^v\./);
 2019:            }
 2020:        }
 2021:    } else {
 2022:        my @pairs=split(/\&/,$rep);
 2023:        foreach (@pairs) {
 2024:            my ($key,$value)=split(/=/,$_);
 2025:            my ($symb,$param) = split(/:/,$key);
 2026:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2027:                                                           &unescape($value);
 2028:        }
 2029:    }
 2030:    return %returnhash;
 2031: }
 2032: 
 2033: # --------------------------------------------------------------- put interface
 2034: 
 2035: sub put {
 2036:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2037:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2038:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2039:    my $uhome=&homeserver($uname,$udomain);
 2040:    my $items='';
 2041:    foreach (keys %$storehash) {
 2042:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
 2043:    }
 2044:    $items=~s/\&$//;
 2045:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2046: }
 2047: 
 2048: # ------------------------------------------------------ critical put interface
 2049: 
 2050: sub cput {
 2051:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2052:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2053:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2054:    my $uhome=&homeserver($uname,$udomain);
 2055:    my $items='';
 2056:    foreach (keys %$storehash) {
 2057:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
 2058:    }
 2059:    $items=~s/\&$//;
 2060:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 2061: }
 2062: 
 2063: # -------------------------------------------------------------- eget interface
 2064: 
 2065: sub eget {
 2066:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2067:    my $items='';
 2068:    foreach (@$storearr) {
 2069:        $items.=escape($_).'&';
 2070:    }
 2071:    $items=~s/\&$//;
 2072:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2073:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2074:    my $uhome=&homeserver($uname,$udomain);
 2075:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 2076:    my @pairs=split(/\&/,$rep);
 2077:    my %returnhash=();
 2078:    my $i=0;
 2079:    foreach (@$storearr) {
 2080:       $returnhash{$_}=unescape($pairs[$i]);
 2081:       $i++;
 2082:    }
 2083:    return %returnhash;
 2084: }
 2085: 
 2086: # ---------------------------------------------- Custom access rule evaluation
 2087: 
 2088: sub customaccess {
 2089:     my ($priv,$uri)=@_;
 2090:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
 2091:     $urealm=~s/^\W//;
 2092:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 2093:     my $access=0;
 2094:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 2095: 	my ($effect,$realm,$role)=split(/\:/,$_);
 2096:         if ($role) {
 2097: 	   if ($role ne $urole) { next; }
 2098:         }
 2099:         foreach (split(/\s*\,\s*/,$realm)) {
 2100:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 2101:             if ($tdom) {
 2102: 		if ($tdom ne $udom) { next; }
 2103:             }
 2104:             if ($tcrs) {
 2105: 		if ($tcrs ne $ucrs) { next; }
 2106:             }
 2107:             if ($tsec) {
 2108: 		if ($tsec ne $usec) { next; }
 2109:             }
 2110:             $access=($effect eq 'allow');
 2111:             last;
 2112:         }
 2113:     }
 2114:     return $access;
 2115: }
 2116: 
 2117: # ------------------------------------------------- Check for a user privilege
 2118: 
 2119: sub allowed {
 2120:     my ($priv,$uri)=@_;
 2121: 
 2122:     my $orguri=$uri;
 2123:     $uri=&declutter($uri);
 2124: 
 2125: # Free bre access to adm and meta resources
 2126: 
 2127:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 2128: 	return 'F';
 2129:     }
 2130: 
 2131: # Free bre to public access
 2132: 
 2133:     if ($priv eq 'bre') {
 2134:         my $copyright=&metadata($uri,'copyright');
 2135: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
 2136:            return 'F'; 
 2137:         }
 2138:         if ($copyright eq 'priv') {
 2139:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2140: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
 2141: 		return '';
 2142:             }
 2143:         }
 2144:         if ($copyright eq 'domain') {
 2145:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2146: 	    unless (($ENV{'user.domain'} eq $1) ||
 2147:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
 2148: 		return '';
 2149:             }
 2150:         }
 2151:         if ($ENV{'request.role'}=~ /li\.\//) {
 2152:             # Library role, so allow browsing of resources in this domain.
 2153:             return 'F';
 2154:         }
 2155:         if ($copyright eq 'custom') {
 2156: 	    unless (&customaccess($priv,$uri)) { return ''; }
 2157:         }
 2158:     }
 2159:     # Domain coordinator is trying to create a course
 2160:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
 2161:         # uri is the requested domain in this case.
 2162:         # comparison to 'request.role.domain' shows if the user has selected
 2163:         # a role of dc for the domain in question. 
 2164:         return 'F' if ($uri eq $ENV{'request.role.domain'});
 2165:     }
 2166: 
 2167:     my $thisallowed='';
 2168:     my $statecond=0;
 2169:     my $courseprivid='';
 2170: 
 2171: # Course
 2172: 
 2173:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
 2174:        $thisallowed.=$1;
 2175:     }
 2176: 
 2177: # Domain
 2178: 
 2179:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 2180:        =~/$priv\&([^\:]*)/) {
 2181:        $thisallowed.=$1;
 2182:     }
 2183: 
 2184: # Course: uri itself is a course
 2185:     my $courseuri=$uri;
 2186:     $courseuri=~s/\_(\d)/\/$1/;
 2187:     $courseuri=~s/^([^\/])/\/$1/;
 2188: 
 2189:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 2190:        =~/$priv\&([^\:]*)/) {
 2191:        $thisallowed.=$1;
 2192:     }
 2193: 
 2194: # URI is an uploaded document for this course
 2195: 
 2196:     if (($priv eq 'bre') && 
 2197:         ($uri=~/^uploaded\/$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}\/$ENV{'course.'.$ENV{'request.course.id'}.'.num'}/)) {
 2198:         return 'F';
 2199:     }
 2200: # Full access at system, domain or course-wide level? Exit.
 2201: 
 2202:     if ($thisallowed=~/F/) {
 2203: 	return 'F';
 2204:     }
 2205: 
 2206: # If this is generating or modifying users, exit with special codes
 2207: 
 2208:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
 2209: 	return $thisallowed;
 2210:     }
 2211: #
 2212: # Gathered so far: system, domain and course wide privileges
 2213: #
 2214: # Course: See if uri or referer is an individual resource that is part of 
 2215: # the course
 2216: 
 2217:     if ($ENV{'request.course.id'}) {
 2218: 
 2219:        $courseprivid=$ENV{'request.course.id'};
 2220:        if ($ENV{'request.course.sec'}) {
 2221:           $courseprivid.='/'.$ENV{'request.course.sec'};
 2222:        }
 2223:        $courseprivid=~s/\_/\//;
 2224:        my $checkreferer=1;
 2225:        my ($match,$cond)=&is_on_map($uri);
 2226:        if ($match) {
 2227:            $statecond=$cond;
 2228:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2229:                =~/$priv\&([^\:]*)/) {
 2230:                $thisallowed.=$1;
 2231:                $checkreferer=0;
 2232:            }
 2233:        }
 2234:        
 2235:        if ($checkreferer) {
 2236: 	  my $refuri=$ENV{'httpref.'.$orguri};
 2237:             unless ($refuri) {
 2238:                 foreach (keys %ENV) {
 2239: 		    if ($_=~/^httpref\..*\*/) {
 2240: 			my $pattern=$_;
 2241:                         $pattern=~s/^httpref\.\/res\///;
 2242:                         $pattern=~s/\*/\[\^\/\]\+/g;
 2243:                         $pattern=~s/\//\\\//g;
 2244:                         if ($orguri=~/$pattern/) {
 2245: 			    $refuri=$ENV{$_};
 2246:                         }
 2247:                     }
 2248:                 }
 2249:             }
 2250: 
 2251:          if ($refuri) { 
 2252: 	  $refuri=&declutter($refuri);
 2253:           my ($match,$cond)=&is_on_map($refuri);
 2254:             if ($match) {
 2255:               my $refstatecond=$cond;
 2256:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2257:                   =~/$priv\&([^\:]*)/) {
 2258:                   $thisallowed.=$1;
 2259:                   $uri=$refuri;
 2260:                   $statecond=$refstatecond;
 2261:               }
 2262:           }
 2263:         }
 2264:        }
 2265:    }
 2266: 
 2267: #
 2268: # Gathered now: all privileges that could apply, and condition number
 2269: # 
 2270: #
 2271: # Full or no access?
 2272: #
 2273: 
 2274:     if ($thisallowed=~/F/) {
 2275: 	return 'F';
 2276:     }
 2277: 
 2278:     unless ($thisallowed) {
 2279:         return '';
 2280:     }
 2281: 
 2282: # Restrictions exist, deal with them
 2283: #
 2284: #   C:according to course preferences
 2285: #   R:according to resource settings
 2286: #   L:unless locked
 2287: #   X:according to user session state
 2288: #
 2289: 
 2290: # Possibly locked functionality, check all courses
 2291: # Locks might take effect only after 10 minutes cache expiration for other
 2292: # courses, and 2 minutes for current course
 2293: 
 2294:     my $envkey;
 2295:     if ($thisallowed=~/L/) {
 2296:         foreach $envkey (keys %ENV) {
 2297:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 2298:                my $courseid=$2;
 2299:                my $roleid=$1.'.'.$2;
 2300:                $courseid=~s/^\///;
 2301:                my $expiretime=600;
 2302:                if ($ENV{'request.role'} eq $roleid) {
 2303: 		  $expiretime=120;
 2304:                }
 2305: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 2306:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 2307:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 2308: 		   &coursedescription($courseid);
 2309:                }
 2310:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
 2311:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 2312: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 2313:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 2314:                             $ENV{'user.home'},
 2315:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 2316:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 2317:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 2318: 		       return '';
 2319:                    }
 2320:                }
 2321:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
 2322:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 2323: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 2324:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 2325:                             $ENV{'user.home'},
 2326:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 2327:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 2328:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 2329: 		       return '';
 2330:                    }
 2331:                }
 2332: 	   }
 2333:        }
 2334:     }
 2335:    
 2336: #
 2337: # Rest of the restrictions depend on selected course
 2338: #
 2339: 
 2340:     unless ($ENV{'request.course.id'}) {
 2341:        return '1';
 2342:     }
 2343: 
 2344: #
 2345: # Now user is definitely in a course
 2346: #
 2347: 
 2348: 
 2349: # Course preferences
 2350: 
 2351:    if ($thisallowed=~/C/) {
 2352:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 2353:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
 2354:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 2355: 	   =~/$rolecode/) {
 2356:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2357:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 2358:                 $ENV{'request.course.id'});
 2359:            return '';
 2360:        }
 2361: 
 2362:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
 2363: 	   =~/$unamedom/) {
 2364:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2365:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 2366:                 $ENV{'request.course.id'});
 2367:            return '';
 2368:        }
 2369:    }
 2370: 
 2371: # Resource preferences
 2372: 
 2373:    if ($thisallowed=~/R/) {
 2374:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 2375:        if (&metadata($uri,'roledeny')=~/$rolecode/) {
 2376: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2377:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 2378:           return '';
 2379:        }
 2380:    }
 2381: 
 2382: # Restricted by state or randomout?
 2383: 
 2384:    if ($thisallowed=~/X/) {
 2385:       if ($ENV{'acc.randomout'}) {
 2386:          my $symb=&symbread($uri,1);
 2387:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
 2388:             return ''; 
 2389:          }
 2390:       }
 2391:       if (&condval($statecond)) {
 2392: 	 return '2';
 2393:       } else {
 2394:          return '';
 2395:       }
 2396:    }
 2397: 
 2398:    return 'F';
 2399: }
 2400: 
 2401: # --------------------------------------------------- Is a resource on the map?
 2402: 
 2403: sub is_on_map {
 2404:     my $uri=&declutter(shift);
 2405:     my @uriparts=split(/\//,$uri);
 2406:     my $filename=$uriparts[$#uriparts];
 2407:     my $pathname=$uri;
 2408:     $pathname=~s|/\Q$filename\E$||;
 2409:     $pathname=~s/^adm\/wrapper\///;    
 2410:     #Trying to find the conditional for the file
 2411:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 2412: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 2413:     if ($match) {
 2414: 	return (1,$1);
 2415:     } else {
 2416: 	return (0,0);
 2417:     }
 2418: }
 2419: 
 2420: # ----------------------------------------------------------------- Define Role
 2421: 
 2422: sub definerole {
 2423:   if (allowed('mcr','/')) {
 2424:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 2425:     foreach (split('/',$sysrole)) {
 2426: 	my ($crole,$cqual)=split(/\&/,$_);
 2427:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
 2428:         if ($pr{'cr:s'}=~/$crole\&/) {
 2429: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
 2430:                return "refused:s:$crole&$cqual"; 
 2431:             }
 2432:         }
 2433:     }
 2434:     foreach (split('/',$domrole)) {
 2435: 	my ($crole,$cqual)=split(/\&/,$_);
 2436:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
 2437:         if ($pr{'cr:d'}=~/$crole\&/) {
 2438: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
 2439:                return "refused:d:$crole&$cqual"; 
 2440:             }
 2441:         }
 2442:     }
 2443:     foreach (split('/',$courole)) {
 2444: 	my ($crole,$cqual)=split(/\&/,$_);
 2445:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
 2446:         if ($pr{'cr:c'}=~/$crole\&/) {
 2447: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
 2448:                return "refused:c:$crole&$cqual"; 
 2449:             }
 2450:         }
 2451:     }
 2452:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2453:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 2454: 	        "rolesdef_$rolename=".
 2455:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 2456:     return reply($command,$ENV{'user.home'});
 2457:   } else {
 2458:     return 'refused';
 2459:   }
 2460: }
 2461: 
 2462: # ---------------- Make a metadata query against the network of library servers
 2463: 
 2464: sub metadata_query {
 2465:     my ($query,$custom,$customshow,$server_array)=@_;
 2466:     my %rhash;
 2467:     my @server_list = (defined($server_array) ? @$server_array
 2468:                                               : keys(%libserv) );
 2469:     for my $server (@server_list) {
 2470: 	unless ($custom or $customshow) {
 2471: 	    my $reply=&reply("querysend:".&escape($query),$server);
 2472: 	    $rhash{$server}=$reply;
 2473: 	}
 2474: 	else {
 2475: 	    my $reply=&reply("querysend:".&escape($query).':'.
 2476: 			     &escape($custom).':'.&escape($customshow),
 2477: 			     $server);
 2478: 	    $rhash{$server}=$reply;
 2479: 	}
 2480:     }
 2481:     return \%rhash;
 2482: }
 2483: 
 2484: # ----------------------------------------- Send log queries and wait for reply
 2485: 
 2486: sub log_query {
 2487:     my ($uname,$udom,$query,%filters)=@_;
 2488:     my $uhome=&homeserver($uname,$udom);
 2489:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 2490:     my $uhost=$hostname{$uhome};
 2491:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 2492:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 2493:                        $uhome);
 2494:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
 2495:     return get_query_reply($queryid);
 2496: }
 2497: 
 2498: sub get_query_reply {
 2499:     my $queryid=shift;
 2500:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 2501:     my $reply='';
 2502:     for (1..100) {
 2503: 	sleep 2;
 2504:         if (-e $replyfile.'.end') {
 2505: 	    if (my $fh=Apache::File->new($replyfile)) {
 2506:                $reply.=<$fh>;
 2507:                $fh->close;
 2508: 	   } else { return 'error: reply_file_error'; }
 2509:            return &unescape($reply);
 2510: 	}
 2511:     }
 2512:     return 'timeout:'.$queryid;
 2513: }
 2514: 
 2515: sub courselog_query {
 2516: #
 2517: # possible filters:
 2518: # url: url or symb
 2519: # username
 2520: # domain
 2521: # action: view, submit, grade
 2522: # start: timestamp
 2523: # end: timestamp
 2524: #
 2525:     my (%filters)=@_;
 2526:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
 2527:     if ($filters{'url'}) {
 2528: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 2529:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 2530:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 2531:     }
 2532:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 2533:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 2534:     return &log_query($cname,$cdom,'courselog',%filters);
 2535: }
 2536: 
 2537: sub userlog_query {
 2538:     my ($uname,$udom,%filters)=@_;
 2539:     return &log_query($uname,$udom,'userlog',%filters);
 2540: }
 2541: 
 2542: # ------------------------------------------------------------------ Plain Text
 2543: 
 2544: sub plaintext {
 2545:     my $short=shift;
 2546:     return $prp{$short};
 2547: }
 2548: 
 2549: # ----------------------------------------------------------------- Assign Role
 2550: 
 2551: sub assignrole {
 2552:     my ($udom,$uname,$url,$role,$end,$start)=@_;
 2553:     my $mrole;
 2554:     if ($role =~ /^cr\//) {
 2555: 	unless (&allowed('ccr',$url)) {
 2556:            &logthis('Refused custom assignrole: '.
 2557:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2558: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2559:            return 'refused'; 
 2560:         }
 2561:         $mrole='cr';
 2562:     } else {
 2563:         my $cwosec=$url;
 2564:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 2565:         unless (&allowed('c'.$role,$cwosec)) { 
 2566:            &logthis('Refused assignrole: '.
 2567:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2568: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2569:            return 'refused'; 
 2570:         }
 2571:         $mrole=$role;
 2572:     }
 2573:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2574:                 "$udom:$uname:$url".'_'."$mrole=$role";
 2575:     if ($end) { $command.='_'.$end; }
 2576:     if ($start) {
 2577: 	if ($end) { 
 2578:            $command.='_'.$start; 
 2579:         } else {
 2580:            $command.='_0_'.$start;
 2581:         }
 2582:     }
 2583:     my $answer=&reply($command,&homeserver($uname,$udom));
 2584:     if ($answer eq 'ok') {
 2585: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
 2586:     }
 2587:     return $answer;
 2588: }
 2589: 
 2590: # -------------------------------------------------- Modify user authentication
 2591: # Overrides without validation
 2592: 
 2593: sub modifyuserauth {
 2594:     my ($udom,$uname,$umode,$upass)=@_;
 2595:     my $uhome=&homeserver($uname,$udom);
 2596:     unless (&allowed('mau',$udom)) { return 'refused'; }
 2597:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 2598:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2599:              ' in domain '.$ENV{'request.role.domain'});  
 2600:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 2601: 		     &escape($upass),$uhome);
 2602:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
 2603:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 2604:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2605:     &log($udom,,$uname,$uhome,
 2606:         'Authentication changed by '.$ENV{'user.domain'}.', '.
 2607:                                      $ENV{'user.name'}.', '.$umode.
 2608:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2609:     unless ($reply eq 'ok') {
 2610:         &logthis('Authentication mode error: '.$reply);
 2611: 	return 'error: '.$reply;
 2612:     }   
 2613:     return 'ok';
 2614: }
 2615: 
 2616: # --------------------------------------------------------------- Modify a user
 2617: 
 2618: sub modifyuser {
 2619:     my ($udom,    $uname, $uid,
 2620:         $umode,   $upass, $first,
 2621:         $middle,  $last,  $gene,
 2622:         $forceid, $desiredhome)=@_;
 2623:     $udom=~s/\W//g;
 2624:     $uname=~s/\W//g;
 2625:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 2626:              $umode.', '.$first.', '.$middle.', '.
 2627: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 2628:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 2629:                                      ' desiredhome not specified'). 
 2630:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2631:              ' in domain '.$ENV{'request.role.domain'});
 2632:     my $uhome=&homeserver($uname,$udom,'true');
 2633: # ----------------------------------------------------------------- Create User
 2634:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
 2635:         my $unhome='';
 2636:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 2637:             $unhome = $desiredhome;
 2638: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 2639: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 2640:         } else { # load balancing routine for determining $unhome
 2641:             my $tryserver;
 2642:             my $loadm=10000000;
 2643:             foreach $tryserver (keys %libserv) {
 2644: 	       if ($hostdom{$tryserver} eq $udom) {
 2645:                   my $answer=reply('load',$tryserver);
 2646:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 2647: 		      $loadm=$answer;
 2648:                       $unhome=$tryserver;
 2649:                   }
 2650: 	       }
 2651: 	    }
 2652:         }
 2653:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 2654: 	    return 'error: unable to find a home server for '.$uname.
 2655:                    ' in domain '.$udom;
 2656:         }
 2657:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 2658:                          &escape($upass),$unhome);
 2659: 	unless ($reply eq 'ok') {
 2660:             return 'error: '.$reply;
 2661:         }   
 2662:         $uhome=&homeserver($uname,$udom,'true');
 2663:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 2664: 	    return 'error: verify home';
 2665:         }
 2666:     }   # End of creation of new user
 2667: # ---------------------------------------------------------------------- Add ID
 2668:     if ($uid) {
 2669:        $uid=~tr/A-Z/a-z/;
 2670:        my %uidhash=&idrget($udom,$uname);
 2671:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 2672:          && (!$forceid)) {
 2673: 	  unless ($uid eq $uidhash{$uname}) {
 2674: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
 2675:           }
 2676:        } else {
 2677: 	  &idput($udom,($uname => $uid));
 2678:        }
 2679:     }
 2680: # -------------------------------------------------------------- Add names, etc
 2681:     my @tmp=&get('environment',
 2682: 		   ['firstname','middlename','lastname','generation'],
 2683: 		   $udom,$uname);
 2684:     my %names;
 2685:     if ($tmp[0] =~ m/^error:.*/) { 
 2686:         %names=(); 
 2687:     } else {
 2688:         %names = @tmp;
 2689:     }
 2690:     if ($first)  { $names{'firstname'}  = $first; }
 2691:     if ($middle) { $names{'middlename'} = $middle; }
 2692:     if ($last)   { $names{'lastname'}   = $last; }
 2693:     if ($gene)   { $names{'generation'} = $gene; }
 2694:     my $reply = &put('environment', \%names, $udom,$uname);
 2695:     if ($reply ne 'ok') { return 'error: '.$reply; }
 2696:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 2697:              $umode.', '.$first.', '.$middle.', '.
 2698: 	     $last.', '.$gene.' by '.
 2699:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2700:     return 'ok';
 2701: }
 2702: 
 2703: # -------------------------------------------------------------- Modify student
 2704: 
 2705: sub modifystudent {
 2706:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 2707:         $end,$start,$forceid,$desiredhome)=@_;
 2708:     my $cid='';
 2709:     unless ($cid=$ENV{'request.course.id'}) {
 2710: 	return 'not_in_class';
 2711:     }
 2712: # --------------------------------------------------------------- Make the user
 2713:     my $reply=&modifyuser
 2714: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 2715:          $desiredhome);
 2716:     unless ($reply eq 'ok') { return $reply; }
 2717:     # This will cause &modify_student_enrollment to get the uid from the
 2718:     # students environment
 2719:     $uid = undef if (!$forceid);
 2720:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
 2721:                                         $last,$gene,$usec,$end,$start);
 2722:     return $reply;
 2723: }
 2724: 
 2725: sub modify_student_enrollment {
 2726:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
 2727:     # Get the course id from the environment
 2728:     my $cid='';
 2729:     unless ($cid=$ENV{'request.course.id'}) {
 2730: 	return 'not_in_class';
 2731:     }
 2732:     # Make sure the user exists
 2733:     my $uhome=&homeserver($uname,$udom);
 2734:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2735: 	return 'error: no such user';
 2736:     }
 2737:     #
 2738:     # Get student data if we were not given enough information
 2739:     if (!defined($first)  || $first  eq '' || 
 2740:         !defined($last)   || $last   eq '' || 
 2741:         !defined($uid)    || $uid    eq '' || 
 2742:         !defined($middle) || $middle eq '' || 
 2743:         !defined($gene)   || $gene   eq '') {
 2744:         # They did not supply us with enough data to enroll the student, so
 2745:         # we need to pick up more information.
 2746:         my %tmp = &get('environment',
 2747:                        ['firstname','middlename','lastname', 'generation','id']
 2748:                        ,$udom,$uname);
 2749: 
 2750:         foreach (keys(%tmp)) {
 2751:             &logthis("key $_ = ".$tmp{$_});
 2752:         }
 2753:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 2754:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 2755:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 2756:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 2757:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 2758:     }
 2759:     my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
 2760:                                                            $first,$middle);
 2761:     my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 2762: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
 2763:                       &escape($uname.':'.$udom).'='.
 2764:                       &escape(join(':',$end,$start,$uid,$usec,$fullname)),
 2765: 	              $ENV{'course.'.$cid.'.home'});
 2766:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 2767: 	return 'error: '.$reply;
 2768:     }
 2769:     # Add student role to user
 2770:     my $uurl='/'.$cid;
 2771:     $uurl=~s/\_/\//g;
 2772:     if ($usec) {
 2773: 	$uurl.='/'.$usec;
 2774:     }
 2775:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 2776: }
 2777: 
 2778: # ------------------------------------------------- Write to course preferences
 2779: 
 2780: sub writecoursepref {
 2781:     my ($courseid,%prefs)=@_;
 2782:     $courseid=~s/^\///;
 2783:     $courseid=~s/\_/\//g;
 2784:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2785:     my $chome=homeserver($cnum,$cdomain);
 2786:     if (($chome eq '') || ($chome eq 'no_host')) { 
 2787: 	return 'error: no such course';
 2788:     }
 2789:     my $cstring='';
 2790:     foreach (keys %prefs) {
 2791: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 2792:     }
 2793:     $cstring=~s/\&$//;
 2794:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 2795: }
 2796: 
 2797: # ---------------------------------------------------------- Make/modify course
 2798: 
 2799: sub createcourse {
 2800:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
 2801:     $url=&declutter($url);
 2802:     my $cid='';
 2803:     unless (&allowed('ccc',$udom)) {
 2804:         return 'refused';
 2805:     }
 2806: # ------------------------------------------------------------------- Create ID
 2807:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2808:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2809: # ----------------------------------------------- Make sure that does not exist
 2810:    my $uhome=&homeserver($uname,$udom,'true');
 2811:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2812:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2813:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2814:        $uhome=&homeserver($uname,$udom,'true');       
 2815:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2816:            return 'error: unable to generate unique course-ID';
 2817:        } 
 2818:    }
 2819: # ------------------------------------------------ Check supplied server name
 2820:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
 2821:     if (! exists($libserv{$course_server})) {
 2822:         return 'error:bad server name '.$course_server;
 2823:     }
 2824: # ------------------------------------------------------------- Make the course
 2825:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 2826:                       $course_server);
 2827:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 2828:     $uhome=&homeserver($uname,$udom,'true');
 2829:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2830: 	return 'error: no such course';
 2831:     }
 2832: # ----------------------------------------------------------------- Course made
 2833:     my $topurl=$url;
 2834:     unless ($nonstandard) {
 2835: # ------------------------------------------ For standard courses, make top url
 2836:         my $mapurl=&clutter($url);
 2837:         if ($mapurl eq '/res/') { $mapurl=''; }
 2838:         $ENV{'form.initmap'}=(<<ENDINITMAP);
 2839: <map>
 2840: <resource id="1" type="start"></resource>
 2841: <resource id="2" src="$mapurl"></resource>
 2842: <resource id="3" type="finish"></resource>
 2843: <link index="1" from="1" to="2"></link>
 2844: <link index="2" from="2" to="3"></link>
 2845: </map>
 2846: ENDINITMAP
 2847:         $topurl=&declutter(
 2848:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
 2849:                           );
 2850:     }
 2851: # ----------------------------------------------------------- Write preferences
 2852:     &writecoursepref($udom.'_'.$uname,
 2853:                      ('description' => $description,
 2854:                       'url'         => $topurl));
 2855:     return '/'.$udom.'/'.$uname;
 2856: }
 2857: 
 2858: # ---------------------------------------------------------- Assign Custom Role
 2859: 
 2860: sub assigncustomrole {
 2861:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
 2862:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 2863:                        $end,$start);
 2864: }
 2865: 
 2866: # ----------------------------------------------------------------- Revoke Role
 2867: 
 2868: sub revokerole {
 2869:     my ($udom,$uname,$url,$role)=@_;
 2870:     my $now=time;
 2871:     return &assignrole($udom,$uname,$url,$role,$now);
 2872: }
 2873: 
 2874: # ---------------------------------------------------------- Revoke Custom Role
 2875: 
 2876: sub revokecustomrole {
 2877:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
 2878:     my $now=time;
 2879:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
 2880: }
 2881: 
 2882: # ------------------------------------------------------------ Directory lister
 2883: 
 2884: sub dirlist {
 2885:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 2886: 
 2887:     $uri=~s/^\///;
 2888:     $uri=~s/\/$//;
 2889:     my ($udom, $uname);
 2890:     (undef,$udom,$uname)=split(/\//,$uri);
 2891:     if(defined($userdomain)) {
 2892:         $udom = $userdomain;
 2893:     }
 2894:     if(defined($username)) {
 2895:         $uname = $username;
 2896:     }
 2897: 
 2898:     my $dirRoot = $perlvar{'lonDocRoot'};
 2899:     if(defined($alternateDirectoryRoot)) {
 2900:         $dirRoot = $alternateDirectoryRoot;
 2901:         $dirRoot =~ s/\/$//;
 2902:     }
 2903: 
 2904:     if($udom) {
 2905:         if($uname) {
 2906:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
 2907:                               homeserver($uname,$udom));
 2908:             return split(/:/,$listing);
 2909:         } elsif(!defined($alternateDirectoryRoot)) {
 2910:             my $tryserver;
 2911:             my %allusers=();
 2912:             foreach $tryserver (keys %libserv) {
 2913:                 if($hostdom{$tryserver} eq $udom) {
 2914:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 2915:                                       $udom, $tryserver);
 2916:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 2917:                         && ($listing ne 'con_lost')) {
 2918:                         foreach (split(/:/,$listing)) {
 2919:                             my ($entry,@stat)=split(/&/,$_);
 2920:                             $allusers{$entry}=1;
 2921:                         }
 2922:                     }
 2923:                 }
 2924:             }
 2925:             my $alluserstr='';
 2926:             foreach (sort keys %allusers) {
 2927:                 $alluserstr.=$_.'&user:';
 2928:             }
 2929:             $alluserstr=~s/:$//;
 2930:             return split(/:/,$alluserstr);
 2931:         } else {
 2932:             my @emptyResults = ();
 2933:             push(@emptyResults, 'missing user name');
 2934:             return split(':',@emptyResults);
 2935:         }
 2936:     } elsif(!defined($alternateDirectoryRoot)) {
 2937:         my $tryserver;
 2938:         my %alldom=();
 2939:         foreach $tryserver (keys %libserv) {
 2940:             $alldom{$hostdom{$tryserver}}=1;
 2941:         }
 2942:         my $alldomstr='';
 2943:         foreach (sort keys %alldom) {
 2944:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
 2945:         }
 2946:         $alldomstr=~s/:$//;
 2947:         return split(/:/,$alldomstr);       
 2948:     } else {
 2949:         my @emptyResults = ();
 2950:         push(@emptyResults, 'missing domain');
 2951:         return split(':',@emptyResults);
 2952:     }
 2953: }
 2954: 
 2955: # --------------------------------------------- GetFileTimestamp
 2956: # This function utilizes dirlist and returns the date stamp for
 2957: # when it was last modified.  It will also return an error of -1
 2958: # if an error occurs
 2959: 
 2960: sub GetFileTimestamp {
 2961:     my ($studentDomain,$studentName,$filename,$root)=@_;
 2962:     $studentDomain=~s/\W//g;
 2963:     $studentName=~s/\W//g;
 2964:     my $subdir=$studentName.'__';
 2965:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 2966:     my $proname="$studentDomain/$subdir/$studentName";
 2967:     $proname .= '/'.$filename;
 2968:     my @dir = &Apache::lonnet::dirlist($proname, $studentDomain, $studentName,
 2969:                                        $root);
 2970:     my $fileStat = $dir[0];
 2971:     my @stats = split('&', $fileStat);
 2972:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 2973:         return $stats[9];
 2974:     } else {
 2975:         return -1;
 2976:     }
 2977: }
 2978: 
 2979: # -------------------------------------------------------- Value of a Condition
 2980: 
 2981: sub directcondval {
 2982:     my $number=shift;
 2983:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 2984:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 2985:     } else {
 2986:        return 2;
 2987:     }
 2988: }
 2989: 
 2990: sub condval {
 2991:     my $condidx=shift;
 2992:     my $result=0;
 2993:     my $allpathcond='';
 2994:     foreach (split(/\|/,$condidx)) {
 2995:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 2996: 	   $allpathcond.=
 2997:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 2998:        }
 2999:     }
 3000:     $allpathcond=~s/\|$//;
 3001:     if ($ENV{'request.course.id'}) {
 3002:        if ($allpathcond) {
 3003:           my $operand='|';
 3004: 	  my @stack;
 3005:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 3006:               if ($_ eq '(') {
 3007:                  push @stack,($operand,$result)
 3008:               } elsif ($_ eq ')') {
 3009:                   my $before=pop @stack;
 3010: 		  if (pop @stack eq '&') {
 3011: 		      $result=$result>$before?$before:$result;
 3012:                   } else {
 3013:                       $result=$result>$before?$result:$before;
 3014:                   }
 3015:               } elsif (($_ eq '&') || ($_ eq '|')) {
 3016:                   $operand=$_;
 3017:               } else {
 3018:                   my $new=directcondval($_);
 3019:                   if ($operand eq '&') {
 3020:                      $result=$result>$new?$new:$result;
 3021:                   } else {
 3022:                      $result=$result>$new?$result:$new;
 3023:                   }
 3024:               }
 3025:           }
 3026:        }
 3027:     }
 3028:     return $result;
 3029: }
 3030: 
 3031: # ---------------------------------------------------- Devalidate courseresdata
 3032: 
 3033: sub devalidatecourseresdata {
 3034:     my ($coursenum,$coursedomain)=@_;
 3035:     my $hashid=$coursenum.':'.$coursedomain;
 3036:     delete $courseresdatacache{$hashid.'.time'};
 3037: }
 3038: 
 3039: # --------------------------------------------------- Course Resourcedata Query
 3040: 
 3041: sub courseresdata {
 3042:     my ($coursenum,$coursedomain,@which)=@_;
 3043:     my $coursehom=&homeserver($coursenum,$coursedomain);
 3044:     my $hashid=$coursenum.':'.$coursedomain;
 3045:     my $dodump=0;
 3046:     if (!defined($courseresdatacache{$hashid.'.time'})) {
 3047: 	$dodump=1;
 3048:     } else {
 3049: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
 3050:     }
 3051:     if ($dodump) {
 3052: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 3053: 	my ($tmp) = keys(%dumpreply);
 3054: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 3055: 	    $courseresdatacache{$hashid.'.time'}=time;
 3056: 	    $courseresdatacache{$hashid}=\%dumpreply;
 3057: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 3058: 	    return $tmp;
 3059: 	}
 3060:     }
 3061:     foreach my $item (@which) {
 3062: 	if (defined($courseresdatacache{$hashid}->{$item})) {
 3063: 	    return $courseresdatacache{$hashid}->{$item};
 3064: 	}
 3065:     }
 3066:     return undef;
 3067: }
 3068: 
 3069: # --------------------------------------------------------- Value of a Variable
 3070: 
 3071: sub EXT {
 3072:     my ($varname,$symbparm,$udom,$uname,)=@_;
 3073: 
 3074:     unless ($varname) { return ''; }
 3075:     #get real user name/domain, courseid and symb
 3076:     my $courseid;
 3077:     if (!($uname && $udom)) {
 3078:       (my $cursymb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 3079:       if (!$symbparm) {	$symbparm=$cursymb; }
 3080:     } else {
 3081: 	$courseid=$ENV{'request.course.id'};
 3082:     }
 3083:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 3084:     my $rest;
 3085:     if (defined($therest[0])) {
 3086:        $rest=join('.',@therest);
 3087:     } else {
 3088:        $rest='';
 3089:     }
 3090: 
 3091:     my $qualifierrest=$qualifier;
 3092:     if ($rest) { $qualifierrest.='.'.$rest; }
 3093:     my $spacequalifierrest=$space;
 3094:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 3095:     if ($realm eq 'user') {
 3096: # --------------------------------------------------------------- user.resource
 3097: 	if ($space eq 'resource') {
 3098: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
 3099: 		return $Apache::lonhomework::history{$qualifierrest};
 3100: 	    } else {
 3101: 		my %restored=&restore($symbparm,$courseid,$udom,$uname);
 3102: 		return $restored{$qualifierrest};
 3103: 	    }
 3104: # ----------------------------------------------------------------- user.access
 3105:         } elsif ($space eq 'access') {
 3106: 	    # FIXME - not supporting calls for a specific user
 3107:             return &allowed($qualifier,$rest);
 3108: # ------------------------------------------ user.preferences, user.environment
 3109:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 3110: 	    if (($uname eq $ENV{'user.name'}) &&
 3111: 		($udom eq $ENV{'user.domain'})) {
 3112: 		return $ENV{join('.',('environment',$qualifierrest))};
 3113: 	    } else {
 3114: 		my %returnhash=&userenvironment($udom,$uname,$qualifierrest);
 3115: 		return $returnhash{$qualifierrest};
 3116: 	    }
 3117: # ----------------------------------------------------------------- user.course
 3118:         } elsif ($space eq 'course') {
 3119: 	    # FIXME - not supporting calls for a specific user
 3120:             return $ENV{join('.',('request.course',$qualifier))};
 3121: # ------------------------------------------------------------------- user.role
 3122:         } elsif ($space eq 'role') {
 3123: 	    # FIXME - not supporting calls for a specific user
 3124:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 3125:             if ($qualifier eq 'value') {
 3126: 		return $role;
 3127:             } elsif ($qualifier eq 'extent') {
 3128:                 return $where;
 3129:             }
 3130: # ----------------------------------------------------------------- user.domain
 3131:         } elsif ($space eq 'domain') {
 3132:             return $udom;
 3133: # ------------------------------------------------------------------- user.name
 3134:         } elsif ($space eq 'name') {
 3135:             return $uname;
 3136: # ---------------------------------------------------- Any other user namespace
 3137:         } else {
 3138:             my %reply=&get($space,[$qualifierrest],$udom,$uname);
 3139:             return $reply{$qualifierrest};
 3140:         }
 3141:     } elsif ($realm eq 'query') {
 3142: # ---------------------------------------------- pull stuff out of query string
 3143:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},[$space]);
 3144: 	return $ENV{'form.'.$space}; 
 3145:    } elsif ($realm eq 'request') {
 3146: # ------------------------------------------------------------- request.browser
 3147:         if ($space eq 'browser') {
 3148: 	    return $ENV{'browser.'.$qualifier};
 3149: # ------------------------------------------------------------ request.filename
 3150:         } else {
 3151:             return $ENV{'request.'.$spacequalifierrest};
 3152:         }
 3153:     } elsif ($realm eq 'course') {
 3154: # ---------------------------------------------------------- course.description
 3155:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
 3156:     } elsif ($realm eq 'resource') {
 3157: 
 3158: 	if ($courseid eq $ENV{'request.course.id'}) {
 3159: 
 3160: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 3161: 
 3162: # ----------------------------------------------------- Cascading lookup scheme
 3163: 	    if (!$symbparm) { $symbparm=&symbread(); }
 3164: 	    my $symbp=$symbparm;
 3165: 	    my $mapp=(split(/\_\_\_/,$symbp))[0];
 3166: 
 3167: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 3168: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 3169: 
 3170: 	    my $section;
 3171: 	    if (($ENV{'user.name'} eq $uname) &&
 3172: 		($ENV{'user.domain'} eq $udom)) {
 3173: 		$section=$ENV{'request.course.sec'};
 3174: 	    } else {
 3175: 		$section=&usection($udom,$uname,$courseid);
 3176: 	    }
 3177: 
 3178: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 3179: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 3180: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 3181: 
 3182: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
 3183: 	    my $courselevelr=$courseid.'.'.$symbparm;
 3184: 	    my $courselevelm=$courseid.'.'.$mapparm;
 3185: 
 3186: # ----------------------------------------------------------- first, check user
 3187: 	    #most student don't have any data set, check if there is some data
 3188:             #every thirty minutes
 3189: 	    if (!
 3190: 		(exists($ENV{'cache.studentresdata'})
 3191: 		    && (($ENV{'cache.studentresdata'}+1800) > time))) {
 3192: 		my %resourcedata=&get('resourcedata',
 3193: 				      [$courselevelr,$courselevelm,$courselevel],
 3194: 				      $udom,$uname);
 3195: 		my ($tmp)=keys(%resourcedata);
 3196: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 3197: 		    if ($resourcedata{$courselevelr}) {
 3198: 			return $resourcedata{$courselevelr}; }
 3199: 		    if ($resourcedata{$courselevelm}) {
 3200: 			return $resourcedata{$courselevelm}; }
 3201: 		    if ($resourcedata{$courselevel}) {
 3202: 			return $resourcedata{$courselevel}; }
 3203: 		} else {
 3204: 		    if ($tmp!~/No such file/) {
 3205: 			&logthis("<font color=blue>WARNING:".
 3206: 				 " Trying to get resource data for ".
 3207: 				 $uname." at ".$udom.": ".
 3208: 				 $tmp."</font>");
 3209: 		    } elsif ($tmp=~/error:No such file/) {
 3210: 			$ENV{'cache.studentresdata'}=time;
 3211: 			&appenv(('cache.studentresdata'=>
 3212: 				 $ENV{'cache.studentresdata'}));
 3213: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 3214: 			return $tmp;
 3215: 		    }
 3216: 		}
 3217: 	    }
 3218: 
 3219: # -------------------------------------------------------- second, check course
 3220: 
 3221: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
 3222: 					  $ENV{'course.'.$courseid.'.domain'},
 3223: 					  ($seclevelr,$seclevelm,$seclevel,
 3224: 					   $courselevelr,$courselevelm,
 3225: 					   $courselevel));
 3226: 	    if (defined($coursereply)) { return $coursereply; }
 3227: 
 3228: # ------------------------------------------------------ third, check map parms
 3229: 	    my %parmhash=();
 3230: 	    my $thisparm='';
 3231: 	    if (tie(%parmhash,'GDBM_File',
 3232: 		    $ENV{'request.course.fn'}.'_parms.db',
 3233: 		    &GDBM_READER(),0640)) {
 3234: 		$thisparm=$parmhash{$symbparm};
 3235: 		untie(%parmhash);
 3236: 	    }
 3237: 	    if ($thisparm) { return $thisparm; }
 3238: 	}
 3239: # --------------------------------------------- last, look in resource metadata
 3240: 
 3241: 	$spacequalifierrest=~s/\./\_/;
 3242: 	my $filename;
 3243: 	if (!$symbparm) { $symbparm=&symbread(); }
 3244: 	if ($symbparm) {
 3245: 	    $filename=(split(/\_\_\_/,$symbparm))[2];
 3246: 	} else {
 3247: 	    $filename=$ENV{'request.filename'};
 3248: 	}
 3249: 	my $metadata=&metadata($filename,$spacequalifierrest);
 3250: 	if (defined($metadata)) { return $metadata; }
 3251: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 3252: 	if (defined($metadata)) { return $metadata; }
 3253: 
 3254: # ------------------------------------------------------------------ Cascade up
 3255: 	unless ($space eq '0') {
 3256: 	    my @parts=split(/_/,$space);
 3257: 	    my $id=pop(@parts);
 3258: 	    my $part=join('_',@parts);
 3259: 	    if ($part eq '') { $part='0'; }
 3260: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 3261: 				 $symbparm,$udom,$uname);
 3262: 	    if (defined($partgeneral)) { return $partgeneral; }
 3263: 	}
 3264: 
 3265: # ---------------------------------------------------- Any other user namespace
 3266:     } elsif ($realm eq 'environment') {
 3267: # ----------------------------------------------------------------- environment
 3268: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
 3269: 	    return $ENV{'environment.'.$spacequalifierrest};
 3270: 	} else {
 3271: 	    my %returnhash=&userenvironment($udom,$uname,
 3272: 					    $spacequalifierrest);
 3273: 	    return $returnhash{$spacequalifierrest};
 3274: 	}
 3275:     } elsif ($realm eq 'system') {
 3276: # ----------------------------------------------------------------- system.time
 3277: 	if ($space eq 'time') {
 3278: 	    return time;
 3279:         }
 3280:     }
 3281:     return '';
 3282: }
 3283: 
 3284: sub add_prefix_and_part {
 3285:     my ($prefix,$part)=@_;
 3286:     my $keyroot;
 3287:     if (defined($prefix) && $prefix !~ /^__/) {
 3288: 	# prefix that has a part already
 3289: 	$keyroot=$prefix;
 3290:     } elsif (defined($prefix)) {
 3291: 	# prefix that is missing a part
 3292: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 3293:     } else {
 3294: 	# no prefix at all
 3295: 	if (defined($part)) { $keyroot='_'.$part; }
 3296:     }
 3297:     return $keyroot;
 3298: }
 3299: 
 3300: # ---------------------------------------------------------------- Get metadata
 3301: 
 3302: sub metadata {
 3303:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 3304: 
 3305:     $uri=&declutter($uri);
 3306:     # if it is a non metadata possible uri return quickly
 3307:     if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
 3308:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
 3309: 	return '';
 3310:     }
 3311:     my $filename=$uri;
 3312:     $uri=~s/\.meta$//;
 3313: #
 3314: # Is the metadata already cached?
 3315: # Look at timestamp of caching
 3316: # Everything is cached by the main uri, libraries are never directly cached
 3317: #
 3318:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
 3319: #
 3320: # Is this a recursive call for a library?
 3321: #
 3322:         if ($liburi) {
 3323: 	    $liburi=&declutter($liburi);
 3324:             $filename=$liburi;
 3325:         }
 3326:         my %metathesekeys=();
 3327:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 3328: 	my $metastring=&getfile(&filelocation('',&clutter($filename)));
 3329:         my $parser=HTML::LCParser->new(\$metastring);
 3330:         my $token;
 3331:         undef %metathesekeys;
 3332:         while ($token=$parser->get_token) {
 3333: 	    if ($token->[0] eq 'S') {
 3334: 		if (defined($token->[2]->{'package'})) {
 3335: #
 3336: # This is a package - get package info
 3337: #
 3338: 		    my $package=$token->[2]->{'package'};
 3339: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3340: 		    if (defined($token->[2]->{'id'})) { 
 3341: 			$keyroot.='_'.$token->[2]->{'id'}; 
 3342: 		    }
 3343: 		    if ($metacache{$uri.':packages'}) {
 3344: 			$metacache{$uri.':packages'}.=','.$package.$keyroot;
 3345: 		    } else {
 3346: 			$metacache{$uri.':packages'}=$package.$keyroot;
 3347: 		    }
 3348: 		    foreach (keys %packagetab) {
 3349: 			if ($_=~/^$package\&/) {
 3350: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 3351: 			    my $value=$packagetab{$_};
 3352: 			    my $part=$keyroot;
 3353: 			    $part=~s/^\_//;
 3354: 			    if ($subp eq 'display') {
 3355: 				$value.=' [Part: '.$part.']';
 3356: 			    }
 3357: 			    my $unikey='parameter'.$keyroot.'_'.$name;
 3358: 			    if ($subp eq 'default') { $unikey='parameter_0_'.$name; }
 3359: 			    $metathesekeys{$unikey}=1;
 3360: 			    $metacache{$uri.':'.$unikey.'.part'}=$part;
 3361: 			    unless (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
 3362: 				$metacache{$uri.':'.$unikey.'.'.$subp}=$value;
 3363: 			    }
 3364: 			    if (defined($metacache{$uri.':'.$unikey.'.default'})) {
 3365: 				$metacache{$uri.':'.$unikey}=
 3366: 				    $metacache{$uri.':'.$unikey.'.default'}
 3367: 				}
 3368: 			}
 3369: 		    }
 3370: 		} else {
 3371: #
 3372: # This is not a package - some other kind of start tag
 3373: #
 3374: 		    my $entry=$token->[1];
 3375: 		    my $unikey;
 3376: 		    if ($entry eq 'import') {
 3377: 			$unikey='';
 3378: 		    } else {
 3379: 			$unikey=$entry;
 3380: 		    }
 3381: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3382: 
 3383: 		    if (defined($token->[2]->{'id'})) { 
 3384: 			$unikey.='_'.$token->[2]->{'id'}; 
 3385: 		    }
 3386: 
 3387: 		    if ($entry eq 'import') {
 3388: #
 3389: # Importing a library here
 3390: #
 3391: 			if ($depthcount<20) {
 3392: 			    my $location=$parser->get_text('/import');
 3393: 			    my $dir=$filename;
 3394: 			    $dir=~s|[^/]*$||;
 3395: 			    $location=&filelocation($dir,$location);
 3396: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 3397: 							       $location,$unikey,
 3398: 							       $depthcount+1)))) {
 3399: 				$metathesekeys{$_}=1;
 3400: 			    }
 3401: 			}
 3402: 		    } else { 
 3403: 			
 3404: 			if (defined($token->[2]->{'name'})) { 
 3405: 			    $unikey.='_'.$token->[2]->{'name'}; 
 3406: 			}
 3407: 			$metathesekeys{$unikey}=1;
 3408: 			foreach (@{$token->[3]}) {
 3409: 			    $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
 3410: 			}
 3411: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 3412: 			my $default=$metacache{$uri.':'.$unikey.'.default'};
 3413: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 3414: 		 # only ws inside the tag, and not in default, so use default
 3415: 		 # as value
 3416: 			    $metacache{$uri.':'.$unikey}=$default;
 3417: 			} else {
 3418: 		  # either something interesting inside the tag or default
 3419:                   # uninteresting
 3420: 			    $metacache{$uri.':'.$unikey}=$internaltext;
 3421: 			}
 3422: # end of not-a-package not-a-library import
 3423: 		    }
 3424: # end of not-a-package start tag
 3425: 		}
 3426: # the next is the end of "start tag"
 3427: 	    }
 3428: 	}
 3429: # are there custom rights to evaluate
 3430: 	if ($metacache{$uri.':copyright'} eq 'custom') {
 3431: 
 3432:     #
 3433:     # Importing a rights file here
 3434:     #
 3435: 	    unless ($depthcount) {
 3436: 		my $location=$metacache{$uri.':customdistributionfile'};
 3437: 		my $dir=$filename;
 3438: 		$dir=~s|[^/]*$||;
 3439: 		$location=&filelocation($dir,$location);
 3440: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 3441: 						   $location,'_rights',
 3442: 						   $depthcount+1)))) {
 3443: 		    $metathesekeys{$_}=1;
 3444: 		}
 3445: 	    }
 3446: 	}
 3447: 	$metacache{$uri.':keys'}=join(',',keys %metathesekeys);
 3448: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
 3449: 	$metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
 3450: 	$metacache{$uri.':cachedtimestamp'}=time;
 3451: # this is the end of "was not already recently cached
 3452:     }
 3453:     return $metacache{$uri.':'.$what};
 3454: }
 3455: 
 3456: sub metadata_generate_part0 {
 3457:     my ($metadata,$metacache,$uri) = @_;
 3458:     my %allnames;
 3459:     foreach my $metakey (sort keys %$metadata) {
 3460: 	if ($metakey=~/^parameter\_(.*)/) {
 3461: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
 3462: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
 3463: 	  if (! exists($$metadata{'parameter_0_'.$name})) {
 3464: 	    $allnames{$name}=$part;
 3465: 	  }
 3466: 	}
 3467:     }
 3468:     foreach my $name (keys(%allnames)) {
 3469:       $$metadata{"parameter_0_$name"}=1;
 3470:       my $key="$uri:parameter_0_$name";
 3471:       $$metacache{"$key.part"}='0';
 3472:       $$metacache{"$key.name"}=$name;
 3473:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
 3474: 					   $allnames{$name}.'_'.$name.
 3475: 					   '.type'};
 3476:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
 3477: 			     '.display'};
 3478:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
 3479:       $olddis=~s/$expr/\[Part: 0\]/;
 3480:       $$metacache{"$key.display"}=$olddis;
 3481:     }
 3482: }
 3483: 
 3484: # ------------------------------------------------- Get the title of a resource
 3485: 
 3486: sub gettitle {
 3487:     my $urlsymb=shift;
 3488:     my $symb=&symbread($urlsymb);
 3489:     unless ($symb) {
 3490: 	unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
 3491:         return &metadata($urlsymb,'title'); 
 3492:     }
 3493:     if ($titlecache{$symb}) { return $titlecache{$symb}; }
 3494:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
 3495:     my $title='';
 3496:     my %bighash;
 3497:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3498:                             &GDBM_READER(),0640)) {
 3499:         my $mapid=$bighash{'map_pc_'.&clutter($map)};
 3500:         $title=$bighash{'title_'.$mapid.'.'.$resid};
 3501:         untie %bighash;
 3502:     }
 3503:     if ($title) {
 3504:         $titlecache{$symb}=$title;
 3505:         return $title;
 3506:     } else {
 3507: 	return &metadata($urlsymb,'title');
 3508:     }
 3509: }
 3510:     
 3511: # ------------------------------------------------- Update symbolic store links
 3512: 
 3513: sub symblist {
 3514:     my ($mapname,%newhash)=@_;
 3515:     $mapname=declutter($mapname);
 3516:     my %hash;
 3517:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 3518:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3519:                       &GDBM_WRCREAT(),0640)) {
 3520: 	    foreach (keys %newhash) {
 3521:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
 3522:             }
 3523:             if (untie(%hash)) {
 3524: 		return 'ok';
 3525:             }
 3526:         }
 3527:     }
 3528:     return 'error';
 3529: }
 3530: 
 3531: # --------------------------------------------------------------- Verify a symb
 3532: 
 3533: sub symbverify {
 3534:     my ($symb,$thisfn)=@_;
 3535:     $thisfn=&declutter($thisfn);
 3536: # direct jump to resource in page or to a sequence - will construct own symbs
 3537:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 3538: # check URL part
 3539:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
 3540:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
 3541: 
 3542:     $symb=&symbclean($symb);
 3543: 
 3544:     my %bighash;
 3545:     my $okay=0;
 3546:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3547:                             &GDBM_READER(),0640)) {
 3548:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3549:         unless ($ids) { 
 3550:            $ids=$bighash{'ids_/'.$thisfn};
 3551:         }
 3552:         if ($ids) {
 3553: # ------------------------------------------------------------------- Has ID(s)
 3554: 	    foreach (split(/\,/,$ids)) {
 3555:                my ($mapid,$resid)=split(/\./,$_);
 3556:                if (
 3557:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 3558:    eq $symb) { 
 3559:                   $okay=1; 
 3560:                }
 3561: 	   }
 3562:         }
 3563: 	untie(%bighash);
 3564:     }
 3565:     return $okay;
 3566: }
 3567: 
 3568: # --------------------------------------------------------------- Clean-up symb
 3569: 
 3570: sub symbclean {
 3571:     my $symb=shift;
 3572: 
 3573: # remove version from map
 3574:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 3575: 
 3576: # remove version from URL
 3577:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 3578: 
 3579:     return $symb;
 3580: }
 3581: 
 3582: # ------------------------------------------------------ Return symb list entry
 3583: 
 3584: sub symbread {
 3585:     my ($thisfn,$donotrecurse)=@_;
 3586: # no filename provided? try from environment
 3587:     unless ($thisfn) {
 3588:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
 3589: 	$thisfn=$ENV{'request.filename'};
 3590:     }
 3591: # is that filename actually a symb? Verify, clean, and return
 3592:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 3593: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
 3594:     }
 3595:     $thisfn=declutter($thisfn);
 3596:     my %hash;
 3597:     my %bighash;
 3598:     my $syval='';
 3599:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 3600:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3601:                       &GDBM_READER(),0640)) {
 3602: 	    $syval=$hash{$thisfn};
 3603:             untie(%hash);
 3604:         }
 3605: # ---------------------------------------------------------- There was an entry
 3606:         if ($syval) {
 3607:            unless ($syval=~/\_\d+$/) {
 3608: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 3609:                   &appenv('request.ambiguous' => $thisfn);
 3610:                   return '';
 3611:                }    
 3612:                $syval.=$1;
 3613: 	   }
 3614:         } else {
 3615: # ------------------------------------------------------- Was not in symb table
 3616:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3617:                             &GDBM_READER(),0640)) {
 3618: # ---------------------------------------------- Get ID(s) for current resource
 3619:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3620:               unless ($ids) { 
 3621:                  $ids=$bighash{'ids_/'.$thisfn};
 3622:               }
 3623:               unless ($ids) {
 3624: # alias?
 3625: 		  $ids=$bighash{'mapalias_'.$thisfn};
 3626:               }
 3627:               if ($ids) {
 3628: # ------------------------------------------------------------------- Has ID(s)
 3629:                  my @possibilities=split(/\,/,$ids);
 3630:                  if ($#possibilities==0) {
 3631: # ----------------------------------------------- There is only one possibility
 3632: 		     my ($mapid,$resid)=split(/\./,$ids);
 3633:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 3634:                  } elsif (!$donotrecurse) {
 3635: # ------------------------------------------ There is more than one possibility
 3636:                      my $realpossible=0;
 3637:                      foreach (@possibilities) {
 3638: 			 my $file=$bighash{'src_'.$_};
 3639:                          if (&allowed('bre',$file)) {
 3640:          		    my ($mapid,$resid)=split(/\./,$_);
 3641:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 3642: 				$realpossible++;
 3643:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 3644:                                        '___'.$resid;
 3645:                             }
 3646: 			 }
 3647:                      }
 3648: 		     if ($realpossible!=1) { $syval=''; }
 3649:                  } else {
 3650:                      $syval='';
 3651:                  }
 3652: 	      }
 3653:               untie(%bighash)
 3654:            } 
 3655:         }
 3656:         if ($syval) {
 3657:            return &symbclean($syval.'___'.$thisfn); 
 3658:         }
 3659:     }
 3660:     &appenv('request.ambiguous' => $thisfn);
 3661:     return '';
 3662: }
 3663: 
 3664: # ---------------------------------------------------------- Return random seed
 3665: 
 3666: sub numval {
 3667:     my $txt=shift;
 3668:     $txt=~tr/A-J/0-9/;
 3669:     $txt=~tr/a-j/0-9/;
 3670:     $txt=~tr/K-T/0-9/;
 3671:     $txt=~tr/k-t/0-9/;
 3672:     $txt=~tr/U-Z/0-5/;
 3673:     $txt=~tr/u-z/0-5/;
 3674:     $txt=~s/\D//g;
 3675:     return int($txt);
 3676: }    
 3677: 
 3678: sub rndseed {
 3679:     my ($symb,$courseid,$domain,$username)=@_;
 3680:     if (!$symb) {
 3681:       unless ($symb=&symbread()) { return time; }
 3682:     }
 3683:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
 3684:     if (!$domain) {$domain=$ENV{'user.domain'};}
 3685:     if (!$username) {$username=$ENV{'user.name'};}
 3686:     {
 3687:       use integer;
 3688:       my $symbchck=unpack("%32C*",$symb) << 27;
 3689:       my $symbseed=numval($symb) << 22;
 3690:       my $namechck=unpack("%32C*",$username) << 17;
 3691:       my $nameseed=numval($username) << 12;
 3692:       my $domainseed=unpack("%32C*",$domain) << 7;
 3693:       my $courseseed=unpack("%32C*",$courseid);
 3694:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 3695:       #uncommenting these lines can break things!
 3696:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 3697:       #&Apache::lonxml::debug("rndseed :$num:$symb");
 3698:       return $num;
 3699:     }
 3700: }
 3701: 
 3702: sub ireceipt {
 3703:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
 3704:     my $cuname=unpack("%32C*",$funame);
 3705:     my $cudom=unpack("%32C*",$fudom);
 3706:     my $cucourseid=unpack("%32C*",$fucourseid);
 3707:     my $cusymb=unpack("%32C*",$fusymb);
 3708:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
 3709:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
 3710:            ($cunique%$cuname+
 3711:             $cunique%$cudom+
 3712:             $cusymb%$cuname+
 3713:             $cusymb%$cudom+
 3714:             $cucourseid%$cuname+
 3715:             $cucourseid%$cudom);
 3716: }
 3717: 
 3718: sub receipt {
 3719:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 3720:   return &ireceipt($name,$domain,$courseid,$symb);
 3721: }
 3722: 
 3723: # ------------------------------------------------------------ Serves up a file
 3724: # returns either the contents of the file or a -1
 3725: sub getfile {
 3726:  my $file=shift;
 3727:  if ($file=~/^\/*uploaded\//) { # user file
 3728:     my $ua=new LWP::UserAgent;
 3729:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
 3730:     my $response=$ua->request($request);
 3731:     if ($response->is_success()) {
 3732:        return $response->content;
 3733:     } else { 
 3734:        return -1; 
 3735:     }
 3736:  } else { # normal file from res space
 3737:   &repcopy($file);
 3738:   if (! -e $file ) { return -1; };
 3739:   my $fh=Apache::File->new($file);
 3740:   my $a='';
 3741:   while (<$fh>) { $a .=$_; }
 3742:   return $a;
 3743:  }
 3744: }
 3745: 
 3746: sub filelocation {
 3747:   my ($dir,$file) = @_;
 3748:   my $location;
 3749:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 3750:   if ($file=~m:^/~:) { # is a contruction space reference
 3751:     $location = $file;
 3752:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 3753:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
 3754:     $location=$file;
 3755:   } else {
 3756:     $file=~s/^$perlvar{'lonDocRoot'}//;
 3757:     $file=~s:^/*res::;
 3758:     if ( !( $file =~ m:^/:) ) {
 3759:       $location = $dir. '/'.$file;
 3760:     } else {
 3761:       $location = '/home/httpd/html/res'.$file;
 3762:     }
 3763:   }
 3764:   $location=~s://+:/:g; # remove duplicate /
 3765:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 3766:   return $location;
 3767: }
 3768: 
 3769: sub hreflocation {
 3770:     my ($dir,$file)=@_;
 3771:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
 3772:        my $finalpath=filelocation($dir,$file);
 3773:        $finalpath=~s/^\/home\/httpd\/html//;
 3774:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
 3775:        return $finalpath;
 3776:     } else {
 3777:        return $file;
 3778:     }
 3779: }
 3780: 
 3781: # ------------------------------------------------------------- Declutters URLs
 3782: 
 3783: sub declutter {
 3784:     my $thisfn=shift;
 3785:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 3786:     $thisfn=~s/^\///;
 3787:     $thisfn=~s/^res\///;
 3788:     $thisfn=~s/\?.+$//;
 3789:     return $thisfn;
 3790: }
 3791: 
 3792: # ------------------------------------------------------------- Clutter up URLs
 3793: 
 3794: sub clutter {
 3795:     my $thisfn='/'.&declutter(shift);
 3796:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
 3797:        $thisfn='/res'.$thisfn; 
 3798:     }
 3799:     return $thisfn;
 3800: }
 3801: 
 3802: # -------------------------------------------------------- Escape Special Chars
 3803: 
 3804: sub escape {
 3805:     my $str=shift;
 3806:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 3807:     return $str;
 3808: }
 3809: 
 3810: # ----------------------------------------------------- Un-Escape Special Chars
 3811: 
 3812: sub unescape {
 3813:     my $str=shift;
 3814:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 3815:     return $str;
 3816: }
 3817: 
 3818: # ================================================================ Main Program
 3819: 
 3820: sub goodbye {
 3821:    &logthis("Starting Shut down");
 3822:    &flushcourselogs();
 3823:    &logthis("Shutting down");
 3824: }
 3825: 
 3826: BEGIN {
 3827: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 3828:     unless ($readit) {
 3829: {
 3830:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
 3831: 
 3832:     while (my $configline=<$config>) {
 3833:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 3834: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 3835:            chomp($varvalue);
 3836:            $perlvar{$varname}=$varvalue;
 3837:         }
 3838:     }
 3839: }
 3840: {
 3841:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
 3842: 
 3843:     while (my $configline=<$config>) {
 3844:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 3845: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 3846:            chomp($varvalue);
 3847:            $perlvar{$varname}=$varvalue;
 3848:         }
 3849:     }
 3850: }
 3851: 
 3852: # ------------------------------------------------------------ Read domain file
 3853: {
 3854:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
 3855:                             '/domain.tab');
 3856:     %domaindescription = ();
 3857:     %domain_auth_def = ();
 3858:     %domain_auth_arg_def = ();
 3859:     if ($fh) {
 3860:        while (<$fh>) {
 3861:            next if /^\#/;
 3862:            chomp;
 3863:            my ($domain, $domain_description, $def_auth, $def_auth_arg)
 3864:                = split(/:/,$_,4);
 3865:            $domain_auth_def{$domain}=$def_auth;
 3866:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 3867:            $domaindescription{$domain}=$domain_description;
 3868: #          &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 3869: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 3870:        }
 3871:     }
 3872: }
 3873: 
 3874: 
 3875: # ------------------------------------------------------------- Read hosts file
 3876: {
 3877:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
 3878: 
 3879:     while (my $configline=<$config>) {
 3880:        next if ($configline =~ /^(\#|\s*$)/);
 3881:        chomp($configline);
 3882:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
 3883:        if ($id && $domain && $role && $name && $ip) {
 3884: 	 $hostname{$id}=$name;
 3885: 	 $hostdom{$id}=$domain;
 3886: 	 $hostip{$id}=$ip;
 3887: 	 $iphost{$ip}=$id;
 3888: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 3889:        } else {
 3890: 	 if ($configline) {
 3891: 	   &logthis("Skipping hosts.tab line -$configline-");
 3892: 	 }
 3893:        }
 3894:     }
 3895: }
 3896: 
 3897: # ------------------------------------------------------ Read spare server file
 3898: {
 3899:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
 3900: 
 3901:     while (my $configline=<$config>) {
 3902:        chomp($configline);
 3903:        if ($configline) {
 3904:           $spareid{$configline}=1;
 3905:        }
 3906:     }
 3907: }
 3908: # ------------------------------------------------------------ Read permissions
 3909: {
 3910:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
 3911: 
 3912:     while (my $configline=<$config>) {
 3913:        chomp($configline);
 3914:       if ($configline) {
 3915:        my ($role,$perm)=split(/ /,$configline);
 3916:        if ($perm ne '') { $pr{$role}=$perm; }
 3917:       }
 3918:     }
 3919: }
 3920: 
 3921: # -------------------------------------------- Read plain texts for permissions
 3922: {
 3923:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
 3924: 
 3925:     while (my $configline=<$config>) {
 3926:        chomp($configline);
 3927:       if ($configline) {
 3928:        my ($short,$plain)=split(/:/,$configline);
 3929:        if ($plain ne '') { $prp{$short}=$plain; }
 3930:       }
 3931:     }
 3932: }
 3933: 
 3934: # ---------------------------------------------------------- Read package table
 3935: {
 3936:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
 3937: 
 3938:     while (my $configline=<$config>) {
 3939:        chomp($configline);
 3940:        my ($short,$plain)=split(/:/,$configline);
 3941:        my ($pack,$name)=split(/\&/,$short);
 3942:        if ($plain ne '') {
 3943:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
 3944:           $packagetab{$short}=$plain; 
 3945:        }
 3946:     }
 3947: }
 3948: 
 3949: # ------------- set up temporary directory
 3950: {
 3951:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 3952: 
 3953: }
 3954: 
 3955: %metacache=();
 3956: 
 3957: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 3958: $dumpcount=0;
 3959: 
 3960: &logtouch();
 3961: &logthis('<font color=yellow>INFO: Read configuration</font>');
 3962: $readit=1;
 3963: }
 3964: }
 3965: 
 3966: 1;
 3967: __END__
 3968: 
 3969: =pod
 3970: 
 3971: =head1 NAME
 3972: 
 3973: Apache::lonnet - Subroutines to ask questions about things in the network.
 3974: 
 3975: =head1 SYNOPSIS
 3976: 
 3977: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 3978: 
 3979:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 3980: 
 3981: Common parameters:
 3982: 
 3983: =over 4
 3984: 
 3985: =item *
 3986: 
 3987: $uname : an internal username (if $cname expecting a course Id specifically)
 3988: 
 3989: =item *
 3990: 
 3991: $udom : a domain (if $cdom expecting a course's domain specifically)
 3992: 
 3993: =item *
 3994: 
 3995: $symb : a resource instance identifier
 3996: 
 3997: =item *
 3998: 
 3999: $namespace : the name of a .db file that contains the data needed or
 4000: being set.
 4001: 
 4002: =back
 4003: 
 4004: =head1 INTRODUCTION
 4005: 
 4006: This module provides subroutines which interact with the
 4007: lonc/lond (TCP) network layer of LON-CAPA. And Can be used to ask about 
 4008: - classes
 4009: - users 
 4010: - resources
 4011: 
 4012: For many of these objects you can also use this to store data about
 4013: them or modify them in various ways.
 4014: 
 4015: This is part of the LearningOnline Network with CAPA project
 4016: described at http://www.lon-capa.org.
 4017: 
 4018: =head1 RETURN MESSAGES
 4019: 
 4020: =over 4
 4021: 
 4022: =item *
 4023: 
 4024: con_lost : unable to contact remote host
 4025: 
 4026: =item *
 4027: 
 4028: con_delayed : unable to contact remote host, message will be delivered
 4029: when the connection is brought back up
 4030: 
 4031: =item *
 4032: 
 4033: con_failed : unable to contact remote host and unable to save message
 4034: for later delivery
 4035: 
 4036: =item *
 4037: 
 4038: error: : an error a occured, a description of the error follows the :
 4039: 
 4040: =item *
 4041: 
 4042: no_such_host : unable to fund a host associated with the user/domain
 4043: that was requested
 4044: 
 4045: =back
 4046: 
 4047: =head1 PUBLIC SUBROUTINES
 4048: 
 4049: =head2 Session Environment Functions
 4050: 
 4051: =over 4
 4052: 
 4053: =item *
 4054: 
 4055: appenv(%hash) : the value of %hash is written to the user envirnoment
 4056: file, and will be restored for each access this user makes during this
 4057: session, also modifies the %ENV for the current process
 4058: 
 4059: =item *
 4060: 
 4061: 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.
 4062: 
 4063: =back
 4064: 
 4065: =head2 User Information
 4066: 
 4067: =over 4
 4068: 
 4069: =item *
 4070: 
 4071: queryauthenticate($uname,$udom) : try to determine user's current
 4072: authentication scheme
 4073: 
 4074: =item *
 4075: 
 4076: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
 4077: servers (first use the current one), $upass should be the users password
 4078: 
 4079: =item *
 4080: 
 4081: homeserver($uname,$udom) : find the server which has the user's
 4082: directory and files (there must be only one), this caches the answer,
 4083: and also caches if there is a borken connection.
 4084: 
 4085: =item *
 4086: 
 4087: idget($udom,@ids) : find the usernames behind a list of IDs (IDs are a
 4088: unique resource in a domain, there must be only 1 ID per username, and
 4089: only 1 username per ID in a specific domain) (returns hash:
 4090: id=>name,id=>name)
 4091: 
 4092: =item *
 4093: 
 4094: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
 4095: name=>id,name=>id)
 4096: 
 4097: =item *
 4098: 
 4099: idput($udom,%ids) : store away a list of names and associated IDs
 4100: 
 4101: =item *
 4102: 
 4103: rolesinit($udom,$username,$authhost) : get user privileges
 4104: 
 4105: =item *
 4106: 
 4107: usection($udom,$uname,$cname) : finds the section of student in the
 4108: course $cname, return section name/number or '' for "not in course"
 4109: and '-1' for "no section"
 4110: 
 4111: =item *
 4112: 
 4113: userenvironment($udom,$uname,@what) : gets the values of the keys
 4114: passed in @what from the requested user's environment, returns a hash
 4115: 
 4116: =back
 4117: 
 4118: =head2 User Roles
 4119: 
 4120: =over 4
 4121: 
 4122: =item *
 4123: 
 4124: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 4125: actions
 4126:  F: full access
 4127:  U,I,K: authentication modes (cxx only)
 4128:  '': forbidden
 4129:  1: user needs to choose course
 4130:  2: browse allowed
 4131: 
 4132: =item *
 4133: 
 4134: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 4135: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 4136: and course level
 4137: 
 4138: =item *
 4139: 
 4140: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 4141: explanation of a user role term
 4142: 
 4143: =back
 4144: 
 4145: =head2 User Modification
 4146: 
 4147: =over 4
 4148: 
 4149: =item *
 4150: 
 4151: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 4152: user for the level given by URL.  Optional start and end dates (leave empty
 4153: string or zero for "no date")
 4154: 
 4155: =item *
 4156: 
 4157: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 4158: change a users, password, possible return values are: ok,
 4159: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 4160: refused
 4161: 
 4162: =item *
 4163: 
 4164: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 4165: 
 4166: =item *
 4167: 
 4168: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 4169: modify user
 4170: 
 4171: =item *
 4172: 
 4173: modifystudent
 4174: 
 4175: modify a students enrollment and identification information.
 4176: The course id is resolved based on the current users environment.  
 4177: This means the envoking user must be a course coordinator or otherwise
 4178: associated with a course.
 4179: 
 4180: This call is essentially a wrapper for lonnet::modifyuser and
 4181: lonnet::modify_student_enrollment
 4182: 
 4183: Inputs: 
 4184: 
 4185: =over 4
 4186: 
 4187: =item B<$udom> Students loncapa domain
 4188: 
 4189: =item B<$uname> Students loncapa login name
 4190: 
 4191: =item B<$uid> Students id/student number
 4192: 
 4193: =item B<$umode> Students authentication mode
 4194: 
 4195: =item B<$upass> Students password
 4196: 
 4197: =item B<$first> Students first name
 4198: 
 4199: =item B<$middle> Students middle name
 4200: 
 4201: =item B<$last> Students last name
 4202: 
 4203: =item B<$gene> Students generation
 4204: 
 4205: =item B<$usec> Students section in course
 4206: 
 4207: =item B<$end> Unix time of the roles expiration
 4208: 
 4209: =item B<$start> Unix time of the roles start date
 4210: 
 4211: =item B<$forceid> If defined, allow $uid to be changed
 4212: 
 4213: =item B<$desiredhome> server to use as home server for student
 4214: 
 4215: =back
 4216: 
 4217: =item *
 4218: 
 4219: modify_student_enrollment
 4220: 
 4221: Change a students enrollment status in a class.  The environment variable
 4222: 'role.request.course' must be defined for this function to proceed.
 4223: 
 4224: Inputs:
 4225: 
 4226: =over 4
 4227: 
 4228: =item $udom, students domain
 4229: 
 4230: =item $uname, students name
 4231: 
 4232: =item $uid, students user id
 4233: 
 4234: =item $first, students first name
 4235: 
 4236: =item $middle
 4237: 
 4238: =item $last
 4239: 
 4240: =item $gene
 4241: 
 4242: =item $usec
 4243: 
 4244: =item $end
 4245: 
 4246: =item $start
 4247: 
 4248: =back
 4249: 
 4250: 
 4251: =item *
 4252: 
 4253: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 4254: custom role; give a custom role to a user for the level given by URL.  Specify
 4255: name and domain of role author, and role name
 4256: 
 4257: =item *
 4258: 
 4259: revokerole($udom,$uname,$url,$role) : revoke a role for url
 4260: 
 4261: =item *
 4262: 
 4263: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 4264: 
 4265: =back
 4266: 
 4267: =head2 Course Infomation
 4268: 
 4269: =over 4
 4270: 
 4271: =item *
 4272: 
 4273: coursedescription($courseid) : course description
 4274: 
 4275: =item *
 4276: 
 4277: courseresdata($coursenum,$coursedomain,@which) : request for current
 4278: parameter setting for a specific course, @what should be a list of
 4279: parameters to ask about. This routine caches answers for 5 minutes.
 4280: 
 4281: =back
 4282: 
 4283: =head2 Course Modification
 4284: 
 4285: =over 4
 4286: 
 4287: =item *
 4288: 
 4289: writecoursepref($courseid,%prefs) : write preferences (environment
 4290: database) for a course
 4291: 
 4292: =item *
 4293: 
 4294: createcourse($udom,$description,$url) : make/modify course
 4295: 
 4296: =back
 4297: 
 4298: =head2 Resource Subroutines
 4299: 
 4300: =over 4
 4301: 
 4302: =item *
 4303: 
 4304: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 4305: 
 4306: =item *
 4307: 
 4308: repcopy($filename) : subscribes to the requested file, and attempts to
 4309: replicate from the owning library server, Might return
 4310: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
 4311: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
 4312: resource. Expects the local filesystem pathname
 4313: (/home/httpd/html/res/....)
 4314: 
 4315: =back
 4316: 
 4317: =head2 Resource Information
 4318: 
 4319: =over 4
 4320: 
 4321: =item *
 4322: 
 4323: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 4324: a vairety of different possible values, $varname should be a request
 4325: string, and the other parameters can be used to specify who and what
 4326: one is asking about.
 4327: 
 4328: Possible values for $varname are environment.lastname (or other item
 4329: from the envirnment hash), user.name (or someother aspect about the
 4330: user), resource.0.maxtries (or some other part and parameter of a
 4331: resource)
 4332: 
 4333: =item *
 4334: 
 4335: directcondval($number) : get current value of a condition; reads from a state
 4336: string
 4337: 
 4338: =item *
 4339: 
 4340: condval($condidx) : value of condition index based on state
 4341: 
 4342: =item *
 4343: 
 4344: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 4345: resource's metadata, $what should be either a specific key, or either
 4346: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 4347: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 4348: 
 4349: this function automatically caches all requests
 4350: 
 4351: =item *
 4352: 
 4353: metadata_query($query,$custom,$customshow) : make a metadata query against the
 4354: network of library servers; returns file handle of where SQL and regex results
 4355: will be stored for query
 4356: 
 4357: =item *
 4358: 
 4359: symbread($filename) : return symbolic list entry (filename argument optional);
 4360: returns the data handle
 4361: 
 4362: =item *
 4363: 
 4364: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 4365: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
 4366: failure, user must be in a course, as it assumes the existance of the
 4367: course initi hash, and uses $ENV('request.course.id'}
 4368: 
 4369: 
 4370: =item *
 4371: 
 4372: symbclean($symb) : removes versions numbers from a symb, returns the
 4373: cleaned symb
 4374: 
 4375: =item *
 4376: 
 4377: is_on_map($uri) : checks if the $uri is somewhere on the current
 4378: course map, user must be in a course for it to work.
 4379: 
 4380: =item *
 4381: 
 4382: numval($salt) : return random seed value (addend for rndseed)
 4383: 
 4384: =item *
 4385: 
 4386: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 4387: a random seed, all arguments are optional, if they aren't sent it uses the
 4388: environment to derive them. Note: if symb isn't sent and it can't get one
 4389: from &symbread it will use the current time as its return value
 4390: 
 4391: =item *
 4392: 
 4393: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 4394: unfakeable, receipt
 4395: 
 4396: =item *
 4397: 
 4398: receipt() : API to ireceipt working off of ENV values; given out to users
 4399: 
 4400: =item *
 4401: 
 4402: countacc($url) : count the number of accesses to a given URL
 4403: 
 4404: =item *
 4405: 
 4406: 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
 4407: 
 4408: =item *
 4409: 
 4410: 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)
 4411: 
 4412: =item *
 4413: 
 4414: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 4415: 
 4416: =item *
 4417: 
 4418: devalidate($symb) : devalidate temporary spreadsheet calculations,
 4419: forcing spreadsheet to reevaluate the resource scores next time.
 4420: 
 4421: =back
 4422: 
 4423: =head2 Storing/Retreiving Data
 4424: 
 4425: =over 4
 4426: 
 4427: =item *
 4428: 
 4429: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 4430: for this url; hashref needs to be given and should be a \%hashname; the
 4431: remaining args aren't required and if they aren't passed or are '' they will
 4432: be derived from the ENV
 4433: 
 4434: =item *
 4435: 
 4436: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 4437: uses critical subroutine
 4438: 
 4439: =item *
 4440: 
 4441: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 4442: all args are optional
 4443: 
 4444: =item *
 4445: 
 4446: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 4447: works very similar to store/cstore, but all data is stored in a
 4448: temporary location and can be reset using tmpreset, $storehash should
 4449: be a hash reference, returns nothing on success
 4450: 
 4451: =item *
 4452: 
 4453: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 4454: similar to restore, but all data is stored in a temporary location and
 4455: can be reset using tmpreset. Returns a hash of values on success,
 4456: error string otherwise.
 4457: 
 4458: =item *
 4459: 
 4460: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 4461: deltes all keys for $symb form the temporary storage hash.
 4462: 
 4463: =item *
 4464: 
 4465: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 4466: reference filled in from namesp ($udom and $uname are optional)
 4467: 
 4468: =item *
 4469: 
 4470: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 4471: namesp ($udom and $uname are optional)
 4472: 
 4473: =item *
 4474: 
 4475: dump($namespace,$udom,$uname,$regexp) : 
 4476: dumps the complete (or key matching regexp) namespace into a hash
 4477: ($udom, $uname and $regexp are optional)
 4478: 
 4479: =item *
 4480: 
 4481: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 4482: ($udom and $uname are optional)
 4483: 
 4484: =item *
 4485: 
 4486: cput($namespace,$storehash,$udom,$uname) : critical put
 4487: ($udom and $uname are optional)
 4488: 
 4489: =item *
 4490: 
 4491: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 4492: reference filled in from namesp (encrypts the return communication)
 4493: ($udom and $uname are optional)
 4494: 
 4495: =item *
 4496: 
 4497: log($udom,$name,$home,$message) : write to permanent log for user; use
 4498: critical subroutine
 4499: 
 4500: =back
 4501: 
 4502: =head2 Network Status Functions
 4503: 
 4504: =over 4
 4505: 
 4506: =item *
 4507: 
 4508: dirlist($uri) : return directory list based on URI
 4509: 
 4510: =item *
 4511: 
 4512: spareserver() : find server with least workload from spare.tab
 4513: 
 4514: =back
 4515: 
 4516: =head2 Apache Request
 4517: 
 4518: =over 4
 4519: 
 4520: =item *
 4521: 
 4522: ssi($url,%hash) : server side include, does a complete request cycle on url to
 4523: localhost, posts hash
 4524: 
 4525: =back
 4526: 
 4527: =head2 Data to String to Data
 4528: 
 4529: =over 4
 4530: 
 4531: =item *
 4532: 
 4533: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 4534: and '&' separators, supports elements that are arrayrefs and hashrefs
 4535: 
 4536: =item *
 4537: 
 4538: hashref2str($hashref) : convert a hashref into a string complete with
 4539: escaping and '=' and '&' separators, supports elements that are
 4540: arrayrefs and hashrefs
 4541: 
 4542: =item *
 4543: 
 4544: arrayref2str($arrayref) : convert an arrayref into a string complete
 4545: with escaping and '&' separators, supports elements that are arrayrefs
 4546: and hashrefs
 4547: 
 4548: =item *
 4549: 
 4550: str2hash($string) : convert string to hash using unescaping and
 4551: splitting on '=' and '&', supports elements that are arrayrefs and
 4552: hashrefs
 4553: 
 4554: =item *
 4555: 
 4556: str2array($string) : convert string to hash using unescaping and
 4557: splitting on '&', supports elements that are arrayrefs and hashrefs
 4558: 
 4559: =back
 4560: 
 4561: =head2 Logging Routines
 4562: 
 4563: =over 4
 4564: 
 4565: These routines allow one to make log messages in the lonnet.log and
 4566: lonnet.perm logfiles.
 4567: 
 4568: =item *
 4569: 
 4570: logtouch() : make sure the logfile, lonnet.log, exists
 4571: 
 4572: =item *
 4573: 
 4574: logthis() : append message to the normal lonnet.log file, it gets
 4575: preiodically rolled over and deleted.
 4576: 
 4577: =item *
 4578: 
 4579: logperm() : append a permanent message to lonnet.perm.log, this log
 4580: file never gets deleted by any automated portion of the system, only
 4581: messages of critical importance should go in here.
 4582: 
 4583: =back
 4584: 
 4585: =head2 General File Helper Routines
 4586: 
 4587: =over 4
 4588: 
 4589: =item *
 4590: 
 4591: getfile($file) : returns the entire contents of a file or -1; it
 4592: properly subscribes to and replicates the file if neccessary.
 4593: 
 4594: =item *
 4595: 
 4596: filelocation($dir,$file) : returns file system location of a file
 4597: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 4598: directory that relative $file lookups are to looked in ($dir of /a/dir
 4599: and a file of ../bob will become /a/bob)
 4600: 
 4601: =item *
 4602: 
 4603: hreflocation($dir,$file) : returns file system location or a URL; same as
 4604: filelocation except for hrefs
 4605: 
 4606: =item *
 4607: 
 4608: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 4609: 
 4610: =back
 4611: 
 4612: =head2 HTTP Helper Routines
 4613: 
 4614: =over 4
 4615: 
 4616: =item *
 4617: 
 4618: escape() : unpack non-word characters into CGI-compatible hex codes
 4619: 
 4620: =item *
 4621: 
 4622: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 4623: 
 4624: =back
 4625: 
 4626: =head1 PRIVATE SUBROUTINES
 4627: 
 4628: =head2 Underlying communication routines (Shouldn't call)
 4629: 
 4630: =over 4
 4631: 
 4632: =item *
 4633: 
 4634: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 4635: 
 4636: =item *
 4637: 
 4638: reply() : uses subreply to send a message to remote machine, logs all failures
 4639: 
 4640: =item *
 4641: 
 4642: critical() : passes a critical message to another server; if cannot
 4643: get through then place message in connection buffer directory and
 4644: returns con_delayed, if incapable of saving message, returns
 4645: con_failed
 4646: 
 4647: =item *
 4648: 
 4649: reconlonc() : tries to reconnect lonc client processes.
 4650: 
 4651: =back
 4652: 
 4653: =head2 Resource Access Logging
 4654: 
 4655: =over 4
 4656: 
 4657: =item *
 4658: 
 4659: flushcourselogs() : flush (save) buffer logs and access logs
 4660: 
 4661: =item *
 4662: 
 4663: courselog($what) : save message for course in hash
 4664: 
 4665: =item *
 4666: 
 4667: courseacclog($what) : save message for course using &courselog().  Perform
 4668: special processing for specific resource types (problems, exams, quizzes, etc).
 4669: 
 4670: =item *
 4671: 
 4672: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 4673: as a PerlChildExitHandler
 4674: 
 4675: =back
 4676: 
 4677: =head2 Other
 4678: 
 4679: =over 4
 4680: 
 4681: =item *
 4682: 
 4683: symblist($mapname,%newhash) : update symbolic storage links
 4684: 
 4685: =back
 4686: 
 4687: =cut

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