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

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

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