File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.344: download - view: text, annotated - select for diffs
Sat Mar 22 02:13:08 2003 UTC (21 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Steps toward bug #1327

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

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