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

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

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