File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.253: download - view: text, annotated - select for diffs
Wed Jul 17 19:18:47 2002 UTC (22 years ago) by stredwic
Branches: MAIN
CVS tags: HEAD
Added the ability for dirlist to take alternate roots for the directory.
Three parameters were added, $userdomain, $username, and $alternateDirectoryRoot.
The domain and name are necessary because of a call to homeserver.  Previously,
the uri(parameter) was parsed to get that info.  It defaults to that, but the
other parameters will override it if they are defined.  This was necessary, or
different parsings of the uri would have been needed based on the type of uri passed
in.

If alternateDirectoryRoot is not defined, then the function defaults to $perlvar{'lonDocRoot'}
for the directory root.  Also, if username and userdomain are not supplied for
alternate directory roots, it gives up.  The default search of all students and/or domains
when missing that data for the default directory root still exists.

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

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