File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.367: download - view: text, annotated - select for diffs
Fri May 2 15:26:36 2003 UTC (21 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Key annotation feature works now.

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

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