File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.323: download - view: text, annotated - select for diffs
Mon Feb 3 18:03:53 2003 UTC (21 years, 5 months ago) by harris41
Branches: MAIN
CVS tags: HEAD
best wishes to all.

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

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