Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.245

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

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