File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.299: download - view: text, annotated - select for diffs
Tue Oct 22 21:49:10 2002 UTC (21 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Fix to devalidate so it goes into the proper file to devalidate a students
data in the course level spreadsheet.
<lecture>
Interestingly enough, this misspelled filename was wrong from the first day
it was in the code (march 2001) and remained so until today.  Let this be a
reminder to all of us to check our new features to make sure they work.
</lecture>

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

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