File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.318: download - view: text, annotated - select for diffs
Mon Jan 13 21:52:11 2003 UTC (21 years, 6 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added new lond command: dumpcurrent.
Added lonnet::dumpcurrent
Modified spreadsheet.pm to use dumpcurrent to retrieve user data.
Some logging information is active, some is not.  More testing required.

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

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