File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.345: download - view: text, annotated - select for diffs
Sat Mar 22 21:23:35 2003 UTC (21 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Further work on keyed access to courses

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

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