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

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

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