File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.269: download - view: text, annotated - select for diffs
Sat Aug 17 18:58:28 2002 UTC (21 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
&getfile can get userfiles

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

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