File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.324: download - view: text, annotated - select for diffs
Mon Feb 10 20:03:13 2003 UTC (21 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #1019 fixed.
Additional documentation.

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

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