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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.200   ! www         4: # $Id: lonnet.pm,v 1.199 2002/02/04 15:31:22 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.188     www        80: qw(%perlvar %hostname %homecache %hostip %spareid %hostdom 
1.192     www        81:    %libserv %pr %prp %metacache %packagetab 
1.188     www        82:    %courselogs %accesshash $processmarker $dumpcount 
1.200   ! www        83:    %coursedombuf %coursehombuf %courseresdatacache);
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.71      www        87: use HTML::TokeParser;
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)=@_;
                    140:     my $answer=subreply($cmd,$server);
                    141:     if ($answer eq 'con_lost') { $answer=subreply($cmd,$server); }
1.65      www       142:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12      www       143:        &logthis("<font color=blue>WARNING:".
                    144:                 " $cmd to $server returned $answer</font>");
                    145:     }
1.1       albertel  146:     return $answer;
                    147: }
                    148: 
                    149: # ----------------------------------------------------------- Send USR1 to lonc
                    150: 
                    151: sub reconlonc {
                    152:     my $peerfile=shift;
                    153:     &logthis("Trying to reconnect for $peerfile");
                    154:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                    155:     if (my $fh=Apache::File->new("$loncfile")) {
                    156: 	my $loncpid=<$fh>;
                    157:         chomp($loncpid);
                    158:         if (kill 0 => $loncpid) {
                    159: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    160:             kill USR1 => $loncpid;
                    161:             sleep 1;
                    162:             if (-e "$peerfile") { return; }
                    163:             &logthis("$peerfile still not there, give it another try");
                    164:             sleep 5;
                    165:             if (-e "$peerfile") { return; }
1.12      www       166:             &logthis(
                    167:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  168:         } else {
1.12      www       169: 	    &logthis(
                    170:                "<font color=blue>WARNING:".
                    171:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  172:         }
                    173:     } else {
1.12      www       174:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1       albertel  175:     }
                    176: }
                    177: 
                    178: # ------------------------------------------------------ Critical communication
1.12      www       179: 
1.1       albertel  180: sub critical {
                    181:     my ($cmd,$server)=@_;
1.89      www       182:     unless ($hostname{$server}) {
                    183:         &logthis("<font color=blue>WARNING:".
                    184:                " Critical message to unknown server ($server)</font>");
                    185:         return 'no_such_host';
                    186:     }
1.1       albertel  187:     my $answer=reply($cmd,$server);
                    188:     if ($answer eq 'con_lost') {
                    189:         my $pingreply=reply('ping',$server);
                    190: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
                    191:         my $pongreply=reply('pong',$server);
                    192:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
                    193:         $answer=reply($cmd,$server);
                    194:         if ($answer eq 'con_lost') {
                    195:             my $now=time;
                    196:             my $middlename=$cmd;
1.5       www       197:             $middlename=substr($middlename,0,16);
1.1       albertel  198:             $middlename=~s/\W//g;
                    199:             my $dfilename=
                    200:              "$perlvar{'lonSockDir'}/delayed/$now.$middlename.$server";
                    201:             {
                    202:              my $dfh;
                    203:              if ($dfh=Apache::File->new(">$dfilename")) {
1.7       www       204:                 print $dfh "$cmd\n";
1.1       albertel  205: 	     }
                    206:             }
                    207:             sleep 2;
                    208:             my $wcmd='';
                    209:             {
                    210: 	     my $dfh;
                    211:              if ($dfh=Apache::File->new("$dfilename")) {
                    212:                 $wcmd=<$dfh>;
                    213: 	     }
                    214:             }
                    215:             chomp($wcmd);
1.7       www       216:             if ($wcmd eq $cmd) {
1.12      www       217: 		&logthis("<font color=blue>WARNING: ".
                    218:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  219:                 &logperm("D:$server:$cmd");
                    220: 	        return 'con_delayed';
                    221:             } else {
1.12      www       222:                 &logthis("<font color=red>CRITICAL:"
                    223:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  224:                 &logperm("F:$server:$cmd");
                    225:                 return 'con_failed';
                    226:             }
                    227:         }
                    228:     }
                    229:     return $answer;
                    230: }
                    231: 
1.5       www       232: # ---------------------------------------------------------- Append Environment
                    233: 
                    234: sub appenv {
1.6       www       235:     my %newenv=@_;
1.191     harris41  236:     foreach (keys %newenv) {
1.35      www       237: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
                    238:             &logthis("<font color=blue>WARNING: ".
1.151     www       239:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    240:                 .'</font>');
1.35      www       241: 	    delete($newenv{$_});
                    242:         } else {
                    243:             $ENV{$_}=$newenv{$_};
                    244:         }
1.191     harris41  245:     }
1.95      www       246: 
                    247:     my $lockfh;
                    248:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       249:        return 'error: '.$!;
1.95      www       250:     }
                    251:     unless (flock($lockfh,LOCK_EX)) {
                    252:          &logthis("<font color=blue>WARNING: ".
                    253:                   'Could not obtain exclusive lock in appenv: '.$!);
                    254:          $lockfh->close();
                    255:          return 'error: '.$!;
                    256:     }
                    257: 
1.6       www       258:     my @oldenv;
                    259:     {
                    260:      my $fh;
                    261:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       262: 	return 'error: '.$!;
1.6       www       263:      }
                    264:      @oldenv=<$fh>;
1.89      www       265:      $fh->close();
1.6       www       266:     }
                    267:     for (my $i=0; $i<=$#oldenv; $i++) {
                    268:         chomp($oldenv[$i]);
1.9       www       269:         if ($oldenv[$i] ne '') {
                    270:            my ($name,$value)=split(/=/,$oldenv[$i]);
1.24      www       271:            unless (defined($newenv{$name})) {
                    272: 	      $newenv{$name}=$value;
                    273: 	   }
1.9       www       274:         }
1.6       www       275:     }
                    276:     {
                    277:      my $fh;
                    278:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    279: 	return 'error';
                    280:      }
                    281:      my $newname;
1.93      www       282:      foreach $newname (keys %newenv) {
1.6       www       283: 	 print $fh "$newname=$newenv{$newname}\n";
                    284:      }
1.86      albertel  285:      $fh->close();
1.56      www       286:     }
1.95      www       287: 
                    288:     $lockfh->close();
1.56      www       289:     return 'ok';
                    290: }
                    291: # ----------------------------------------------------- Delete from Environment
                    292: 
                    293: sub delenv {
                    294:     my $delthis=shift;
                    295:     my %newenv=();
                    296:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
                    297:         &logthis("<font color=blue>WARNING: ".
                    298:                 "Attempt to delete from environment ".$delthis);
                    299:         return 'error';
                    300:     }
                    301:     my @oldenv;
                    302:     {
                    303:      my $fh;
                    304:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
                    305: 	return 'error';
                    306:      }
1.89      www       307:      unless (flock($fh,LOCK_SH)) {
                    308:          &logthis("<font color=blue>WARNING: ".
                    309:                   'Could not obtain shared lock in delenv: '.$!);
                    310:          $fh->close();
                    311:          return 'error: '.$!;
                    312:      }
1.56      www       313:      @oldenv=<$fh>;
1.89      www       314:      $fh->close();
1.56      www       315:     }
                    316:     {
                    317:      my $fh;
                    318:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    319: 	return 'error';
                    320:      }
1.89      www       321:      unless (flock($fh,LOCK_EX)) {
                    322:          &logthis("<font color=blue>WARNING: ".
                    323:                   'Could not obtain exclusive lock in delenv: '.$!);
                    324:          $fh->close();
                    325:          return 'error: '.$!;
                    326:      }
1.191     harris41  327:      foreach (@oldenv) {
1.56      www       328: 	 unless ($_=~/^$delthis/) { print $fh $_; }
1.191     harris41  329:      }
1.87      www       330:      $fh->close();
1.5       www       331:     }
                    332:     return 'ok';
                    333: }
1.1       albertel  334: 
                    335: # ------------------------------ Find server with least workload from spare.tab
1.11      www       336: 
1.1       albertel  337: sub spareserver {
                    338:     my $tryserver;
                    339:     my $spareserver='';
                    340:     my $lowestserver=100;
                    341:     foreach $tryserver (keys %spareid) {
                    342:        my $answer=reply('load',$tryserver);
                    343:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
                    344: 	   $spareserver="http://$hostname{$tryserver}";
                    345:            $lowestserver=$answer;
                    346:        }
                    347:     }    
                    348:     return $spareserver;
                    349: }
                    350: 
1.169     harris41  351: # ----------------------- Try to determine user's current authentication scheme
                    352: 
                    353: sub queryauthenticate {
                    354:     my ($uname,$udom)=@_;
                    355:     if (($perlvar{'lonRole'} eq 'library') && 
                    356:         ($udom eq $perlvar{'lonDefDomain'})) {
                    357: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
                    358: 			 $perlvar{'lonHostID'});
                    359: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    360: 	    if (length($answer)) {
                    361: 		return $answer;
                    362: 	    }
                    363: 	    else {
                    364: 	&logthis("User $uname at $udom lacks an authentication mechanism");
                    365: 		return 'no_host';
                    366: 	    }
                    367: 	}
                    368:     }
                    369: 
                    370:     my $tryserver;
                    371:     foreach $tryserver (keys %libserv) {
                    372: 	if ($hostdom{$tryserver} eq $udom) {
                    373:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
                    374: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    375: 	       if (length($answer)) {
                    376: 		   return $answer;
                    377: 	       }
                    378: 	       else {
                    379: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
                    380: 		   return 'no_host';
                    381: 	       }
                    382: 	   }
                    383:        }
                    384:     }
                    385:     &logthis("User $uname at $udom lacks an authentication mechanism");    
                    386:     return 'no_host';
                    387: }
                    388: 
1.1       albertel  389: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       390: 
1.1       albertel  391: sub authenticate {
                    392:     my ($uname,$upass,$udom)=@_;
1.12      www       393:     $upass=escape($upass);
1.199     www       394:     $uname=~s/\W//g;
1.1       albertel  395:     if (($perlvar{'lonRole'} eq 'library') && 
                    396:         ($udom eq $perlvar{'lonDefDomain'})) {
1.3       www       397:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
1.2       www       398:         if ($answer =~ /authorized/) {
1.9       www       399:               if ($answer eq 'authorized') {
                    400:                  &logthis("User $uname at $udom authorized by local server"); 
                    401:                  return $perlvar{'lonHostID'}; 
                    402:               }
                    403:               if ($answer eq 'non_authorized') {
                    404:                  &logthis("User $uname at $udom rejected by local server"); 
                    405:                  return 'no_host'; 
                    406:               }
1.2       www       407: 	}
1.1       albertel  408:     }
                    409: 
                    410:     my $tryserver;
                    411:     foreach $tryserver (keys %libserv) {
                    412: 	if ($hostdom{$tryserver} eq $udom) {
1.10      www       413:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
1.1       albertel  414:            if ($answer =~ /authorized/) {
1.9       www       415:               if ($answer eq 'authorized') {
                    416:                  &logthis("User $uname at $udom authorized by $tryserver"); 
                    417:                  return $tryserver; 
                    418:               }
                    419:               if ($answer eq 'non_authorized') {
                    420:                  &logthis("User $uname at $udom rejected by $tryserver");
                    421:                  return 'no_host';
                    422:               } 
1.1       albertel  423: 	   }
                    424:        }
1.9       www       425:     }
                    426:     &logthis("User $uname at $udom could not be authenticated");    
1.1       albertel  427:     return 'no_host';
                    428: }
                    429: 
                    430: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       431: 
1.1       albertel  432: sub homeserver {
                    433:     my ($uname,$udom)=@_;
                    434: 
                    435:     my $index="$uname:$udom";
                    436:     if ($homecache{$index}) { return "$homecache{$index}"; }
                    437: 
                    438:     my $tryserver;
                    439:     foreach $tryserver (keys %libserv) {
                    440: 	if ($hostdom{$tryserver} eq $udom) {
                    441:            my $answer=reply("home:$udom:$uname",$tryserver);
                    442:            if ($answer eq 'found') { 
                    443: 	      $homecache{$index}=$tryserver;
                    444:               return $tryserver; 
                    445: 	   }
                    446:        }
                    447:     }    
                    448:     return 'no_host';
1.70      www       449: }
                    450: 
                    451: # ------------------------------------- Find the usernames behind a list of IDs
                    452: 
                    453: sub idget {
                    454:     my ($udom,@ids)=@_;
                    455:     my %returnhash=();
                    456:     
                    457:     my $tryserver;
                    458:     foreach $tryserver (keys %libserv) {
                    459:        if ($hostdom{$tryserver} eq $udom) {
                    460: 	  my $idlist=join('&',@ids);
                    461:           $idlist=~tr/A-Z/a-z/; 
                    462: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    463:           my @answer=();
1.76      www       464:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       465: 	      @answer=split(/\&/,$reply);
                    466:           }                    ;
                    467:           my $i;
                    468:           for ($i=0;$i<=$#ids;$i++) {
                    469:               if ($answer[$i]) {
                    470: 		  $returnhash{$ids[$i]}=$answer[$i];
                    471:               } 
                    472:           }
                    473:        }
                    474:     }    
                    475:     return %returnhash;
                    476: }
                    477: 
                    478: # ------------------------------------- Find the IDs behind a list of usernames
                    479: 
                    480: sub idrget {
                    481:     my ($udom,@unames)=@_;
                    482:     my %returnhash=();
1.191     harris41  483:     foreach (@unames) {
1.70      www       484:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  485:     }
1.70      www       486:     return %returnhash;
                    487: }
                    488: 
                    489: # ------------------------------- Store away a list of names and associated IDs
                    490: 
                    491: sub idput {
                    492:     my ($udom,%ids)=@_;
                    493:     my %servers=();
1.191     harris41  494:     foreach (keys %ids) {
1.70      www       495:         my $uhom=&homeserver($_,$udom);
                    496:         if ($uhom ne 'no_host') {
                    497:             my $id=&escape($ids{$_});
                    498:             $id=~tr/A-Z/a-z/;
                    499:             my $unam=&escape($_);
                    500: 	    if ($servers{$uhom}) {
                    501: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    502:             } else {
                    503:                 $servers{$uhom}=$id.'='.$unam;
                    504:             }
                    505:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
                    506:         }
1.191     harris41  507:     }
                    508:     foreach (keys %servers) {
1.70      www       509:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  510:     }
1.70      www       511: }
                    512: 
                    513: # ------------------------------------- Find the section of student in a course
                    514: 
                    515: sub usection {
                    516:     my ($udom,$unam,$courseid)=@_;
                    517:     $courseid=~s/\_/\//g;
                    518:     $courseid=~s/^(\w)/\/$1/;
1.191     harris41  519:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    520:                         &homeserver($unam,$udom)))) {
1.70      www       521:         my ($key,$value)=split(/\=/,$_);
                    522:         $key=&unescape($key);
                    523:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
                    524:             my $section=$1;
                    525:             if ($key eq $courseid.'_st') { $section=''; }
                    526: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    527:             my $now=time;
                    528:             my $notactive=0;
                    529:             if ($start) {
                    530: 		if ($now<$start) { $notactive=1; }
                    531:             }
                    532:             if ($end) {
                    533:                 if ($now>$end) { $notactive=1; }
                    534:             } 
                    535:             unless ($notactive) { return $section; }
                    536:         }
1.191     harris41  537:     }
1.70      www       538:     return '-1';
                    539: }
                    540: 
                    541: # ------------------------------------- Read an entry from a user's environment
                    542: 
                    543: sub userenvironment {
                    544:     my ($udom,$unam,@what)=@_;
                    545:     my %returnhash=();
                    546:     my @answer=split(/\&/,
                    547:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    548:                       &homeserver($unam,$udom)));
                    549:     my $i;
                    550:     for ($i=0;$i<=$#what;$i++) {
                    551: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    552:     }
                    553:     return %returnhash;
1.1       albertel  554: }
                    555: 
                    556: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www       557: 
1.1       albertel  558: sub subscribe {
                    559:     my $fname=shift;
                    560:     my $author=$fname;
                    561:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    562:     my ($udom,$uname)=split(/\//,$author);
                    563:     my $home=homeserver($uname,$udom);
                    564:     if (($home eq 'no_host') || ($home eq $perlvar{'lonHostID'})) { 
                    565:         return 'not_found'; 
                    566:     }
                    567:     my $answer=reply("sub:$fname",$home);
1.64      www       568:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    569: 	$answer.=' by '.$home;
                    570:     }
1.1       albertel  571:     return $answer;
                    572: }
                    573:     
1.8       www       574: # -------------------------------------------------------------- Replicate file
                    575: 
                    576: sub repcopy {
                    577:     my $filename=shift;
1.23      www       578:     $filename=~s/\/+/\//g;
1.8       www       579:     my $transname="$filename.in.transfer";
1.17      www       580:     if ((-e $filename) || (-e $transname)) { return OK; }
1.8       www       581:     my $remoteurl=subscribe($filename);
1.64      www       582:     if ($remoteurl =~ /^con_lost by/) {
                    583: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       584:            return HTTP_SERVICE_UNAVAILABLE;
                    585:     } elsif ($remoteurl eq 'not_found') {
                    586: 	   &logthis("Subscribe returned not_found: $filename");
                    587: 	   return HTTP_NOT_FOUND;
1.64      www       588:     } elsif ($remoteurl =~ /^rejected by/) {
                    589: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       590:            return FORBIDDEN;
1.20      www       591:     } elsif ($remoteurl eq 'directory') {
                    592:            return OK;
1.8       www       593:     } else {
                    594:            my @parts=split(/\//,$filename);
                    595:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                    596:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                    597:                &logthis("Malconfiguration for replication: $filename");
                    598: 	       return HTTP_BAD_REQUEST;
                    599:            }
                    600:            my $count;
                    601:            for ($count=5;$count<$#parts;$count++) {
                    602:                $path.="/$parts[$count]";
                    603:                if ((-e $path)!=1) {
                    604: 		   mkdir($path,0777);
                    605:                }
                    606:            }
                    607:            my $ua=new LWP::UserAgent;
                    608:            my $request=new HTTP::Request('GET',"$remoteurl");
                    609:            my $response=$ua->request($request,$transname);
                    610:            if ($response->is_error()) {
                    611: 	       unlink($transname);
                    612:                my $message=$response->status_line;
1.12      www       613:                &logthis("<font color=blue>WARNING:"
                    614:                        ." LWP get: $message: $filename</font>");
1.8       www       615:                return HTTP_SERVICE_UNAVAILABLE;
                    616:            } else {
1.16      www       617: 	       if ($remoteurl!~/\.meta$/) {
                    618:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                    619:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                    620:                   if ($mresponse->is_error()) {
                    621: 		      unlink($filename.'.meta');
                    622:                       &logthis(
                    623:                      "<font color=yellow>INFO: No metadata: $filename</font>");
                    624:                   }
                    625: 	       }
1.8       www       626:                rename($transname,$filename);
                    627:                return OK;
                    628:            }
                    629:     }
                    630: }
                    631: 
1.15      www       632: # --------------------------------------------------------- Server Side Include
                    633: 
                    634: sub ssi {
                    635: 
1.23      www       636:     my ($fn,%form)=@_;
1.15      www       637: 
                    638:     my $ua=new LWP::UserAgent;
1.23      www       639:     
                    640:     my $request;
                    641:     
                    642:     if (%form) {
                    643:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
                    644:       $request->content(join '&', map { "$_=$form{$_}" } keys %form);
                    645:     } else {
                    646:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                    647:     }
                    648: 
1.15      www       649:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                    650:     my $response=$ua->request($request);
                    651: 
                    652:     return $response->content;
                    653: }
                    654: 
1.14      www       655: # ------------------------------------------------------------------------- Log
                    656: 
                    657: sub log {
                    658:     my ($dom,$nam,$hom,$what)=@_;
1.47      www       659:     return critical("log:$dom:$nam:$what",$hom);
1.157     www       660: }
                    661: 
                    662: # ------------------------------------------------------------------ Course Log
                    663: 
                    664: sub flushcourselogs {
                    665:     &logthis('Flushing course log buffers');
1.191     harris41  666:     foreach (keys %courselogs) {
1.157     www       667:         my $crsid=$_;
1.188     www       668:         if (&reply('log:'.$coursedombuf{$crsid}.':'.
                    669: 		          &escape($courselogs{$crsid}),
                    670: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www       671: 	    delete $courselogs{$crsid};
                    672:         } else {
                    673:             &logthis('Failed to flush log buffer for '.$crsid);
                    674:             if (length($courselogs{$crsid})>40000) {
                    675:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
                    676:                         " exceeded maximum size, deleting.</font>");
                    677:                delete $courselogs{$crsid};
                    678:             }
                    679:         }        
1.191     harris41  680:     }
1.185     www       681:     &logthis('Flushing access logs');
1.191     harris41  682:     foreach (keys %accesshash) {
1.185     www       683:         my $entry=$_;
                    684:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
                    685:         my %temphash=($entry => $accesshash{$entry});
                    686:         if (&Apache::lonnet::put('resevaldata',\%temphash,$1,$2) eq 'ok') {
                    687: 	    delete $accesshash{$entry};
                    688:         }
1.191     harris41  689:     }
1.186     www       690:     $dumpcount++;
1.157     www       691: }
                    692: 
                    693: sub courselog {
                    694:     my $what=shift;
1.158     www       695:     $what=time.':'.$what;
1.157     www       696:     unless ($ENV{'request.course.id'}) { return ''; }
1.188     www       697:     $coursedombuf{$ENV{'request.course.id'}}=
                    698:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
                    699:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                    700:     $coursehombuf{$ENV{'request.course.id'}}=
                    701:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.157     www       702:     if (defined $courselogs{$ENV{'request.course.id'}}) {
                    703: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
                    704:     } else {
                    705: 	$courselogs{$ENV{'request.course.id'}}.=$what;
                    706:     }
                    707:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
                    708: 	&flushcourselogs();
                    709:     }
1.158     www       710: }
                    711: 
                    712: sub courseacclog {
                    713:     my $fnsymb=shift;
                    714:     unless ($ENV{'request.course.id'}) { return ''; }
                    715:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.192     www       716:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
1.187     www       717:         $what.=':POST';
1.191     harris41  718: 	foreach (keys %ENV) {
1.158     www       719:             if ($_=~/^form\.(.*)/) {
                    720: 		$what.=':'.$1.'='.$ENV{$_};
                    721:             }
1.191     harris41  722:         }
1.158     www       723:     }
                    724:     &courselog($what);
1.149     www       725: }
                    726: 
1.185     www       727: sub countacc {
                    728:     my $url=&declutter(shift);
                    729:     unless ($ENV{'request.course.id'}) { return ''; }
                    730:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
1.186     www       731:     my $key=$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.185     www       732:     if (defined($accesshash{$key})) {
                    733: 	$accesshash{$key}++;
                    734:     } else {
                    735:         $accesshash{$key}=1;
                    736:     }
                    737: }
                    738:     
1.149     www       739: # ----------------------------------------------------------- Check out an item
                    740: 
                    741: sub checkout {
                    742:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                    743:     my $now=time;
                    744:     my $lonhost=$perlvar{'lonHostID'};
                    745:     my $infostr=&escape(
                    746:                  $tuname.'&'.
                    747:                  $tudom.'&'.
                    748:                  $tcrsid.'&'.
                    749:                  $symb.'&'.
                    750: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                    751:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www       752:     if ($token=~/^error\:/) { 
                    753:         &logthis("<font color=blue>WARNING: ".
                    754:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                    755:                  "</font>");
                    756:         return ''; 
                    757:     }
                    758: 
1.149     www       759:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                    760:     $token=~tr/a-z/A-Z/;
                    761: 
1.153     www       762:     my %infohash=('resource.0.outtoken' => $token,
                    763:                   'resource.0.checkouttime' => $now,
                    764:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www       765: 
                    766:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                    767:        return '';
1.151     www       768:     } else {
                    769:         &logthis("<font color=blue>WARNING: ".
                    770:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                    771:                  "</font>");
1.149     www       772:     }    
                    773: 
                    774:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                    775:                          &escape('Checkout '.$infostr.' - '.
                    776:                                                  $token)) ne 'ok') {
                    777: 	return '';
1.151     www       778:     } else {
                    779:         &logthis("<font color=blue>WARNING: ".
                    780:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                    781:                  "</font>");
1.149     www       782:     }
1.151     www       783:     return $token;
1.149     www       784: }
                    785: 
                    786: # ------------------------------------------------------------ Check in an item
                    787: 
                    788: sub checkin {
                    789:     my $token=shift;
1.150     www       790:     my $now=time;
                    791:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                    792:     $lonhost=~tr/A-Z/a-z/;
                    793:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
                    794:     $dtoken=~s/\W/\_/g;
                    795:     my ($tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                    796:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                    797: 
1.154     www       798:     unless (($tuname) && ($tudom)) {
                    799:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                    800:         return '';
                    801:     }
                    802:     
                    803:     unless (&allowed('mgr',$tcrsid)) {
                    804:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                    805:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
                    806:         return '';
                    807:     }
                    808: 
1.153     www       809:     my %infohash=('resource.0.intoken' => $token,
                    810:                   'resource.0.checkintime' => $now,
                    811:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www       812: 
                    813:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                    814:        return '';
                    815:     }    
                    816: 
                    817:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                    818:                          &escape('Checkin - '.$token)) ne 'ok') {
                    819: 	return '';
                    820:     }
                    821: 
                    822:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www       823: }
                    824: 
                    825: # --------------------------------------------- Set Expire Date for Spreadsheet
                    826: 
                    827: sub expirespread {
                    828:     my ($uname,$udom,$stype,$usymb)=@_;
                    829:     my $cid=$ENV{'request.course.id'}; 
                    830:     if ($cid) {
                    831:        my $now=time;
                    832:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
                    833:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
                    834:                             $ENV{'course.'.$cid.'.num'}.
                    835: 	        	    ':nohist_expirationdates:'.
                    836:                             &escape($key).'='.$now,
                    837:                             $ENV{'course.'.$cid.'.home'})
                    838:     }
                    839:     return 'ok';
1.14      www       840: }
                    841: 
1.109     www       842: # ----------------------------------------------------- Devalidate Spreadsheets
                    843: 
                    844: sub devalidate {
                    845:     my $symb=shift;
                    846:     my $cid=$ENV{'request.course.id'}; 
                    847:     if ($cid) {
                    848: 	my $key=$ENV{'user.name'}.':'.$ENV{'user.domain'}.':';
                    849:         my $status=
1.133     albertel  850: 	    &del('nohist_calculatedsheet',
                    851: 		 [$key.'studentcalc'],
                    852: 		 $ENV{'course.'.$cid.'.domain'},
                    853: 		 $ENV{'course.'.$cid.'.num'})
                    854: 		.' '.
                    855: 	    &del('nohist_calculatedsheets_'.$cid,
                    856: 		 [$key.'assesscalc:'.$symb]);
1.109     www       857:         unless ($status eq 'ok ok') {
                    858:            &logthis('Could not devalidate spreadsheet '.
                    859:                     $ENV{'user.name'}.' at '.$ENV{'user.domain'}.' for '.
                    860: 		    $symb.': '.$status);
1.133     albertel  861:         }
1.109     www       862:     }
                    863: }
                    864: 
1.168     albertel  865: sub hash2str {
                    866:   my (%hash)=@_;
                    867:   my $result='';
1.191     harris41  868:   foreach (keys %hash) { $result.=escape($_).'='.escape($hash{$_}).'&'; }
1.168     albertel  869:   $result=~s/\&$//;
                    870:   return $result;
                    871: }
                    872: 
                    873: sub str2hash {
                    874:   my ($string) = @_;
                    875:   my %returnhash;
1.191     harris41  876:   foreach (split(/\&/,$string)) {
1.168     albertel  877:     my ($name,$value)=split(/\=/,$_);
                    878:     $returnhash{&unescape($name)}=&unescape($value);
1.191     harris41  879:   }
1.168     albertel  880:   return %returnhash;
                    881: }
                    882: 
1.167     albertel  883: # -------------------------------------------------------------------Temp Store
                    884: 
1.168     albertel  885: sub tmpreset {
                    886:   my ($symb,$namespace,$domain,$stuname) = @_;
                    887:   if (!$symb) {
                    888:     $symb=&symbread();
                    889:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
                    890:   }
                    891:   $symb=escape($symb);
                    892: 
                    893:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                    894:   $namespace=~s/\//\_/g;
                    895:   $namespace=~s/\W//g;
                    896: 
                    897:   #FIXME needs to do something for /pub resources
                    898:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                    899:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                    900:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                    901:   my %hash;
                    902:   if (tie(%hash,'GDBM_File',
                    903: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
                    904: 	  &GDBM_WRCREAT,0640)) {
                    905:     foreach my $key (keys %hash) {
1.180     albertel  906:       if ($key=~ /:$symb/) {
1.168     albertel  907: 	delete($hash{$key});
                    908:       }
                    909:     }
                    910:   }
                    911: }
                    912: 
1.167     albertel  913: sub tmpstore {
1.168     albertel  914:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                    915: 
                    916:   if (!$symb) {
                    917:     $symb=&symbread();
                    918:     if (!$symb) { $symb= $ENV{'request.url'}; }
                    919:   }
                    920:   $symb=escape($symb);
                    921: 
                    922:   if (!$namespace) {
                    923:     # I don't think we would ever want to store this for a course.
                    924:     # it seems this will only be used if we don't have a course.
                    925:     #$namespace=$ENV{'request.course.id'};
                    926:     #if (!$namespace) {
                    927:       $namespace=$ENV{'request.state'};
                    928:     #}
                    929:   }
                    930:   $namespace=~s/\//\_/g;
                    931:   $namespace=~s/\W//g;
                    932: #FIXME needs to do something for /pub resources
                    933:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                    934:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                    935:   my $now=time;
                    936:   my %hash;
                    937:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                    938:   if (tie(%hash,'GDBM_File',
                    939: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
                    940: 	  &GDBM_WRCREAT,0640)) {
                    941:     $hash{"version:$symb"}++;
                    942:     my $version=$hash{"version:$symb"};
                    943:     my $allkeys=''; 
                    944:     foreach my $key (keys(%$storehash)) {
                    945:       $allkeys.=$key.':';
                    946:       $hash{"$version:$symb:$key"}=$$storehash{$key};
                    947:     }
                    948:     $hash{"$version:$symb:timestamp"}=$now;
                    949:     $allkeys.='timestamp';
                    950:     $hash{"$version:keys:$symb"}=$allkeys;
                    951:     if (untie(%hash)) {
                    952:       return 'ok';
                    953:     } else {
                    954:       return "error:$!";
                    955:     }
                    956:   } else {
                    957:     return "error:$!";
                    958:   }
                    959: }
1.167     albertel  960: 
1.168     albertel  961: # -----------------------------------------------------------------Temp Restore
1.167     albertel  962: 
1.168     albertel  963: sub tmprestore {
                    964:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel  965: 
1.168     albertel  966:   if (!$symb) {
                    967:     $symb=&symbread();
                    968:     if (!$symb) { $symb= $ENV{'request.url'}; }
                    969:   }
                    970:   $symb=escape($symb);
                    971: 
                    972:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                    973:   #FIXME needs to do something for /pub resources
                    974:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                    975:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                    976: 
                    977:   my %returnhash;
                    978:   $namespace=~s/\//\_/g;
                    979:   $namespace=~s/\W//g;
                    980:   my %hash;
                    981:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                    982:   if (tie(%hash,'GDBM_File',
                    983: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
                    984: 	  &GDBM_READER,0640)) {
                    985:     my $version=$hash{"version:$symb"};
                    986:     $returnhash{'version'}=$version;
                    987:     my $scope;
                    988:     for ($scope=1;$scope<=$version;$scope++) {
                    989:       my $vkeys=$hash{"$scope:keys:$symb"};
                    990:       my @keys=split(/:/,$vkeys);
                    991:       my $key;
                    992:       $returnhash{"$scope:keys"}=$vkeys;
                    993:       foreach $key (@keys) {
                    994: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
                    995: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1.167     albertel  996:       }
                    997:     }
1.168     albertel  998:     if (!(untie(%hash))) {
                    999:       return "error:$!";
                   1000:     }
                   1001:   } else {
                   1002:     return "error:$!";
                   1003:   }
                   1004:   return %returnhash;
1.167     albertel 1005: }
                   1006: 
1.9       www      1007: # ----------------------------------------------------------------------- Store
                   1008: 
                   1009: sub store {
1.124     www      1010:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1011:     my $home='';
                   1012: 
1.168     albertel 1013:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1014: 
1.122     albertel 1015:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1016: 
                   1017:     &devalidate($symb);
                   1018: 
                   1019:     $symb=escape($symb);
1.187     www      1020:     if (!$namespace) { 
                   1021:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1022:           return ''; 
                   1023:        } 
                   1024:     }
1.122     albertel 1025:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1026:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1027:     if (!$home) { $home=$ENV{'user.home'}; }
1.12      www      1028:     my $namevalue='';
1.191     harris41 1029:     foreach (keys %$storehash) {
1.122     albertel 1030:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1031:     }
1.12      www      1032:     $namevalue=~s/\&$//;
1.187     www      1033:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      1034:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      1035: }
                   1036: 
1.47      www      1037: # -------------------------------------------------------------- Critical Store
                   1038: 
                   1039: sub cstore {
1.124     www      1040:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1041:     my $home='';
                   1042: 
1.168     albertel 1043:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1044: 
1.122     albertel 1045:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1046: 
                   1047:     &devalidate($symb);
                   1048: 
                   1049:     $symb=escape($symb);
1.187     www      1050:     if (!$namespace) { 
                   1051:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1052:           return ''; 
                   1053:        } 
                   1054:     }
1.122     albertel 1055:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1056:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1057:     if (!$home) { $home=$ENV{'user.home'}; }
                   1058: 
1.47      www      1059:     my $namevalue='';
1.191     harris41 1060:     foreach (keys %$storehash) {
1.122     albertel 1061:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1062:     }
1.47      www      1063:     $namevalue=~s/\&$//;
1.187     www      1064:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      1065:     return critical
                   1066:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      1067: }
                   1068: 
1.9       www      1069: # --------------------------------------------------------------------- Restore
                   1070: 
                   1071: sub restore {
1.124     www      1072:     my ($symb,$namespace,$domain,$stuname) = @_;
                   1073:     my $home='';
                   1074: 
1.168     albertel 1075:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1076: 
1.122     albertel 1077:     if (!$symb) {
                   1078:       unless ($symb=escape(&symbread())) { return ''; }
                   1079:     } else {
                   1080:       $symb=&escape($symb);
                   1081:     }
1.188     www      1082:     if (!$namespace) { 
                   1083:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1084:           return ''; 
                   1085:        } 
                   1086:     }
1.122     albertel 1087:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1088:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1089:     if (!$home) { $home=$ENV{'user.home'}; }
                   1090:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   1091: 
1.12      www      1092:     my %returnhash=();
1.191     harris41 1093:     foreach (split(/\&/,$answer)) {
1.12      www      1094: 	my ($name,$value)=split(/\=/,$_);
                   1095:         $returnhash{&unescape($name)}=&unescape($value);
1.191     harris41 1096:     }
1.75      www      1097:     my $version;
                   1098:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 1099:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      1100:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 1101:        }
1.75      www      1102:     }
1.13      www      1103:     return %returnhash;
1.34      www      1104: }
                   1105: 
                   1106: # ---------------------------------------------------------- Course Description
                   1107: 
                   1108: sub coursedescription {
                   1109:     my $courseid=shift;
                   1110:     $courseid=~s/^\///;
1.49      www      1111:     $courseid=~s/\_/\//g;
1.34      www      1112:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 1113:     my $chome=&homeserver($cnum,$cdomain);
1.34      www      1114:     if ($chome ne 'no_host') {
1.129     albertel 1115:        my %returnhash=&dump('environment',$cdomain,$cnum);
                   1116:        if (!exists($returnhash{'con_lost'})) {
1.96      www      1117:            my $normalid=$cdomain.'_'.$cnum;
1.53      www      1118:            my %envhash=();
1.129     albertel 1119:            $returnhash{'home'}= $chome;
                   1120: 	   $returnhash{'domain'} = $cdomain;
                   1121: 	   $returnhash{'num'} = $cnum;
1.130     albertel 1122:            while (my ($name,$value) = each %returnhash) {
1.53      www      1123:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 1124:            }
1.34      www      1125:            $returnhash{'url'}='/res/'.declutter($returnhash{'url'});
                   1126:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.38      www      1127: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.54      www      1128:            $envhash{'course.'.$normalid.'.last_cache'}=time;
1.60      www      1129:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   1130:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   1131:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.53      www      1132:            &appenv(%envhash);
1.34      www      1133:            return %returnhash;
                   1134:        }
                   1135:     }
                   1136:     return ();
1.9       www      1137: }
1.1       albertel 1138: 
1.103     harris41 1139: # -------------------------------------------------------- Get user privileges
1.11      www      1140: 
                   1141: sub rolesinit {
                   1142:     my ($domain,$username,$authhost)=@_;
                   1143:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      1144:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      1145:     my %allroles=();
                   1146:     my %thesepriv=();
                   1147:     my $now=time;
1.21      www      1148:     my $userroles="user.login.time=$now\n";
1.11      www      1149:     my $thesestr;
                   1150: 
                   1151:     if ($rolesdump ne '') {
1.191     harris41 1152:         foreach (split(/&/,$rolesdump)) {
1.21      www      1153: 	  if ($_!~/^rolesdef\&/) {
1.11      www      1154:             my ($area,$role)=split(/=/,$_);
1.21      www      1155:             $area=~s/\_\w\w$//;
1.11      www      1156:             my ($trole,$tend,$tstart)=split(/_/,$role);
1.21      www      1157:             $userroles.='user.role.'.$trole.'.'.$area.'='.
                   1158:                         $tstart.'.'.$tend."\n";
1.11      www      1159:             if ($tend!=0) {
                   1160: 	        if ($tend<$now) {
                   1161: 	            $trole='';
                   1162:                 } 
                   1163:             }
                   1164:             if ($tstart!=0) {
                   1165:                 if ($tstart>$now) {
                   1166:                    $trole='';        
                   1167:                 }
                   1168:             }
                   1169:             if (($area ne '') && ($trole ne '')) {
1.50      www      1170: 	       my $spec=$trole.'.'.$area;
1.12      www      1171:                my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   1172:                if ($trole =~ /^cr\//) {
                   1173: 		   my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   1174:                    my $homsvr=homeserver($rauthor,$rdomain);
                   1175:                    if ($hostname{$homsvr} ne '') {
                   1176:                       my $roledef=
1.21      www      1177: 			  reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
1.12      www      1178:                                 $homsvr);
                   1179:                       if (($roledef ne 'con_lost') && ($roledef ne '')) {
                   1180:                          my ($syspriv,$dompriv,$coursepriv)=
1.21      www      1181: 			     split(/\_/,unescape($roledef));
1.50      www      1182:  	                 $allroles{'cm./'}.=':'.$syspriv;
                   1183:                          $allroles{$spec.'./'}.=':'.$syspriv;
1.12      www      1184:                          if ($tdomain ne '') {
1.50      www      1185:                              $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   1186:                              $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
1.12      www      1187:                              if ($trest ne '') {
1.50      www      1188: 		                $allroles{'cm.'.$area}.=':'.$coursepriv;
                   1189: 		                $allroles{$spec.'.'.$area}.=':'.$coursepriv;
1.12      www      1190:                              }
                   1191: 	                 }
                   1192:                       }
1.11      www      1193:                    }
1.12      www      1194:                } else {
1.50      www      1195: 	           $allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   1196: 	           $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
1.12      www      1197:                    if ($tdomain ne '') {
1.50      www      1198:                      $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   1199:                      $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
1.12      www      1200:                       if ($trest ne '') {
1.50      www      1201: 		          $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   1202: 		          $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
1.12      www      1203:                       }
                   1204: 	           }
1.11      www      1205: 	       }
1.12      www      1206:             }
                   1207:           } 
1.191     harris41 1208:         }
1.125     www      1209:         my $adv=0;
1.128     www      1210:         my $author=0;
1.191     harris41 1211:         foreach (keys %allroles) {
1.11      www      1212:             %thesepriv=();
1.146     www      1213:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1.128     www      1214:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1.191     harris41 1215:             foreach (split(/:/,$allroles{$_})) {
1.11      www      1216:                 if ($_ ne '') {
1.103     harris41 1217: 		    my ($privilege,$restrictions)=split(/&/,$_);
1.11      www      1218:                     if ($restrictions eq '') {
1.103     harris41 1219: 			$thesepriv{$privilege}='F';
1.11      www      1220:                     } else {
1.103     harris41 1221:                         if ($thesepriv{$privilege} ne 'F') {
                   1222: 			    $thesepriv{$privilege}.=$restrictions;
1.11      www      1223:                         }
                   1224:                     }
                   1225:                 }
1.191     harris41 1226:             }
1.11      www      1227:             $thesestr='';
1.191     harris41 1228:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.11      www      1229:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1.191     harris41 1230:         }
1.128     www      1231:         $userroles.='user.adv='.$adv."\n".
                   1232: 	            'user.author='.$author."\n";
1.126     www      1233:         $ENV{'user.adv'}=$adv;
1.11      www      1234:     }
                   1235:     return $userroles;  
                   1236: }
                   1237: 
1.12      www      1238: # --------------------------------------------------------------- get interface
                   1239: 
                   1240: sub get {
1.131     albertel 1241:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      1242:    my $items='';
1.191     harris41 1243:    foreach (@$storearr) {
1.12      www      1244:        $items.=escape($_).'&';
1.191     harris41 1245:    }
1.12      www      1246:    $items=~s/\&$//;
1.131     albertel 1247:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1248:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1249:    my $uhome=&homeserver($uname,$udomain);
                   1250: 
1.133     albertel 1251:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      1252:    my @pairs=split(/\&/,$rep);
                   1253:    my %returnhash=();
1.42      www      1254:    my $i=0;
1.191     harris41 1255:    foreach (@$storearr) {
1.42      www      1256:       $returnhash{$_}=unescape($pairs[$i]);
                   1257:       $i++;
1.191     harris41 1258:    }
1.15      www      1259:    return %returnhash;
1.27      www      1260: }
                   1261: 
                   1262: # --------------------------------------------------------------- del interface
                   1263: 
                   1264: sub del {
1.133     albertel 1265:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      1266:    my $items='';
1.191     harris41 1267:    foreach (@$storearr) {
1.27      www      1268:        $items.=escape($_).'&';
1.191     harris41 1269:    }
1.27      www      1270:    $items=~s/\&$//;
1.133     albertel 1271:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1272:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1273:    my $uhome=&homeserver($uname,$udomain);
                   1274: 
                   1275:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      1276: }
                   1277: 
                   1278: # -------------------------------------------------------------- dump interface
                   1279: 
                   1280: sub dump {
1.193     www      1281:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.129     albertel 1282:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1283:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1284:    my $uhome=&homeserver($uname,$udomain);
1.193     www      1285:    if ($regexp) {
                   1286:        $regexp=&escape($regexp);
                   1287:    } else {
                   1288:        $regexp='.';
                   1289:    }
                   1290:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      1291:    my @pairs=split(/\&/,$rep);
                   1292:    my %returnhash=();
1.191     harris41 1293:    foreach (@pairs) {
1.12      www      1294:       my ($key,$value)=split(/=/,$_);
1.29      www      1295:       $returnhash{unescape($key)}=unescape($value);
1.191     harris41 1296:    }
1.12      www      1297:    return %returnhash;
                   1298: }
                   1299: 
                   1300: # --------------------------------------------------------------- put interface
                   1301: 
                   1302: sub put {
1.134     albertel 1303:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   1304:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1305:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1306:    my $uhome=&homeserver($uname,$udomain);
1.12      www      1307:    my $items='';
1.191     harris41 1308:    foreach (keys %$storehash) {
1.134     albertel 1309:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1.191     harris41 1310:    }
1.12      www      1311:    $items=~s/\&$//;
1.134     albertel 1312:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      1313: }
                   1314: 
                   1315: # ------------------------------------------------------ critical put interface
                   1316: 
                   1317: sub cput {
1.134     albertel 1318:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   1319:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1320:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1321:    my $uhome=&homeserver($uname,$udomain);
1.47      www      1322:    my $items='';
1.191     harris41 1323:    foreach (keys %$storehash) {
1.134     albertel 1324:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1325:    }
1.47      www      1326:    $items=~s/\&$//;
1.134     albertel 1327:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      1328: }
                   1329: 
                   1330: # -------------------------------------------------------------- eget interface
                   1331: 
                   1332: sub eget {
1.133     albertel 1333:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      1334:    my $items='';
1.191     harris41 1335:    foreach (@$storearr) {
1.12      www      1336:        $items.=escape($_).'&';
1.191     harris41 1337:    }
1.12      www      1338:    $items=~s/\&$//;
1.133     albertel 1339:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1340:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1341:    my $uhome=&homeserver($uname,$udomain);
                   1342:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      1343:    my @pairs=split(/\&/,$rep);
                   1344:    my %returnhash=();
1.42      www      1345:    my $i=0;
1.191     harris41 1346:    foreach (@$storearr) {
1.42      www      1347:       $returnhash{$_}=unescape($pairs[$i]);
                   1348:       $i++;
1.191     harris41 1349:    }
1.12      www      1350:    return %returnhash;
                   1351: }
                   1352: 
1.103     harris41 1353: # ------------------------------------------------- Check for a user privilege
1.12      www      1354: 
                   1355: sub allowed {
                   1356:     my ($priv,$uri)=@_;
1.152     www      1357: 
                   1358:     my $orguri=$uri;
1.52      www      1359:     $uri=&declutter($uri);
1.29      www      1360: 
1.54      www      1361: # Free bre access to adm and meta resources
1.29      www      1362: 
1.54      www      1363:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      1364: 	return 'F';
1.159     www      1365:     }
                   1366: 
                   1367: # Free bre to public access
                   1368: 
                   1369:     if ($priv eq 'bre') {
                   1370: 	if (&metadata($uri,'copyright') eq 'public') { return 'F'; }
1.14      www      1371:     }
1.29      www      1372: 
1.52      www      1373:     my $thisallowed='';
                   1374:     my $statecond=0;
                   1375:     my $courseprivid='';
                   1376: 
                   1377: # Course
                   1378: 
                   1379:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
                   1380:        $thisallowed.=$1;
                   1381:     }
1.29      www      1382: 
1.52      www      1383: # Domain
                   1384: 
                   1385:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
                   1386:        =~/$priv\&([^\:]*)/) {
1.12      www      1387:        $thisallowed.=$1;
                   1388:     }
1.52      www      1389: 
                   1390: # Course: uri itself is a course
1.66      www      1391:     my $courseuri=$uri;
                   1392:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      1393:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      1394: 
1.83      www      1395:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.52      www      1396:        =~/$priv\&([^\:]*)/) {
1.12      www      1397:        $thisallowed.=$1;
                   1398:     }
1.29      www      1399: 
1.52      www      1400: # Full access at system, domain or course-wide level? Exit.
1.29      www      1401: 
                   1402:     if ($thisallowed=~/F/) {
                   1403: 	return 'F';
                   1404:     }
                   1405: 
1.52      www      1406: # If this is generating or modifying users, exit with special codes
1.29      www      1407: 
1.166     www      1408:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1.52      www      1409: 	return $thisallowed;
                   1410:     }
                   1411: #
1.103     harris41 1412: # Gathered so far: system, domain and course wide privileges
1.52      www      1413: #
                   1414: # Course: See if uri or referer is an individual resource that is part of 
                   1415: # the course
                   1416: 
                   1417:     if ($ENV{'request.course.id'}) {
                   1418:        $courseprivid=$ENV{'request.course.id'};
                   1419:        if ($ENV{'request.course.sec'}) {
                   1420:           $courseprivid.='/'.$ENV{'request.course.sec'};
                   1421:        }
                   1422:        $courseprivid=~s/\_/\//;
                   1423:        my $checkreferer=1;
                   1424:        my @uriparts=split(/\//,$uri);
                   1425:        my $filename=$uriparts[$#uriparts];
                   1426:        my $pathname=$uri;
                   1427:        $pathname=~s/\/$filename$//;
                   1428:        if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.54      www      1429:            /\&$filename\:([\d\|]+)\&/) {
1.52      www      1430:            $statecond=$1;
                   1431:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   1432:                =~/$priv\&([^\:]*)/) {
                   1433:                $thisallowed.=$1;
                   1434:                $checkreferer=0;
                   1435:            }
1.29      www      1436:        }
1.83      www      1437:        
1.148     www      1438:        if ($checkreferer) {
1.152     www      1439: 	  my $refuri=$ENV{'httpref.'.$orguri};
1.148     www      1440: 
                   1441:             unless ($refuri) {
1.191     harris41 1442:                 foreach (keys %ENV) {
1.148     www      1443: 		    if ($_=~/^httpref\..*\*/) {
                   1444: 			my $pattern=$_;
1.156     www      1445:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      1446:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   1447:                         $pattern=~s/\//\\\//g;
1.152     www      1448:                         if ($orguri=~/$pattern/) {
1.148     www      1449: 			    $refuri=$ENV{$_};
                   1450:                         }
                   1451:                     }
1.191     harris41 1452:                 }
1.148     www      1453:             }
                   1454:          if ($refuri) { 
1.152     www      1455: 	  $refuri=&declutter($refuri);
1.53      www      1456:           my @uriparts=split(/\//,$refuri);
1.52      www      1457:           my $filename=$uriparts[$#uriparts];
1.53      www      1458:           my $pathname=$refuri;
1.52      www      1459:           $pathname=~s/\/$filename$//;
1.53      www      1460:             if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.54      www      1461:               /\&$filename\:([\d\|]+)\&/) {
1.53      www      1462:               my $refstatecond=$1;
1.52      www      1463:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   1464:                   =~/$priv\&([^\:]*)/) {
                   1465:                   $thisallowed.=$1;
1.53      www      1466:                   $uri=$refuri;
                   1467:                   $statecond=$refstatecond;
1.52      www      1468:               }
                   1469:           }
1.148     www      1470:         }
1.29      www      1471:        }
1.52      www      1472:    }
1.29      www      1473: 
1.52      www      1474: #
1.103     harris41 1475: # Gathered now: all privileges that could apply, and condition number
1.52      www      1476: # 
                   1477: #
                   1478: # Full or no access?
                   1479: #
1.29      www      1480: 
1.52      www      1481:     if ($thisallowed=~/F/) {
                   1482: 	return 'F';
                   1483:     }
1.29      www      1484: 
1.52      www      1485:     unless ($thisallowed) {
                   1486:         return '';
                   1487:     }
1.29      www      1488: 
1.52      www      1489: # Restrictions exist, deal with them
                   1490: #
                   1491: #   C:according to course preferences
                   1492: #   R:according to resource settings
                   1493: #   L:unless locked
                   1494: #   X:according to user session state
                   1495: #
                   1496: 
                   1497: # Possibly locked functionality, check all courses
1.54      www      1498: # Locks might take effect only after 10 minutes cache expiration for other
                   1499: # courses, and 2 minutes for current course
1.52      www      1500: 
                   1501:     my $envkey;
                   1502:     if ($thisallowed=~/L/) {
                   1503:         foreach $envkey (keys %ENV) {
1.54      www      1504:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   1505:                my $courseid=$2;
                   1506:                my $roleid=$1.'.'.$2;
1.92      www      1507:                $courseid=~s/^\///;
1.54      www      1508:                my $expiretime=600;
                   1509:                if ($ENV{'request.role'} eq $roleid) {
                   1510: 		  $expiretime=120;
                   1511:                }
                   1512: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   1513:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
                   1514:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
                   1515: 		   &coursedescription($courseid);
                   1516:                }
                   1517:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
                   1518:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   1519: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57      www      1520:                        &log($ENV{'user.domain'},$ENV{'user.name'},
                   1521:                             $ENV{'user.host'},
                   1522:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      1523:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      1524:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      1525: 		       return '';
                   1526:                    }
                   1527:                }
1.54      www      1528:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
                   1529:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   1530: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57      www      1531:                        &log($ENV{'user.domain'},$ENV{'user.name'},
                   1532:                             $ENV{'user.host'},
                   1533:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      1534:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      1535:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      1536: 		       return '';
                   1537:                    }
                   1538:                }
                   1539: 	   }
1.29      www      1540:        }
1.52      www      1541:     }
                   1542:    
                   1543: #
                   1544: # Rest of the restrictions depend on selected course
                   1545: #
                   1546: 
                   1547:     unless ($ENV{'request.course.id'}) {
                   1548:        return '1';
                   1549:     }
1.29      www      1550: 
1.52      www      1551: #
                   1552: # Now user is definitely in a course
                   1553: #
1.53      www      1554: 
                   1555: 
                   1556: # Course preferences
                   1557: 
                   1558:    if ($thisallowed=~/C/) {
1.54      www      1559:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
                   1560:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.194     www      1561: 	   =~/$rolecode/) {
1.57      www      1562:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1563:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.54      www      1564:                 $ENV{'request.course.id'});
                   1565:            return '';
                   1566:        }
1.53      www      1567:    }
                   1568: 
                   1569: # Resource preferences
                   1570: 
                   1571:    if ($thisallowed=~/R/) {
1.54      www      1572:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
                   1573:        my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
                   1574:        if (-e $filename) {
                   1575:            my @content;
                   1576:            {
                   1577: 	     my $fh=Apache::File->new($filename);
                   1578:              @content=<$fh>;
                   1579: 	   }
                   1580:            if (join('',@content)=~
                   1581:                     /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
1.57      www      1582: 	       &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1583:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.54      www      1584:            return '';
                   1585: 
                   1586:            }
                   1587:        }
1.53      www      1588:    }
1.30      www      1589: 
1.52      www      1590: # Restricted by state?
1.30      www      1591: 
1.52      www      1592:    if ($thisallowed=~/X/) {
                   1593:       if (&condval($statecond)) {
                   1594: 	 return '2';
                   1595:       } else {
                   1596:          return '';
                   1597:       }
                   1598:    }
1.30      www      1599: 
1.52      www      1600:    return 'F';
1.12      www      1601: }
                   1602: 
                   1603: # ----------------------------------------------------------------- Define Role
                   1604: 
                   1605: sub definerole {
                   1606:   if (allowed('mcr','/')) {
                   1607:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.191     harris41 1608:     foreach (split('/',$sysrole)) {
1.21      www      1609: 	my ($crole,$cqual)=split(/\&/,$_);
                   1610:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
                   1611:         if ($pr{'cr:s'}=~/$crole\&/) {
                   1612: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
                   1613:                return "refused:s:$crole&$cqual"; 
                   1614:             }
                   1615:         }
1.191     harris41 1616:     }
                   1617:     foreach (split('/',$domrole)) {
1.21      www      1618: 	my ($crole,$cqual)=split(/\&/,$_);
                   1619:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
                   1620:         if ($pr{'cr:d'}=~/$crole\&/) {
                   1621: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
                   1622:                return "refused:d:$crole&$cqual"; 
                   1623:             }
                   1624:         }
1.191     harris41 1625:     }
                   1626:     foreach (split('/',$courole)) {
1.21      www      1627: 	my ($crole,$cqual)=split(/\&/,$_);
                   1628:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
                   1629:         if ($pr{'cr:c'}=~/$crole\&/) {
                   1630: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
                   1631:                return "refused:c:$crole&$cqual"; 
                   1632:             }
                   1633:         }
1.191     harris41 1634:     }
1.12      www      1635:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   1636:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21      www      1637: 	        "rolesdef_$rolename=".
                   1638:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.12      www      1639:     return reply($command,$ENV{'user.home'});
                   1640:   } else {
                   1641:     return 'refused';
                   1642:   }
1.105     harris41 1643: }
                   1644: 
                   1645: # ---------------- Make a metadata query against the network of library servers
                   1646: 
                   1647: sub metadata_query {
1.116     harris41 1648:     my ($query,$custom,$customshow)=@_;
1.120     harris41 1649:     my %rhash;
1.123     harris41 1650:     for my $server (keys %libserv) {
1.118     harris41 1651: 	unless ($custom or $customshow) {
                   1652: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   1653: 	    $rhash{$server}=$reply;
                   1654: 	}
                   1655: 	else {
                   1656: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   1657: 			     &escape($custom).':'.&escape($customshow),
                   1658: 			     $server);
                   1659: 	    $rhash{$server}=$reply;
                   1660: 	}
1.112     harris41 1661:     }
1.118     harris41 1662:     return \%rhash;
1.12      www      1663: }
                   1664: 
                   1665: # ------------------------------------------------------------------ Plain Text
                   1666: 
                   1667: sub plaintext {
1.22      www      1668:     my $short=shift;
                   1669:     return $prp{$short};
1.12      www      1670: }
                   1671: 
                   1672: # ----------------------------------------------------------------- Assign Role
                   1673: 
                   1674: sub assignrole {
1.21      www      1675:     my ($udom,$uname,$url,$role,$end,$start)=@_;
                   1676:     my $mrole;
                   1677:     if ($role =~ /^cr\//) {
1.104     www      1678: 	unless (&allowed('ccr',$url)) {
                   1679:            &logthis('Refused custom assignrole: '.
                   1680:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   1681: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   1682:            return 'refused'; 
                   1683:         }
1.21      www      1684:         $mrole='cr';
                   1685:     } else {
1.82      www      1686:         my $cwosec=$url;
1.83      www      1687:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.104     www      1688:         unless (&allowed('c'.$role,$cwosec)) { 
                   1689:            &logthis('Refused assignrole: '.
                   1690:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   1691: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   1692:            return 'refused'; 
                   1693:         }
1.21      www      1694:         $mrole=$role;
                   1695:     }
                   1696:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   1697:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      1698:     if ($end) { $command.='_'.$end; }
1.21      www      1699:     if ($start) {
                   1700: 	if ($end) { 
1.81      www      1701:            $command.='_'.$start; 
1.21      www      1702:         } else {
1.81      www      1703:            $command.='_0_'.$start;
1.21      www      1704:         }
                   1705:     }
                   1706:     return &reply($command,&homeserver($uname,$udom));
1.169     harris41 1707: }
                   1708: 
                   1709: # -------------------------------------------------- Modify user authentication
1.197     www      1710: # Overrides without validation
                   1711: 
1.169     harris41 1712: sub modifyuserauth {
                   1713:     my ($udom,$uname,$umode,$upass)=@_;
                   1714:     my $uhome=&homeserver($uname,$udom);
1.197     www      1715:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   1716:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.169     harris41 1717:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'});  
                   1718:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   1719: 		     &escape($upass),$uhome);
1.197     www      1720:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                   1721:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   1722:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   1723:     &log($udom,,$uname,$uhome,
                   1724:         'Authentication changed by '.$ENV{'user.domain'}.', '.
                   1725:                                      $ENV{'user.name'}.', '.$umode.
                   1726:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 1727:     unless ($reply eq 'ok') {
1.197     www      1728:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 1729: 	return 'error: '.$reply;
                   1730:     }   
1.170     harris41 1731:     return 'ok';
1.80      www      1732: }
                   1733: 
1.81      www      1734: # --------------------------------------------------------------- Modify a user
1.80      www      1735: 
                   1736: 
1.81      www      1737: sub modifyuser {
1.196     www      1738:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   1739:         $forceid)=@_;
1.198     www      1740:     $udom=~s/\W//g;
                   1741:     $uname=~s/\W//g;
1.81      www      1742:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      1743:              $umode.', '.$first.', '.$middle.', '.
1.196     www      1744: 	     $last.', '.$gene.'(forceid: '.$forceid.') by '.
1.80      www      1745:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});  
                   1746:     my $uhome=&homeserver($uname,$udom);
                   1747: # ----------------------------------------------------------------- Create User
1.81      www      1748:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
1.80      www      1749:         my $unhome='';
                   1750: 	if ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
                   1751: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                   1752:         } else {
                   1753:             my $tryserver;
1.81      www      1754:             my $loadm=10000000;
1.80      www      1755:             foreach $tryserver (keys %libserv) {
                   1756: 	       if ($hostdom{$tryserver} eq $udom) {
                   1757:                   my $answer=reply('load',$tryserver);
                   1758:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   1759: 		      $loadm=$answer;
                   1760:                       $unhome=$tryserver;
                   1761:                   }
                   1762: 	       }
                   1763: 	    }
                   1764:         }
                   1765:         if (($unhome eq '') || ($unhome eq 'no_host')) {
                   1766: 	    return 'error: find home';
                   1767:         }
                   1768:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   1769:                          &escape($upass),$unhome);
                   1770: 	unless ($reply eq 'ok') {
                   1771:             return 'error: '.$reply;
                   1772:         }   
                   1773:         $uhome=&homeserver($uname,$udom);
                   1774:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
                   1775: 	    return 'error: verify home';
                   1776:         }
                   1777:     }
                   1778: # ---------------------------------------------------------------------- Add ID
                   1779:     if ($uid) {
                   1780:        $uid=~tr/A-Z/a-z/;
                   1781:        my %uidhash=&idrget($udom,$uname);
1.196     www      1782:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   1783:          && (!$forceid)) {
1.80      www      1784: 	  unless ($uid eq $uidhash{$uname}) {
                   1785: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
                   1786:           }
                   1787:        } else {
                   1788: 	  &idput($udom,($uname => $uid));
                   1789:        }
                   1790:     }
                   1791: # -------------------------------------------------------------- Add names, etc
1.134     albertel 1792:     my %names=&get('environment',
                   1793: 		   ['firstname','middlename','lastname','generation'],
                   1794: 		   $udom,$uname);
                   1795:     if ($first)  { $names{'firstname'}  = $first; }
                   1796:     if ($middle) { $names{'middlename'} = $middle; }
                   1797:     if ($last)   { $names{'lastname'}   = $last; }
                   1798:     if ($gene)   { $names{'generation'} = $gene; }
                   1799:     my $reply = &put('environment', \%names, $udom,$uname);
                   1800:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      1801:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      1802:              $umode.', '.$first.', '.$middle.', '.
                   1803: 	     $last.', '.$gene.' by '.
                   1804:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134     albertel 1805:     return 'ok';
1.80      www      1806: }
                   1807: 
1.81      www      1808: # -------------------------------------------------------------- Modify student
1.80      www      1809: 
1.81      www      1810: sub modifystudent {
                   1811:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.197     www      1812:         $end,$start,$forceid)=@_;
1.81      www      1813:     my $cid='';
                   1814:     unless ($cid=$ENV{'request.course.id'}) {
1.80      www      1815: 	return 'not_in_class';
                   1816:     }
                   1817: # --------------------------------------------------------------- Make the user
1.81      www      1818:     my $reply=&modifyuser
1.197     www      1819: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid);
1.80      www      1820:     unless ($reply eq 'ok') { return $reply; }
1.81      www      1821:     my $uhome=&homeserver($uname,$udom);
                   1822:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   1823: 	return 'error: no such user';
                   1824:     }
1.80      www      1825: # -------------------------------------------------- Add student to course list
1.160     www      1826:     $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1.81      www      1827: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
                   1828:                       &escape($uname.':'.$udom).'='.
                   1829:                       &escape($end.':'.$start),
                   1830: 	              $ENV{'course.'.$cid.'.home'});
                   1831:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   1832: 	return 'error: '.$reply;
                   1833:     }
1.80      www      1834: # ---------------------------------------------------- Add student role to user
1.83      www      1835:     my $uurl='/'.$cid;
1.81      www      1836:     $uurl=~s/\_/\//g;
                   1837:     if ($usec) {
                   1838: 	$uurl.='/'.$usec;
                   1839:     }
                   1840:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      1841: }
                   1842: 
1.84      www      1843: # ------------------------------------------------- Write to course preferences
                   1844: 
                   1845: sub writecoursepref {
                   1846:     my ($courseid,%prefs)=@_;
                   1847:     $courseid=~s/^\///;
                   1848:     $courseid=~s/\_/\//g;
                   1849:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   1850:     my $chome=homeserver($cnum,$cdomain);
                   1851:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   1852: 	return 'error: no such course';
                   1853:     }
                   1854:     my $cstring='';
1.191     harris41 1855:     foreach (keys %prefs) {
1.84      www      1856: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 1857:     }
1.84      www      1858:     $cstring=~s/\&$//;
                   1859:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   1860: }
                   1861: 
                   1862: # ---------------------------------------------------------- Make/modify course
                   1863: 
                   1864: sub createcourse {
                   1865:     my ($udom,$description,$url)=@_;
                   1866:     $url=&declutter($url);
                   1867:     my $cid='';
                   1868:     unless (&allowed('ccc',$ENV{'user.domain'})) {
                   1869:         return 'refused';
                   1870:     }
                   1871:     unless ($udom eq $ENV{'user.domain'}) {
                   1872:         return 'refused';
                   1873:     }
                   1874: # ------------------------------------------------------------------- Create ID
                   1875:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   1876:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   1877: # ----------------------------------------------- Make sure that does not exist
                   1878:    my $uhome=&homeserver($uname,$udom);
                   1879:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   1880:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   1881:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   1882:        $uhome=&homeserver($uname,$udom);       
                   1883:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   1884:            return 'error: unable to generate unique course-ID';
                   1885:        } 
                   1886:    }
                   1887: # ------------------------------------------------------------- Make the course
                   1888:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
                   1889:                       $ENV{'user.home'});
                   1890:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.160     www      1891:     $uhome=&homeserver($uname,$udom);
1.84      www      1892:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   1893: 	return 'error: no such course';
                   1894:     }
                   1895:     &writecoursepref($udom.'_'.$uname,
                   1896:                      ('description' => $description,
                   1897:                       'url'         => $url));
                   1898:     return '/'.$udom.'/'.$uname;
                   1899: }
                   1900: 
1.21      www      1901: # ---------------------------------------------------------- Assign Custom Role
                   1902: 
                   1903: sub assigncustomrole {
                   1904:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
                   1905:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
                   1906:                        $end,$start);
                   1907: }
                   1908: 
                   1909: # ----------------------------------------------------------------- Revoke Role
                   1910: 
                   1911: sub revokerole {
                   1912:     my ($udom,$uname,$url,$role)=@_;
                   1913:     my $now=time;
                   1914:     return &assignrole($udom,$uname,$url,$role,$now);
                   1915: }
                   1916: 
                   1917: # ---------------------------------------------------------- Revoke Custom Role
                   1918: 
                   1919: sub revokecustomrole {
                   1920:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
                   1921:     my $now=time;
                   1922:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
1.17      www      1923: }
                   1924: 
                   1925: # ------------------------------------------------------------ Directory lister
                   1926: 
                   1927: sub dirlist {
                   1928:     my $uri=shift;
1.18      www      1929:     $uri=~s/^\///;
                   1930:     $uri=~s/\/$//;
1.19      www      1931:     my ($res,$udom,$uname,@rest)=split(/\//,$uri);
                   1932:     if ($udom) {
                   1933:      if ($uname) {
                   1934:        my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/'.$uri,
                   1935:                       homeserver($uname,$udom));
                   1936:        return split(/:/,$listing);
                   1937:      } else {
                   1938:        my $tryserver;
                   1939:        my %allusers=();
                   1940:        foreach $tryserver (keys %libserv) {
                   1941: 	  if ($hostdom{$tryserver} eq $udom) {
                   1942:              my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.$udom,
                   1943: 			       $tryserver);
                   1944:              if (($listing ne 'no_such_dir') && ($listing ne 'empty')
                   1945:               && ($listing ne 'con_lost')) {
1.191     harris41 1946:                 foreach (split(/:/,$listing)) {
1.19      www      1947:                   my ($entry,@stat)=split(/&/,$_);
                   1948:                   $allusers{$entry}=1;
1.191     harris41 1949:                 }
1.19      www      1950:              }
                   1951: 	  }
                   1952:        }
                   1953:        my $alluserstr='';
1.191     harris41 1954:        foreach (sort keys %allusers) {
1.19      www      1955:            $alluserstr.=$_.'&user:';
1.191     harris41 1956:        }
1.19      www      1957:        $alluserstr=~s/:$//;
                   1958:        return split(/:/,$alluserstr);
                   1959:      } 
                   1960:    } else {
                   1961:        my $tryserver;
                   1962:        my %alldom=();
                   1963:        foreach $tryserver (keys %libserv) {
                   1964: 	   $alldom{$hostdom{$tryserver}}=1;
                   1965:        }
                   1966:        my $alldomstr='';
1.191     harris41 1967:        foreach (sort keys %alldom) {
1.19      www      1968:           $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
1.191     harris41 1969:        }
1.19      www      1970:        $alldomstr=~s/:$//;
                   1971:        return split(/:/,$alldomstr);       
                   1972:    }
1.26      www      1973: }
                   1974: 
                   1975: # -------------------------------------------------------- Value of a Condition
                   1976: 
1.40      www      1977: sub directcondval {
                   1978:     my $number=shift;
                   1979:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
                   1980:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
                   1981:     } else {
                   1982:        return 2;
                   1983:     }
                   1984: }
                   1985: 
1.26      www      1986: sub condval {
                   1987:     my $condidx=shift;
                   1988:     my $result=0;
1.54      www      1989:     my $allpathcond='';
1.191     harris41 1990:     foreach (split(/\|/,$condidx)) {
1.54      www      1991:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
                   1992: 	   $allpathcond.=
                   1993:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
                   1994:        }
1.191     harris41 1995:     }
1.54      www      1996:     $allpathcond=~s/\|$//;
1.33      www      1997:     if ($ENV{'request.course.id'}) {
1.54      www      1998:        if ($allpathcond) {
1.26      www      1999:           my $operand='|';
                   2000: 	  my @stack;
1.191     harris41 2001:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      2002:               if ($_ eq '(') {
                   2003:                  push @stack,($operand,$result)
                   2004:               } elsif ($_ eq ')') {
                   2005:                   my $before=pop @stack;
                   2006: 		  if (pop @stack eq '&') {
                   2007: 		      $result=$result>$before?$before:$result;
                   2008:                   } else {
                   2009:                       $result=$result>$before?$result:$before;
                   2010:                   }
                   2011:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   2012:                   $operand=$_;
                   2013:               } else {
1.40      www      2014:                   my $new=directcondval($_);
1.26      www      2015:                   if ($operand eq '&') {
                   2016:                      $result=$result>$new?$new:$result;
                   2017:                   } else {
                   2018:                      $result=$result>$new?$result:$new;
1.191     harris41 2019:                   }
1.26      www      2020:               }
1.191     harris41 2021:           }
1.26      www      2022:        }
                   2023:     }
                   2024:     return $result;
1.28      www      2025: }
                   2026: 
1.200   ! www      2027: # --------------------------------------------------- Course Resourcedata Query
        !          2028: 
        !          2029: sub courseresdata {
        !          2030:     my ($coursenum,$coursedomain,@which)=@_;
        !          2031:     my $coursehom=&homeserver($coursenum,$coursedomain);
        !          2032:     my $hashid=$coursenum.':'.$coursedomain;
        !          2033:     unless (defined($courseresdatacache{$hashid.'.time'})) {
        !          2034: 	unless (time-$courseresdatacache{$hashid.'.time'}<300) {
        !          2035:            my $coursehom=&homeserver($coursenum,$coursedomain);
        !          2036:            if ($coursehom) {
        !          2037:               my $dumpreply=&reply('dump:'.$coursedomain.':'.$coursenum.
        !          2038: 			     ':resourcedata:.',$coursehom);
        !          2039: 	      unless ($dumpreply=~/^error\:/) {
        !          2040: 	         $courseresdatacache{$hashid.'.time'}=time;
        !          2041:                  $courseresdatacache{$hashid}=$dumpreply;
        !          2042: 	     }
        !          2043: 	  }
        !          2044:        }
        !          2045:     }
        !          2046:    my @pairs=split(/\&/,$courseresdatacache{$hashid});
        !          2047:    my %returnhash=();
        !          2048:    foreach (@pairs) {
        !          2049:       my ($key,$value)=split(/=/,$_);
        !          2050:       $returnhash{unescape($key)}=unescape($value);
        !          2051:    }
        !          2052:     my $item;
        !          2053:    foreach $item (@which) {
        !          2054:        if ($returnhash{$item}) { return $returnhash{$item}; }
        !          2055:    }
        !          2056:    return '';
        !          2057: }
        !          2058: 
1.28      www      2059: # --------------------------------------------------------- Value of a Variable
                   2060: 
1.58      www      2061: sub EXT {
1.147     www      2062:     my ($varname,$symbparm)=@_;
1.68      www      2063:     unless ($varname) { return ''; }
1.48      www      2064:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   2065:     my $rest;
                   2066:     if ($therest[0]) {
                   2067:        $rest=join('.',@therest);
                   2068:     } else {
                   2069:        $rest='';
                   2070:     }
1.57      www      2071:     my $qualifierrest=$qualifier;
                   2072:     if ($rest) { $qualifierrest.='.'.$rest; }
                   2073:     my $spacequalifierrest=$space;
                   2074:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      2075:     if ($realm eq 'user') {
1.48      www      2076: # --------------------------------------------------------------- user.resource
                   2077: 	if ($space eq 'resource') {
1.122     albertel 2078: 	    my %restored=&restore();
1.57      www      2079:             return $restored{$qualifierrest};
1.48      www      2080: # ----------------------------------------------------------------- user.access
                   2081:         } elsif ($space eq 'access') {
                   2082:             return &allowed($qualifier,$rest);
                   2083: # ------------------------------------------ user.preferences, user.environment
                   2084:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.57      www      2085:             return $ENV{join('.',('environment',$qualifierrest))};
1.48      www      2086: # ----------------------------------------------------------------- user.course
                   2087:         } elsif ($space eq 'course') {
                   2088:             return $ENV{join('.',('request.course',$qualifier))};
                   2089: # ------------------------------------------------------------------- user.role
                   2090:         } elsif ($space eq 'role') {
                   2091:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   2092:             if ($qualifier eq 'value') {
                   2093: 		return $role;
                   2094:             } elsif ($qualifier eq 'extent') {
                   2095:                 return $where;
                   2096:             }
                   2097: # ----------------------------------------------------------------- user.domain
                   2098:         } elsif ($space eq 'domain') {
                   2099:             return $ENV{'user.domain'};
                   2100: # ------------------------------------------------------------------- user.name
                   2101:         } elsif ($space eq 'name') {
                   2102:             return $ENV{'user.name'};
                   2103: # ---------------------------------------------------- Any other user namespace
1.29      www      2104:         } else {
1.48      www      2105:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
1.131     albertel 2106:             my %reply=&get($space,[$item]);
1.48      www      2107:             return $reply{$item};
                   2108:         }
                   2109:     } elsif ($realm eq 'request') {
                   2110: # ------------------------------------------------------------- request.browser
                   2111:         if ($space eq 'browser') {
                   2112: 	    return $ENV{'browser.'.$qualifier};
1.57      www      2113: # ------------------------------------------------------------ request.filename
                   2114:         } else {
                   2115:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      2116:         }
1.28      www      2117:     } elsif ($realm eq 'course') {
1.48      www      2118: # ---------------------------------------------------------- course.description
1.127     ng       2119:         return $ENV{'course.'.$ENV{'request.course.id'}.'.'.
1.57      www      2120:                               $spacequalifierrest};
                   2121:     } elsif ($realm eq 'resource') {
1.127     ng       2122:        if ($ENV{'request.course.id'}) {
1.165     www      2123: 
                   2124: #	   print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
                   2125: 
                   2126: 
1.60      www      2127: # ----------------------------------------------------- Cascading lookup scheme
1.147     www      2128:          my $symbp;
                   2129:          if ($symbparm) {
                   2130:             $symbp=$symbparm;
                   2131: 	 } else {
                   2132:             $symbp=&symbread();
                   2133:          }            
1.127     ng       2134:          my $mapp=(split(/\_\_\_/,$symbp))[0];
1.69      www      2135: 
1.127     ng       2136:          my $symbparm=$symbp.'.'.$spacequalifierrest;
                   2137:          my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.69      www      2138: 
1.127     ng       2139:          my $seclevel=
1.69      www      2140:             $ENV{'request.course.id'}.'.['.
                   2141: 		$ENV{'request.course.sec'}.'].'.$spacequalifierrest;
1.127     ng       2142:          my $seclevelr=
1.69      www      2143:             $ENV{'request.course.id'}.'.['.
                   2144: 		$ENV{'request.course.sec'}.'].'.$symbparm;
1.127     ng       2145:          my $seclevelm=
1.69      www      2146:             $ENV{'request.course.id'}.'.['.
                   2147: 		$ENV{'request.course.sec'}.'].'.$mapparm;
                   2148: 
1.127     ng       2149:          my $courselevel=
1.60      www      2150:             $ENV{'request.course.id'}.'.'.$spacequalifierrest;
1.127     ng       2151:          my $courselevelr=
1.69      www      2152:             $ENV{'request.course.id'}.'.'.$symbparm;
1.127     ng       2153:          my $courselevelm=
1.69      www      2154:             $ENV{'request.course.id'}.'.'.$mapparm;
                   2155: 
1.60      www      2156: # ----------------------------------------------------------- first, check user
1.127     ng       2157:          my %resourcedata=get('resourcedata',
1.131     albertel 2158:                            [$courselevelr,$courselevelm,$courselevel]);
1.127     ng       2159:          if (($resourcedata{$courselevelr}!~/^error\:/) &&
                   2160:              ($resourcedata{$courselevelr}!~/^con_lost/)) {
1.69      www      2161: 
1.127     ng       2162:          if ($resourcedata{$courselevelr}) { 
                   2163:             return $resourcedata{$courselevelr}; }
                   2164:          if ($resourcedata{$courselevelm}) { 
                   2165:             return $resourcedata{$courselevelm}; }
                   2166:          if ($resourcedata{$courselevel}) { return $resourcedata{$courselevel}; }
1.69      www      2167: 
1.94      www      2168:       } else {
                   2169: 	  if ($resourcedata{$courselevelr}!~/No such file/) {
                   2170: 	    &logthis("<font color=blue>WARNING:".
                   2171: 		   " Trying to get resource data for ".$ENV{'user.name'}." at "
                   2172:                    .$ENV{'user.domain'}.": ".$resourcedata{$courselevelr}.
                   2173:                  "</font>");
                   2174: 	  }
1.63      www      2175:       }
1.95      www      2176: 
1.60      www      2177: # -------------------------------------------------------- second, check course
1.96      www      2178: 
1.200   ! www      2179:         my $coursereply=&courseresdata(
        !          2180:                         $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
        !          2181:                         $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
        !          2182:                         ($seclevelr,$seclevelm,$seclevel,
        !          2183:                          $courselevelr,$courselevelm,$courselevel));
        !          2184:         if ($coursereply) { return $coursereply; }
        !          2185: 
1.60      www      2186: # ------------------------------------------------------ third, check map parms
1.65      www      2187:        my %parmhash=();
                   2188:        my $thisparm='';       
                   2189:        if (tie(%parmhash,'GDBM_File',
                   2190:           $ENV{'request.course.fn'}.'_parms.db',&GDBM_READER,0640)) {
                   2191:            $thisparm=$parmhash{$symbparm};
                   2192: 	   untie(%parmhash);
1.60      www      2193:        }
1.65      www      2194:        if ($thisparm) { return $thisparm; }
1.60      www      2195:      }
                   2196:      
                   2197: # --------------------------------------------- last, look in resource metadata
1.71      www      2198: 
1.78      www      2199:       $spacequalifierrest=~s/\./\_/;
1.71      www      2200:       my $metadata=&metadata($ENV{'request.filename'},$spacequalifierrest);
                   2201:       if ($metadata) { return $metadata; }
1.78      www      2202:       $metadata=&metadata($ENV{'request.filename'},
                   2203:                                          'parameter_'.$spacequalifierrest);
                   2204:       if ($metadata) { return $metadata; }
1.142     www      2205: 
1.145     www      2206: # ------------------------------------------------------------------ Cascade up
                   2207: 
                   2208:       unless ($space eq '0') {
1.165     www      2209:           my ($part,$id)=split(/\_/,$space);
1.145     www      2210:           if ($id) {
1.147     www      2211: 	      my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
                   2212:                                    $symbparm);
1.145     www      2213:               if ($partgeneral) { return $partgeneral; }
                   2214:           } else {
1.147     www      2215:               my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
                   2216:                                        $symbparm);
1.145     www      2217:               if ($resourcegeneral) { return $resourcegeneral; }
                   2218:           }
                   2219:       }
1.71      www      2220: 
1.48      www      2221: # ---------------------------------------------------- Any other user namespace
                   2222:     } elsif ($realm eq 'environment') {
                   2223: # ----------------------------------------------------------------- environment
1.127     ng       2224:         return $ENV{'environment.'.$spacequalifierrest};
1.28      www      2225:     } elsif ($realm eq 'system') {
1.48      www      2226: # ----------------------------------------------------------------- system.time
                   2227: 	if ($space eq 'time') {
                   2228: 	    return time;
                   2229:         }
1.28      www      2230:     }
1.48      www      2231:     return '';
1.61      www      2232: }
                   2233: 
1.71      www      2234: # ---------------------------------------------------------------- Get metadata
                   2235: 
                   2236: sub metadata {
1.176     www      2237:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.78      www      2238: 
1.71      www      2239:     $uri=&declutter($uri);
1.73      www      2240:     my $filename=$uri;
                   2241:     $uri=~s/\.meta$//;
1.172     www      2242: #
                   2243: # Is the metadata already cached?
1.177     www      2244: # Look at timestamp of caching
1.172     www      2245: # Everything is cached by the main uri, libraries are never directly cached
                   2246: #
1.174     www      2247:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600) {
1.172     www      2248: #
                   2249: # Is this a recursive call for a library?
                   2250: #
1.171     www      2251:         if ($liburi) {
                   2252: 	    $liburi=&declutter($liburi);
                   2253:             $filename=$liburi;
                   2254:         }
1.140     www      2255:         my %metathesekeys=();
1.73      www      2256:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
                   2257: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
1.71      www      2258:         my $parser=HTML::TokeParser->new(\$metastring);
                   2259:         my $token;
1.140     www      2260:         undef %metathesekeys;
1.71      www      2261:         while ($token=$parser->get_token) {
                   2262:            if ($token->[0] eq 'S') {
1.135     www      2263: 	     if (defined($token->[2]->{'package'})) {
1.172     www      2264: #
                   2265: # This is a package - get package info
                   2266: #
1.136     www      2267: 	      my $package=$token->[2]->{'package'};
                   2268: 	      my $keyroot='';
1.172     www      2269:               if ($prefix) {
                   2270: 		  $keyroot.='_'.$prefix;
                   2271:               } else {
                   2272:                 if (defined($token->[2]->{'part'})) { 
                   2273:                    $keyroot.='_'.$token->[2]->{'part'}; 
                   2274: 	        }
1.136     www      2275: 	      }
                   2276:               if (defined($token->[2]->{'id'})) { 
1.165     www      2277:                  $keyroot.='_'.$token->[2]->{'id'}; 
1.136     www      2278: 	      }
                   2279:               if ($metacache{$uri.':packages'}) {
                   2280:                  $metacache{$uri.':packages'}.=','.$package.$keyroot;
                   2281:               } else {
                   2282:                  $metacache{$uri.':packages'}=$package.$keyroot;
                   2283: 	      }
1.191     harris41 2284:               foreach (keys %packagetab) {
1.137     www      2285: 		  if ($_=~/^$package\&/) {
                   2286: 		      my ($pack,$name,$subp)=split(/\&/,$_);
1.139     www      2287:                       my $value=$packagetab{$_};
1.144     www      2288: 		      my $part=$keyroot;
                   2289:                       $part=~s/^\_//;
1.139     www      2290:                       if ($subp eq 'display') {
                   2291: 			  $value.=' [Part: '.$part.']';
                   2292:                       }
                   2293:                       my $unikey='parameter'.$keyroot.'_'.$name;
1.140     www      2294:                       $metathesekeys{$unikey}=1;
1.144     www      2295:                       $metacache{$uri.':'.$unikey.'.part'}=$part;
1.141     www      2296:                       unless 
                   2297:                        (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
                   2298:                          $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
                   2299: 		      }
1.137     www      2300:                   }
1.191     harris41 2301:               }
1.135     www      2302:              } else {
1.172     www      2303: #
                   2304: # This is not a package - some other kind of start tag
                   2305: # 
1.175     www      2306:               my $entry=$token->[1];
1.176     www      2307:               my $unikey;
                   2308:               if ($entry eq 'import') {
                   2309:                  $unikey='';
                   2310:               } else {
                   2311:                  $unikey=$entry;
                   2312: 	      }
1.172     www      2313:               if ($prefix) {
1.176     www      2314: 		  $unikey.=$prefix;
1.172     www      2315:               } else {
                   2316:                 if (defined($token->[2]->{'part'})) { 
                   2317:                    $unikey.='_'.$token->[2]->{'part'}; 
                   2318: 	        }
1.136     www      2319: 	      }
                   2320:               if (defined($token->[2]->{'id'})) { 
1.165     www      2321:                  $unikey.='_'.$token->[2]->{'id'}; 
1.71      www      2322: 	      }
1.175     www      2323: 
                   2324:              if ($entry eq 'import') {
                   2325: #
                   2326: # Importing a library here
1.176     www      2327: #                
                   2328: 		 if (defined($depthcount)) { $depthcount++; } else 
                   2329:                                            { $depthcount=0; }
                   2330:                  if ($depthcount<20) {
1.191     harris41 2331: 		     foreach (split(/\,/,&metadata($uri,'keys',
                   2332:                                   $parser->get_text('/import'),$unikey,
                   2333:                                   $depthcount))) {
1.177     www      2334:                          $metathesekeys{$_}=1;
1.191     harris41 2335: 		     }
1.176     www      2336: 		 }
1.175     www      2337:              } else { 
                   2338: 
1.72      www      2339:               if (defined($token->[2]->{'name'})) { 
1.71      www      2340:                  $unikey.='_'.$token->[2]->{'name'}; 
                   2341: 	      }
1.140     www      2342:               $metathesekeys{$unikey}=1;
1.191     harris41 2343:               foreach (@{$token->[3]}) {
1.71      www      2344: 		  $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.191     harris41 2345:               }
1.78      www      2346:               unless (
                   2347:                  $metacache{$uri.':'.$unikey}=$parser->get_text('/'.$entry)
                   2348: 		      ) { $metacache{$uri.':'.$unikey}=
                   2349: 			      $metacache{$uri.':'.$unikey.'.default'};
                   2350: 		      }
1.172     www      2351: # end of not-a-package not-a-library import
1.175     www      2352: 	   }
1.172     www      2353: # end of not-a-package start tag
                   2354: 	  }
                   2355: # the next is the end of "start tag"
1.140     www      2356: 	 }
1.71      www      2357:        }
1.140     www      2358:        $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
1.174     www      2359:        $metacache{$uri.':cachedtimestamp'}=time;
1.177     www      2360: # this is the end of "was not already recently cached
1.71      www      2361:     }
                   2362:     return $metacache{$uri.':'.$what};
                   2363: }
                   2364: 
1.31      www      2365: # ------------------------------------------------- Update symbolic store links
                   2366: 
                   2367: sub symblist {
                   2368:     my ($mapname,%newhash)=@_;
                   2369:     $mapname=declutter($mapname);
                   2370:     my %hash;
                   2371:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   2372:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
                   2373:                       &GDBM_WRCREAT,0640)) {
1.191     harris41 2374: 	    foreach (keys %newhash) {
1.31      www      2375:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
1.191     harris41 2376:             }
1.31      www      2377:             if (untie(%hash)) {
                   2378: 		return 'ok';
                   2379:             }
                   2380:         }
                   2381:     }
                   2382:     return 'error';
                   2383: }
                   2384: 
                   2385: # ------------------------------------------------------ Return symb list entry
                   2386: 
                   2387: sub symbread {
1.44      www      2388:     my $thisfn=shift;
                   2389:     unless ($thisfn) {
1.179     www      2390:         if ($ENV{'request.symb'}) { return $ENV{'request.symb'}; }
1.44      www      2391: 	$thisfn=$ENV{'request.filename'};
                   2392:     }
                   2393:     $thisfn=declutter($thisfn);
1.31      www      2394:     my %hash;
1.37      www      2395:     my %bighash;
                   2396:     my $syval='';
1.45      www      2397:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31      www      2398:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
                   2399:                       &GDBM_READER,0640)) {
                   2400: 	    $syval=$hash{$thisfn};
1.37      www      2401:             untie(%hash);
                   2402:         }
                   2403: # ---------------------------------------------------------- There was an entry
                   2404:         if ($syval) {
                   2405:            unless ($syval=~/\_\d+$/) {
                   2406: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44      www      2407:                   &appenv('request.ambiguous' => $thisfn);
1.37      www      2408:                   return '';
                   2409:                }    
                   2410:                $syval.=$1;
                   2411: 	   }
                   2412:         } else {
                   2413: # ------------------------------------------------------- Was not in symb table
                   2414:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                   2415:                             &GDBM_READER,0640)) {
                   2416: # ---------------------------------------------- Get ID(s) for current resource
                   2417:               my $ids=$bighash{'ids_/res/'.$thisfn};
1.65      www      2418:               unless ($ids) { 
                   2419:                  $ids=$bighash{'ids_/'.$thisfn};
                   2420:               }
1.37      www      2421:               if ($ids) {
                   2422: # ------------------------------------------------------------------- Has ID(s)
                   2423:                  my @possibilities=split(/\,/,$ids);
1.39      www      2424:                  if ($#possibilities==0) {
                   2425: # ----------------------------------------------- There is only one possibility
1.37      www      2426: 		     my ($mapid,$resid)=split(/\./,$ids);
                   2427:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
                   2428:                  } else {
1.39      www      2429: # ------------------------------------------ There is more than one possibility
                   2430:                      my $realpossible=0;
1.191     harris41 2431:                      foreach (@possibilities) {
1.39      www      2432: 			 my $file=$bighash{'src_'.$_};
                   2433:                          if (&allowed('bre',$file)) {
                   2434:          		    my ($mapid,$resid)=split(/\./,$_);
                   2435:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   2436: 				$realpossible++;
                   2437:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   2438:                                        '___'.$resid;
                   2439:                             }
                   2440: 			 }
1.191     harris41 2441:                      }
1.39      www      2442: 		     if ($realpossible!=1) { $syval=''; }
1.37      www      2443:                  }
                   2444: 	      }
                   2445:               untie(%bighash)
                   2446:            } 
1.31      www      2447:         }
1.62      www      2448:         if ($syval) {
                   2449:            return $syval.'___'.$thisfn; 
                   2450:         }
1.31      www      2451:     }
1.44      www      2452:     &appenv('request.ambiguous' => $thisfn);
1.31      www      2453:     return '';
                   2454: }
                   2455: 
                   2456: # ---------------------------------------------------------- Return random seed
                   2457: 
1.32      www      2458: sub numval {
                   2459:     my $txt=shift;
                   2460:     $txt=~tr/A-J/0-9/;
                   2461:     $txt=~tr/a-j/0-9/;
                   2462:     $txt=~tr/K-T/0-9/;
                   2463:     $txt=~tr/k-t/0-9/;
                   2464:     $txt=~tr/U-Z/0-5/;
                   2465:     $txt=~tr/u-z/0-5/;
                   2466:     $txt=~s/\D//g;
                   2467:     return int($txt);
                   2468: }    
                   2469: 
1.31      www      2470: sub rndseed {
1.155     albertel 2471:     my ($symb,$courseid,$domain,$username)=@_;
                   2472:     if (!$symb) {
                   2473:       unless ($symb=&symbread()) { return time; }
                   2474:     }
                   2475:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
                   2476:     if (!$domain) {$domain=$ENV{'user.domain'};}
                   2477:     if (!$username) {$username=$ENV{'user.name'};}
                   2478:     {
1.98      albertel 2479:       use integer;
                   2480:       my $symbchck=unpack("%32C*",$symb) << 27;
1.100     albertel 2481:       my $symbseed=numval($symb) << 22;
1.155     albertel 2482:       my $namechck=unpack("%32C*",$username) << 17;
                   2483:       my $nameseed=numval($username) << 12;
                   2484:       my $domainseed=unpack("%32C*",$domain) << 7;
                   2485:       my $courseseed=unpack("%32C*",$courseid);
1.98      albertel 2486:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.99      albertel 2487:       #uncommenting these lines can break things!
                   2488:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   2489:       #&Apache::lonxml::debug("rndseed :$num:$symb");
1.98      albertel 2490:       return $num;
                   2491:     }
1.36      albertel 2492: }
                   2493: 
1.76      www      2494: sub ireceipt {
                   2495:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
                   2496:     my $cuname=unpack("%32C*",$funame);
                   2497:     my $cudom=unpack("%32C*",$fudom);
                   2498:     my $cucourseid=unpack("%32C*",$fucourseid);
                   2499:     my $cusymb=unpack("%32C*",$fusymb);
1.77      www      2500:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76      www      2501:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
                   2502:            ($cunique%$cuname+
                   2503:             $cunique%$cudom+
                   2504:             $cusymb%$cuname+
                   2505:             $cusymb%$cudom+
                   2506:             $cucourseid%$cuname+
                   2507:             $cucourseid%$cudom);
                   2508: }
                   2509: 
                   2510: sub receipt {
                   2511:     return &ireceipt($ENV{'user.name'},$ENV{'user.domain'},
                   2512:                      $ENV{'request.course.id'},&symbread());
                   2513: }
                   2514:   
1.36      albertel 2515: # ------------------------------------------------------------ Serves up a file
                   2516: # returns either the contents of the file or a -1
                   2517: sub getfile {
                   2518:   my $file=shift;
1.37      www      2519:   &repcopy($file);
1.36      albertel 2520:   if (! -e $file ) { return -1; };
                   2521:   my $fh=Apache::File->new($file);
                   2522:   my $a='';
                   2523:   while (<$fh>) { $a .=$_; }
                   2524:   return $a
                   2525: }
                   2526: 
                   2527: sub filelocation {
                   2528:   my ($dir,$file) = @_;
                   2529:   my $location;
                   2530:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59      albertel 2531:   if ($file=~m:^/~:) { # is a contruction space reference
                   2532:     $location = $file;
                   2533:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.36      albertel 2534:   } else {
1.59      albertel 2535:     $file=~s/^$perlvar{'lonDocRoot'}//;
                   2536:     $file=~s:^/*res::;
                   2537:     if ( !( $file =~ m:^/:) ) {
                   2538:       $location = $dir. '/'.$file;
                   2539:     } else {
                   2540:       $location = '/home/httpd/html/res'.$file;
                   2541:     }
1.36      albertel 2542:   }
                   2543:   $location=~s://+:/:g; # remove duplicate /
1.46      www      2544:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   2545:   return $location;
                   2546: }
1.36      albertel 2547: 
1.46      www      2548: sub hreflocation {
                   2549:     my ($dir,$file)=@_;
1.191     harris41 2550:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46      www      2551:        my $finalpath=filelocation($dir,$file);
                   2552:        $finalpath=~s/^\/home\/httpd\/html//;
                   2553:        return $finalpath;
                   2554:     } else {
                   2555:        return $file;
                   2556:     }
1.31      www      2557: }
                   2558: 
                   2559: # ------------------------------------------------------------- Declutters URLs
                   2560: 
                   2561: sub declutter {
                   2562:     my $thisfn=shift;
                   2563:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
                   2564:     $thisfn=~s/^\///;
                   2565:     $thisfn=~s/^res\///;
                   2566:     return $thisfn;
1.12      www      2567: }
                   2568: 
                   2569: # -------------------------------------------------------- Escape Special Chars
                   2570: 
                   2571: sub escape {
                   2572:     my $str=shift;
                   2573:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   2574:     return $str;
                   2575: }
                   2576: 
                   2577: # ----------------------------------------------------- Un-Escape Special Chars
                   2578: 
                   2579: sub unescape {
                   2580:     my $str=shift;
                   2581:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2582:     return $str;
                   2583: }
1.11      www      2584: 
1.1       albertel 2585: # ================================================================ Main Program
                   2586: 
1.184     www      2587: sub goodbye {
                   2588:    &flushcourselogs();
                   2589:    &logthis("Shutting down");
                   2590: }
                   2591: 
1.179     www      2592: BEGIN {
1.1       albertel 2593: # ------------------------------------------------------------ Read access.conf
1.195     www      2594:     unless ($readit) {
1.1       albertel 2595: {
                   2596:     my $config=Apache::File->new("/etc/httpd/conf/access.conf");
                   2597: 
                   2598:     while (my $configline=<$config>) {
                   2599:         if ($configline =~ /PerlSetVar/) {
                   2600: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      2601:            chomp($varvalue);
1.1       albertel 2602:            $perlvar{$varname}=$varvalue;
                   2603:         }
                   2604:     }
                   2605: }
                   2606: 
                   2607: # ------------------------------------------------------------- Read hosts file
                   2608: {
                   2609:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
                   2610: 
                   2611:     while (my $configline=<$config>) {
1.154     www      2612:        chomp($configline);
1.1       albertel 2613:        my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                   2614:        $hostname{$id}=$name;
                   2615:        $hostdom{$id}=$domain;
1.150     www      2616:        $hostip{$id}=$ip;
1.1       albertel 2617:        if ($role eq 'library') { $libserv{$id}=$name; }
                   2618:     }
                   2619: }
                   2620: 
                   2621: # ------------------------------------------------------ Read spare server file
                   2622: {
                   2623:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
                   2624: 
                   2625:     while (my $configline=<$config>) {
                   2626:        chomp($configline);
                   2627:        if (($configline) && ($configline ne $perlvar{'lonHostID'})) {
                   2628:           $spareid{$configline}=1;
                   2629:        }
                   2630:     }
                   2631: }
1.11      www      2632: # ------------------------------------------------------------ Read permissions
                   2633: {
                   2634:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
                   2635: 
                   2636:     while (my $configline=<$config>) {
                   2637:        chomp($configline);
1.160     www      2638:       if ($configline) {
1.11      www      2639:        my ($role,$perm)=split(/ /,$configline);
                   2640:        if ($perm ne '') { $pr{$role}=$perm; }
1.160     www      2641:       }
1.11      www      2642:     }
                   2643: }
                   2644: 
                   2645: # -------------------------------------------- Read plain texts for permissions
                   2646: {
                   2647:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
                   2648: 
                   2649:     while (my $configline=<$config>) {
                   2650:        chomp($configline);
1.160     www      2651:       if ($configline) {
1.11      www      2652:        my ($short,$plain)=split(/:/,$configline);
                   2653:        if ($plain ne '') { $prp{$short}=$plain; }
1.160     www      2654:       }
1.135     www      2655:     }
                   2656: }
                   2657: 
                   2658: # ---------------------------------------------------------- Read package table
                   2659: {
                   2660:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
                   2661: 
                   2662:     while (my $configline=<$config>) {
                   2663:        chomp($configline);
                   2664:        my ($short,$plain)=split(/:/,$configline);
1.143     www      2665:        my ($pack,$name)=split(/\&/,$short);
                   2666:        if ($plain ne '') {
                   2667:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   2668:           $packagetab{$short}=$plain; 
1.25      www      2669:        }
1.11      www      2670:     }
                   2671: }
                   2672: 
1.71      www      2673: %metacache=();
1.185     www      2674: 
                   2675: $processmarker=$$.'_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      2676: $dumpcount=0;
1.22      www      2677: 
1.163     harris41 2678: &logtouch();
1.12      www      2679: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      2680: $readit=1;
                   2681: }
1.1       albertel 2682: }
1.179     www      2683: 
1.1       albertel 2684: 1;
1.191     harris41 2685: __END__
                   2686: 
                   2687: =head1 NAME
                   2688: 
                   2689: Apache::lonnet - TCP networking package
                   2690: 
                   2691: =head1 SYNOPSIS
                   2692: 
                   2693: Invoked by other LON-CAPA modules.
                   2694: 
                   2695:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   2696: 
                   2697: =head1 INTRODUCTION
                   2698: 
                   2699: This module provides subroutines which interact with the
                   2700: lonc/lond (TCP) network layer of LON-CAPA.
                   2701: 
                   2702: This is part of the LearningOnline Network with CAPA project
                   2703: described at http://www.lon-capa.org.
                   2704: 
                   2705: =head1 HANDLER SUBROUTINE
                   2706: 
                   2707: There is no handler routine for this module.
                   2708: 
                   2709: =head1 OTHER SUBROUTINES
                   2710: 
                   2711: =over 4
                   2712: 
                   2713: =item *
                   2714: 
                   2715: logtouch() : make sure the logfile, lonnet.log, exists
                   2716: 
                   2717: =item *
                   2718: 
                   2719: logthis() : append message to lonnet.log
                   2720: 
                   2721: =item *
                   2722: 
                   2723: logperm() : append a permanent message to lonnet.perm.log
                   2724: 
                   2725: =item *
                   2726: 
                   2727: subreply() : non-critical communication, called by &reply
                   2728: 
                   2729: =item *
                   2730: 
                   2731: reply() : makes two attempts to pass message; logs refusals and rejections
                   2732: 
                   2733: =item *
                   2734: 
                   2735: reconlonc() : tries to reconnect lonc client processes.
                   2736: 
                   2737: =item *
                   2738: 
                   2739: critical() : passes a critical message to another server; if cannot get
                   2740: through then place message in connection buffer
                   2741: 
                   2742: =item *
                   2743: 
                   2744: appenv(%hash) : read in current user environment, append new environment
                   2745: values to make new user environment
                   2746: 
                   2747: =item *
                   2748: 
                   2749: delenv($varname) : read in current user environment, remove all values
                   2750: beginning with $varname, write new user environment (note: flock is used
                   2751: to prevent conflicting shared read/writes with file)
                   2752: 
                   2753: =item *
                   2754: 
                   2755: spareserver() : find server with least workload from spare.tab
                   2756: 
                   2757: =item *
                   2758: 
                   2759: queryauthenticate($uname,$udom) : try to determine user's current
                   2760: authentication scheme
                   2761: 
                   2762: =item *
                   2763: 
                   2764: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
                   2765: servers (first use the current one)
                   2766: 
                   2767: =item *
                   2768: 
                   2769: homeserver($uname,$udom) : find the homebase for a user from domain's lib
                   2770: servers
                   2771: 
                   2772: =item *
                   2773: 
                   2774: idget($udom,@ids) : find the usernames behind a list of IDs (returns hash:
                   2775: id=>name,id=>name)
                   2776: 
                   2777: =item *
                   2778: 
                   2779: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
                   2780: name=>id,name=>id)
                   2781: 
                   2782: =item *
                   2783: 
                   2784: idput($udom,%ids) : store away a list of names and associated IDs
                   2785: 
                   2786: =item *
                   2787: 
                   2788: usection($domain,$user,$courseid) : output of section name/number or '' for
                   2789: "not in course" and '-1' for "no section"
                   2790: 
                   2791: =item *
                   2792: 
                   2793: userenvironment($domain,$user,$what) : puts out any environment parameter 
                   2794: for a user
                   2795: 
                   2796: =item *
                   2797: 
                   2798: subscribe($fname) : subscribe to a resource, return URL if possible
                   2799: 
                   2800: =item *
                   2801: 
                   2802: repcopy($filename) : replicate file
                   2803: 
                   2804: =item *
                   2805: 
                   2806: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   2807: localhost, posts hash
                   2808: 
                   2809: =item *
                   2810: 
                   2811: log($domain,$name,$home,$message) : write to permanent log for user; use
                   2812: critical subroutine
                   2813: 
                   2814: =item *
                   2815: 
                   2816: flushcourselogs() : flush (save) buffer logs and access logs
                   2817: 
                   2818: =item *
                   2819: 
                   2820: courselog($what) : save message for course in hash
                   2821: 
                   2822: =item *
                   2823: 
                   2824: courseacclog($what) : save message for course using &courselog().  Perform
                   2825: special processing for specific resource types (problems, exams, quizzes, etc).
                   2826: 
                   2827: =item *
                   2828: 
                   2829: countacc($url) : count the number of accesses to a given URL
                   2830: 
                   2831: =item *
                   2832: 
                   2833: sub checkout($symb,$tuname,$tudom,$tcrsid) : check out an item
                   2834: 
                   2835: =item *
                   2836: 
                   2837: sub checkin($token) : check in an item
                   2838: 
                   2839: =item *
                   2840: 
                   2841: sub expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
                   2842: 
                   2843: =item *
                   2844: 
                   2845: devalidate($symb) : devalidate spreadsheets
                   2846: 
                   2847: =item *
                   2848: 
                   2849: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   2850: and '&' separators
                   2851: 
                   2852: =item *
                   2853: 
                   2854: str2hash($string) : convert string to hash using unescaping and splitting on
                   2855: '=' and '&'
                   2856: 
                   2857: =item *
                   2858: 
                   2859: tmpreset($symb,$namespace,$domain,$stuname) : temporary storage
                   2860: 
                   2861: =item *
                   2862: 
                   2863: tmprestore($symb,$namespace,$domain,$stuname) : temporary restore
                   2864: 
                   2865: =item *
                   2866: 
                   2867: store($storehash,$symb,$namespace,$domain,$stuname) : stores hash permanently
                   2868: for this url; hashref needs to be given and should be a \%hashname; the
                   2869: remaining args aren't required and if they aren't passed or are '' they will
                   2870: be derived from the ENV
                   2871: 
                   2872: =item *
                   2873: 
                   2874: cstore($storehash,$symb,$namespace,$domain,$stuname) : same as store but
                   2875: uses critical subroutine
                   2876: 
                   2877: =item *
                   2878: 
                   2879: restore($symb,$namespace,$domain,$stuname) : returns hash for this symb;
                   2880: all args are optional
                   2881: 
                   2882: =item *
                   2883: 
                   2884: coursedescription($courseid) : course description
                   2885: 
                   2886: =item *
                   2887: 
                   2888: rolesinit($domain,$username,$authhost) : get user privileges
                   2889: 
                   2890: =item *
                   2891: 
                   2892: get($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
                   2893: reference filled in from namesp ($udomain and $uname are optional)
                   2894: 
                   2895: =item *
                   2896: 
                   2897: del($namespace,$storearr,$udomain,$uname) : deletes keys out of array from
                   2898: namesp ($udomain and $uname are optional)
                   2899: 
                   2900: =item *
                   2901: 
1.193     www      2902: dump($namespace,$udomain,$uname,$regexp) : 
                   2903: dumps the complete (or key matching regexp) namespace into a hash
                   2904: ($udomain, $uname and $regexp are optional)
1.191     harris41 2905: 
                   2906: =item *
                   2907: 
                   2908: put($namespace,$storehash,$udomain,$uname) : stores hash in namesp
                   2909: ($udomain and $uname are optional)
                   2910: 
                   2911: =item *
                   2912: 
                   2913: cput($namespace,$storehash,$udomain,$uname) : critical put
                   2914: ($udomain and $uname are optional)
                   2915: 
                   2916: =item *
                   2917: 
                   2918: eget($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
                   2919: reference filled in from namesp (encrypts the return communication)
                   2920: ($udomain and $uname are optional)
                   2921: 
                   2922: =item *
                   2923: 
                   2924: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   2925: actions
                   2926:  F: full access
                   2927:  U,I,K: authentication modes (cxx only)
                   2928:  '': forbidden
                   2929:  1: user needs to choose course
                   2930:  2: browse allowed
                   2931: 
                   2932: =item *
                   2933: 
                   2934: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   2935: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   2936: and course level
                   2937: 
                   2938: =item *
                   2939: 
                   2940: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   2941: network of library servers; returns file handle of where SQL and regex results
                   2942: will be stored for query
                   2943: 
                   2944: =item *
                   2945: 
                   2946: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   2947: explanation of a user role term
                   2948: 
                   2949: =item *
                   2950: 
                   2951: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   2952: user for the level given by URL.  Optional start and end dates (leave empty
                   2953: string or zero for "no date")
                   2954: 
                   2955: =item *
                   2956: 
                   2957: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
                   2958: 
                   2959: =item *
                   2960: 
                   2961: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   2962: modify user
                   2963: 
                   2964: =item *
                   2965: 
                   2966: modifystudent($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
                   2967: $end,$start) : modify student
                   2968: 
                   2969: =item *
                   2970: 
                   2971: writecoursepref($courseid,%prefs) : write preferences for a course
                   2972: 
                   2973: =item *
                   2974: 
                   2975: createcourse($udom,$description,$url) : make/modify course
                   2976: 
                   2977: =item *
                   2978: 
                   2979: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   2980: custom role; give a custom role to a user for the level given by URL.  Specify
                   2981: name and domain of role author, and role name
                   2982: 
                   2983: =item *
                   2984: 
                   2985: revokerole($udom,$uname,$url,$role) : revoke a role for url
                   2986: 
                   2987: =item *
                   2988: 
                   2989: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   2990: 
                   2991: =item *
                   2992: 
                   2993: dirlist($uri) : return directory list based on URI
                   2994: 
                   2995: =item *
                   2996: 
                   2997: directcondval($number) : get current value of a condition; reads from a state
                   2998: string
                   2999: 
                   3000: =item *
                   3001: 
                   3002: condval($condidx) : value of condition index based on state
                   3003: 
                   3004: =item *
                   3005: 
                   3006: EXT($varname,$symbparm) : value of a variable
                   3007: 
                   3008: =item *
                   3009: 
                   3010: metadata($uri,$what,$liburi,$prefix,$depthcount) : get metadata; returns the
                   3011: metadata entry for a file; entry='keys', returns a comma separated list of keys
                   3012: 
                   3013: =item *
                   3014: 
                   3015: symblist($mapname,%newhash) : update symbolic storage links
                   3016: 
                   3017: =item *
                   3018: 
                   3019: symbread($filename) : return symbolic list entry (filename argument optional);
                   3020: returns the data handle
                   3021: 
                   3022: =item *
                   3023: 
                   3024: numval($salt) : return random seed value (addend for rndseed)
                   3025: 
                   3026: =item *
                   3027: 
                   3028: rndseed($symb,$courseid,$domain,$username) : create a random sum; returns
                   3029: a random seed, all arguments are optional, if they aren't sent it uses the
                   3030: environment to derive them. Note: if symb isn't sent and it can't get one
                   3031: from &symbread it will use the current time as its return value
                   3032: 
                   3033: =item *
                   3034: 
                   3035: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   3036: unfakeable, receipt
                   3037: 
                   3038: =item *
                   3039: 
                   3040: receipt() : API to ireceipt working off of ENV values; given out to users
                   3041: 
                   3042: =item *
                   3043: 
                   3044: getfile($file) : serves up a file, returns the contents of a file or -1;
                   3045: replicates and subscribes to the file
                   3046: 
                   3047: =item *
                   3048: 
                   3049: filelocation($dir,$file) : returns file system location of a file based on URI;
                   3050: meant to be "fairly clean" absolute reference
                   3051: 
                   3052: =item *
                   3053: 
                   3054: hreflocation($dir,$file) : returns file system location or a URL; same as
                   3055: filelocation except for hrefs
                   3056: 
                   3057: =item *
                   3058: 
                   3059: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   3060: 
                   3061: =item *
                   3062: 
                   3063: escape() : unpack non-word characters into CGI-compatible hex codes
                   3064: 
                   3065: =item *
                   3066: 
                   3067: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   3068: 
                   3069: =item *
                   3070: 
                   3071: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   3072: as a PerlChildExitHandler
                   3073: 
                   3074: =back
                   3075: 
                   3076: =cut

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