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

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

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