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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.199   ! www         4: # $Id: lonnet.pm,v 1.198 2002/01/04 18:12:23 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.199   ! www        69: # 1/4,2/4 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 
                     83:    %coursedombuf %coursehombuf);
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: 
                   2027: # --------------------------------------------------------- Value of a Variable
                   2028: 
1.58      www      2029: sub EXT {
1.147     www      2030:     my ($varname,$symbparm)=@_;
1.68      www      2031:     unless ($varname) { return ''; }
1.48      www      2032:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   2033:     my $rest;
                   2034:     if ($therest[0]) {
                   2035:        $rest=join('.',@therest);
                   2036:     } else {
                   2037:        $rest='';
                   2038:     }
1.57      www      2039:     my $qualifierrest=$qualifier;
                   2040:     if ($rest) { $qualifierrest.='.'.$rest; }
                   2041:     my $spacequalifierrest=$space;
                   2042:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      2043:     if ($realm eq 'user') {
1.48      www      2044: # --------------------------------------------------------------- user.resource
                   2045: 	if ($space eq 'resource') {
1.122     albertel 2046: 	    my %restored=&restore();
1.57      www      2047:             return $restored{$qualifierrest};
1.48      www      2048: # ----------------------------------------------------------------- user.access
                   2049:         } elsif ($space eq 'access') {
                   2050:             return &allowed($qualifier,$rest);
                   2051: # ------------------------------------------ user.preferences, user.environment
                   2052:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.57      www      2053:             return $ENV{join('.',('environment',$qualifierrest))};
1.48      www      2054: # ----------------------------------------------------------------- user.course
                   2055:         } elsif ($space eq 'course') {
                   2056:             return $ENV{join('.',('request.course',$qualifier))};
                   2057: # ------------------------------------------------------------------- user.role
                   2058:         } elsif ($space eq 'role') {
                   2059:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   2060:             if ($qualifier eq 'value') {
                   2061: 		return $role;
                   2062:             } elsif ($qualifier eq 'extent') {
                   2063:                 return $where;
                   2064:             }
                   2065: # ----------------------------------------------------------------- user.domain
                   2066:         } elsif ($space eq 'domain') {
                   2067:             return $ENV{'user.domain'};
                   2068: # ------------------------------------------------------------------- user.name
                   2069:         } elsif ($space eq 'name') {
                   2070:             return $ENV{'user.name'};
                   2071: # ---------------------------------------------------- Any other user namespace
1.29      www      2072:         } else {
1.48      www      2073:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
1.131     albertel 2074:             my %reply=&get($space,[$item]);
1.48      www      2075:             return $reply{$item};
                   2076:         }
                   2077:     } elsif ($realm eq 'request') {
                   2078: # ------------------------------------------------------------- request.browser
                   2079:         if ($space eq 'browser') {
                   2080: 	    return $ENV{'browser.'.$qualifier};
1.57      www      2081: # ------------------------------------------------------------ request.filename
                   2082:         } else {
                   2083:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      2084:         }
1.28      www      2085:     } elsif ($realm eq 'course') {
1.48      www      2086: # ---------------------------------------------------------- course.description
1.127     ng       2087:         return $ENV{'course.'.$ENV{'request.course.id'}.'.'.
1.57      www      2088:                               $spacequalifierrest};
                   2089:     } elsif ($realm eq 'resource') {
1.127     ng       2090:        if ($ENV{'request.course.id'}) {
1.165     www      2091: 
                   2092: #	   print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
                   2093: 
                   2094: 
1.60      www      2095: # ----------------------------------------------------- Cascading lookup scheme
1.147     www      2096:          my $symbp;
                   2097:          if ($symbparm) {
                   2098:             $symbp=$symbparm;
                   2099: 	 } else {
                   2100:             $symbp=&symbread();
                   2101:          }            
1.127     ng       2102:          my $mapp=(split(/\_\_\_/,$symbp))[0];
1.69      www      2103: 
1.127     ng       2104:          my $symbparm=$symbp.'.'.$spacequalifierrest;
                   2105:          my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.69      www      2106: 
1.127     ng       2107:          my $seclevel=
1.69      www      2108:             $ENV{'request.course.id'}.'.['.
                   2109: 		$ENV{'request.course.sec'}.'].'.$spacequalifierrest;
1.127     ng       2110:          my $seclevelr=
1.69      www      2111:             $ENV{'request.course.id'}.'.['.
                   2112: 		$ENV{'request.course.sec'}.'].'.$symbparm;
1.127     ng       2113:          my $seclevelm=
1.69      www      2114:             $ENV{'request.course.id'}.'.['.
                   2115: 		$ENV{'request.course.sec'}.'].'.$mapparm;
                   2116: 
1.127     ng       2117:          my $courselevel=
1.60      www      2118:             $ENV{'request.course.id'}.'.'.$spacequalifierrest;
1.127     ng       2119:          my $courselevelr=
1.69      www      2120:             $ENV{'request.course.id'}.'.'.$symbparm;
1.127     ng       2121:          my $courselevelm=
1.69      www      2122:             $ENV{'request.course.id'}.'.'.$mapparm;
                   2123: 
1.60      www      2124: # ----------------------------------------------------------- first, check user
1.127     ng       2125:          my %resourcedata=get('resourcedata',
1.131     albertel 2126:                            [$courselevelr,$courselevelm,$courselevel]);
1.127     ng       2127:          if (($resourcedata{$courselevelr}!~/^error\:/) &&
                   2128:              ($resourcedata{$courselevelr}!~/^con_lost/)) {
1.69      www      2129: 
1.127     ng       2130:          if ($resourcedata{$courselevelr}) { 
                   2131:             return $resourcedata{$courselevelr}; }
                   2132:          if ($resourcedata{$courselevelm}) { 
                   2133:             return $resourcedata{$courselevelm}; }
                   2134:          if ($resourcedata{$courselevel}) { return $resourcedata{$courselevel}; }
1.69      www      2135: 
1.94      www      2136:       } else {
                   2137: 	  if ($resourcedata{$courselevelr}!~/No such file/) {
                   2138: 	    &logthis("<font color=blue>WARNING:".
                   2139: 		   " Trying to get resource data for ".$ENV{'user.name'}." at "
                   2140:                    .$ENV{'user.domain'}.": ".$resourcedata{$courselevelr}.
                   2141:                  "</font>");
                   2142: 	  }
1.63      www      2143:       }
1.95      www      2144: 
1.60      www      2145: # -------------------------------------------------------- second, check course
1.96      www      2146: 
1.60      www      2147:         my $reply=&reply('get:'.
1.96      www      2148:               $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
                   2149:               $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
1.79      www      2150: 	      ':resourcedata:'.
                   2151:    &escape($seclevelr).'&'.&escape($seclevelm).'&'.&escape($seclevel).'&'.
                   2152:    &escape($courselevelr).'&'.&escape($courselevelm).'&'.&escape($courselevel),
1.96      www      2153: 		   $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
1.63      www      2154:       if ($reply!~/^error\:/) {
1.191     harris41 2155: 	  foreach (split(/\&/,$reply)) {
1.79      www      2156: 	      if ($_) { return &unescape($_); }
1.191     harris41 2157:           }
1.63      www      2158:       }
1.94      www      2159:       if (($reply=~/^con_lost/) || ($reply=~/^error\:/)) {
                   2160: 	  &logthis("<font color=blue>WARNING:".
1.95      www      2161:                 " Getting ".$reply." asking for ".$varname." for ".
1.96      www      2162:                 $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
1.95      www      2163:                 ' at '.
1.96      www      2164:                 $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
1.95      www      2165:                 ' from '.
1.96      www      2166:                 $ENV{'course.'.$ENV{'request.course.id'}.'.home'}.
1.94      www      2167:                  "</font>");
                   2168:       }
1.60      www      2169: # ------------------------------------------------------ third, check map parms
1.65      www      2170:        my %parmhash=();
                   2171:        my $thisparm='';       
                   2172:        if (tie(%parmhash,'GDBM_File',
                   2173:           $ENV{'request.course.fn'}.'_parms.db',&GDBM_READER,0640)) {
                   2174:            $thisparm=$parmhash{$symbparm};
                   2175: 	   untie(%parmhash);
1.60      www      2176:        }
1.65      www      2177:        if ($thisparm) { return $thisparm; }
1.60      www      2178:      }
                   2179:      
                   2180: # --------------------------------------------- last, look in resource metadata
1.71      www      2181: 
1.78      www      2182:       $spacequalifierrest=~s/\./\_/;
1.71      www      2183:       my $metadata=&metadata($ENV{'request.filename'},$spacequalifierrest);
                   2184:       if ($metadata) { return $metadata; }
1.78      www      2185:       $metadata=&metadata($ENV{'request.filename'},
                   2186:                                          'parameter_'.$spacequalifierrest);
                   2187:       if ($metadata) { return $metadata; }
1.142     www      2188: 
1.145     www      2189: # ------------------------------------------------------------------ Cascade up
                   2190: 
                   2191:       unless ($space eq '0') {
1.165     www      2192:           my ($part,$id)=split(/\_/,$space);
1.145     www      2193:           if ($id) {
1.147     www      2194: 	      my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
                   2195:                                    $symbparm);
1.145     www      2196:               if ($partgeneral) { return $partgeneral; }
                   2197:           } else {
1.147     www      2198:               my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
                   2199:                                        $symbparm);
1.145     www      2200:               if ($resourcegeneral) { return $resourcegeneral; }
                   2201:           }
                   2202:       }
1.71      www      2203: 
1.48      www      2204: # ---------------------------------------------------- Any other user namespace
                   2205:     } elsif ($realm eq 'environment') {
                   2206: # ----------------------------------------------------------------- environment
1.127     ng       2207:         return $ENV{'environment.'.$spacequalifierrest};
1.28      www      2208:     } elsif ($realm eq 'system') {
1.48      www      2209: # ----------------------------------------------------------------- system.time
                   2210: 	if ($space eq 'time') {
                   2211: 	    return time;
                   2212:         }
1.28      www      2213:     }
1.48      www      2214:     return '';
1.61      www      2215: }
                   2216: 
1.71      www      2217: # ---------------------------------------------------------------- Get metadata
                   2218: 
                   2219: sub metadata {
1.176     www      2220:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.78      www      2221: 
1.71      www      2222:     $uri=&declutter($uri);
1.73      www      2223:     my $filename=$uri;
                   2224:     $uri=~s/\.meta$//;
1.172     www      2225: #
                   2226: # Is the metadata already cached?
1.177     www      2227: # Look at timestamp of caching
1.172     www      2228: # Everything is cached by the main uri, libraries are never directly cached
                   2229: #
1.174     www      2230:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600) {
1.172     www      2231: #
                   2232: # Is this a recursive call for a library?
                   2233: #
1.171     www      2234:         if ($liburi) {
                   2235: 	    $liburi=&declutter($liburi);
                   2236:             $filename=$liburi;
                   2237:         }
1.140     www      2238:         my %metathesekeys=();
1.73      www      2239:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
                   2240: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
1.71      www      2241:         my $parser=HTML::TokeParser->new(\$metastring);
                   2242:         my $token;
1.140     www      2243:         undef %metathesekeys;
1.71      www      2244:         while ($token=$parser->get_token) {
                   2245:            if ($token->[0] eq 'S') {
1.135     www      2246: 	     if (defined($token->[2]->{'package'})) {
1.172     www      2247: #
                   2248: # This is a package - get package info
                   2249: #
1.136     www      2250: 	      my $package=$token->[2]->{'package'};
                   2251: 	      my $keyroot='';
1.172     www      2252:               if ($prefix) {
                   2253: 		  $keyroot.='_'.$prefix;
                   2254:               } else {
                   2255:                 if (defined($token->[2]->{'part'})) { 
                   2256:                    $keyroot.='_'.$token->[2]->{'part'}; 
                   2257: 	        }
1.136     www      2258: 	      }
                   2259:               if (defined($token->[2]->{'id'})) { 
1.165     www      2260:                  $keyroot.='_'.$token->[2]->{'id'}; 
1.136     www      2261: 	      }
                   2262:               if ($metacache{$uri.':packages'}) {
                   2263:                  $metacache{$uri.':packages'}.=','.$package.$keyroot;
                   2264:               } else {
                   2265:                  $metacache{$uri.':packages'}=$package.$keyroot;
                   2266: 	      }
1.191     harris41 2267:               foreach (keys %packagetab) {
1.137     www      2268: 		  if ($_=~/^$package\&/) {
                   2269: 		      my ($pack,$name,$subp)=split(/\&/,$_);
1.139     www      2270:                       my $value=$packagetab{$_};
1.144     www      2271: 		      my $part=$keyroot;
                   2272:                       $part=~s/^\_//;
1.139     www      2273:                       if ($subp eq 'display') {
                   2274: 			  $value.=' [Part: '.$part.']';
                   2275:                       }
                   2276:                       my $unikey='parameter'.$keyroot.'_'.$name;
1.140     www      2277:                       $metathesekeys{$unikey}=1;
1.144     www      2278:                       $metacache{$uri.':'.$unikey.'.part'}=$part;
1.141     www      2279:                       unless 
                   2280:                        (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
                   2281:                          $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
                   2282: 		      }
1.137     www      2283:                   }
1.191     harris41 2284:               }
1.135     www      2285:              } else {
1.172     www      2286: #
                   2287: # This is not a package - some other kind of start tag
                   2288: # 
1.175     www      2289:               my $entry=$token->[1];
1.176     www      2290:               my $unikey;
                   2291:               if ($entry eq 'import') {
                   2292:                  $unikey='';
                   2293:               } else {
                   2294:                  $unikey=$entry;
                   2295: 	      }
1.172     www      2296:               if ($prefix) {
1.176     www      2297: 		  $unikey.=$prefix;
1.172     www      2298:               } else {
                   2299:                 if (defined($token->[2]->{'part'})) { 
                   2300:                    $unikey.='_'.$token->[2]->{'part'}; 
                   2301: 	        }
1.136     www      2302: 	      }
                   2303:               if (defined($token->[2]->{'id'})) { 
1.165     www      2304:                  $unikey.='_'.$token->[2]->{'id'}; 
1.71      www      2305: 	      }
1.175     www      2306: 
                   2307:              if ($entry eq 'import') {
                   2308: #
                   2309: # Importing a library here
1.176     www      2310: #                
                   2311: 		 if (defined($depthcount)) { $depthcount++; } else 
                   2312:                                            { $depthcount=0; }
                   2313:                  if ($depthcount<20) {
1.191     harris41 2314: 		     foreach (split(/\,/,&metadata($uri,'keys',
                   2315:                                   $parser->get_text('/import'),$unikey,
                   2316:                                   $depthcount))) {
1.177     www      2317:                          $metathesekeys{$_}=1;
1.191     harris41 2318: 		     }
1.176     www      2319: 		 }
1.175     www      2320:              } else { 
                   2321: 
1.72      www      2322:               if (defined($token->[2]->{'name'})) { 
1.71      www      2323:                  $unikey.='_'.$token->[2]->{'name'}; 
                   2324: 	      }
1.140     www      2325:               $metathesekeys{$unikey}=1;
1.191     harris41 2326:               foreach (@{$token->[3]}) {
1.71      www      2327: 		  $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.191     harris41 2328:               }
1.78      www      2329:               unless (
                   2330:                  $metacache{$uri.':'.$unikey}=$parser->get_text('/'.$entry)
                   2331: 		      ) { $metacache{$uri.':'.$unikey}=
                   2332: 			      $metacache{$uri.':'.$unikey.'.default'};
                   2333: 		      }
1.172     www      2334: # end of not-a-package not-a-library import
1.175     www      2335: 	   }
1.172     www      2336: # end of not-a-package start tag
                   2337: 	  }
                   2338: # the next is the end of "start tag"
1.140     www      2339: 	 }
1.71      www      2340:        }
1.140     www      2341:        $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
1.174     www      2342:        $metacache{$uri.':cachedtimestamp'}=time;
1.177     www      2343: # this is the end of "was not already recently cached
1.71      www      2344:     }
                   2345:     return $metacache{$uri.':'.$what};
                   2346: }
                   2347: 
1.31      www      2348: # ------------------------------------------------- Update symbolic store links
                   2349: 
                   2350: sub symblist {
                   2351:     my ($mapname,%newhash)=@_;
                   2352:     $mapname=declutter($mapname);
                   2353:     my %hash;
                   2354:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   2355:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
                   2356:                       &GDBM_WRCREAT,0640)) {
1.191     harris41 2357: 	    foreach (keys %newhash) {
1.31      www      2358:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
1.191     harris41 2359:             }
1.31      www      2360:             if (untie(%hash)) {
                   2361: 		return 'ok';
                   2362:             }
                   2363:         }
                   2364:     }
                   2365:     return 'error';
                   2366: }
                   2367: 
                   2368: # ------------------------------------------------------ Return symb list entry
                   2369: 
                   2370: sub symbread {
1.44      www      2371:     my $thisfn=shift;
                   2372:     unless ($thisfn) {
1.179     www      2373:         if ($ENV{'request.symb'}) { return $ENV{'request.symb'}; }
1.44      www      2374: 	$thisfn=$ENV{'request.filename'};
                   2375:     }
                   2376:     $thisfn=declutter($thisfn);
1.31      www      2377:     my %hash;
1.37      www      2378:     my %bighash;
                   2379:     my $syval='';
1.45      www      2380:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31      www      2381:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
                   2382:                       &GDBM_READER,0640)) {
                   2383: 	    $syval=$hash{$thisfn};
1.37      www      2384:             untie(%hash);
                   2385:         }
                   2386: # ---------------------------------------------------------- There was an entry
                   2387:         if ($syval) {
                   2388:            unless ($syval=~/\_\d+$/) {
                   2389: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44      www      2390:                   &appenv('request.ambiguous' => $thisfn);
1.37      www      2391:                   return '';
                   2392:                }    
                   2393:                $syval.=$1;
                   2394: 	   }
                   2395:         } else {
                   2396: # ------------------------------------------------------- Was not in symb table
                   2397:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                   2398:                             &GDBM_READER,0640)) {
                   2399: # ---------------------------------------------- Get ID(s) for current resource
                   2400:               my $ids=$bighash{'ids_/res/'.$thisfn};
1.65      www      2401:               unless ($ids) { 
                   2402:                  $ids=$bighash{'ids_/'.$thisfn};
                   2403:               }
1.37      www      2404:               if ($ids) {
                   2405: # ------------------------------------------------------------------- Has ID(s)
                   2406:                  my @possibilities=split(/\,/,$ids);
1.39      www      2407:                  if ($#possibilities==0) {
                   2408: # ----------------------------------------------- There is only one possibility
1.37      www      2409: 		     my ($mapid,$resid)=split(/\./,$ids);
                   2410:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
                   2411:                  } else {
1.39      www      2412: # ------------------------------------------ There is more than one possibility
                   2413:                      my $realpossible=0;
1.191     harris41 2414:                      foreach (@possibilities) {
1.39      www      2415: 			 my $file=$bighash{'src_'.$_};
                   2416:                          if (&allowed('bre',$file)) {
                   2417:          		    my ($mapid,$resid)=split(/\./,$_);
                   2418:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   2419: 				$realpossible++;
                   2420:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   2421:                                        '___'.$resid;
                   2422:                             }
                   2423: 			 }
1.191     harris41 2424:                      }
1.39      www      2425: 		     if ($realpossible!=1) { $syval=''; }
1.37      www      2426:                  }
                   2427: 	      }
                   2428:               untie(%bighash)
                   2429:            } 
1.31      www      2430:         }
1.62      www      2431:         if ($syval) {
                   2432:            return $syval.'___'.$thisfn; 
                   2433:         }
1.31      www      2434:     }
1.44      www      2435:     &appenv('request.ambiguous' => $thisfn);
1.31      www      2436:     return '';
                   2437: }
                   2438: 
                   2439: # ---------------------------------------------------------- Return random seed
                   2440: 
1.32      www      2441: sub numval {
                   2442:     my $txt=shift;
                   2443:     $txt=~tr/A-J/0-9/;
                   2444:     $txt=~tr/a-j/0-9/;
                   2445:     $txt=~tr/K-T/0-9/;
                   2446:     $txt=~tr/k-t/0-9/;
                   2447:     $txt=~tr/U-Z/0-5/;
                   2448:     $txt=~tr/u-z/0-5/;
                   2449:     $txt=~s/\D//g;
                   2450:     return int($txt);
                   2451: }    
                   2452: 
1.31      www      2453: sub rndseed {
1.155     albertel 2454:     my ($symb,$courseid,$domain,$username)=@_;
                   2455:     if (!$symb) {
                   2456:       unless ($symb=&symbread()) { return time; }
                   2457:     }
                   2458:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
                   2459:     if (!$domain) {$domain=$ENV{'user.domain'};}
                   2460:     if (!$username) {$username=$ENV{'user.name'};}
                   2461:     {
1.98      albertel 2462:       use integer;
                   2463:       my $symbchck=unpack("%32C*",$symb) << 27;
1.100     albertel 2464:       my $symbseed=numval($symb) << 22;
1.155     albertel 2465:       my $namechck=unpack("%32C*",$username) << 17;
                   2466:       my $nameseed=numval($username) << 12;
                   2467:       my $domainseed=unpack("%32C*",$domain) << 7;
                   2468:       my $courseseed=unpack("%32C*",$courseid);
1.98      albertel 2469:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.99      albertel 2470:       #uncommenting these lines can break things!
                   2471:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   2472:       #&Apache::lonxml::debug("rndseed :$num:$symb");
1.98      albertel 2473:       return $num;
                   2474:     }
1.36      albertel 2475: }
                   2476: 
1.76      www      2477: sub ireceipt {
                   2478:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
                   2479:     my $cuname=unpack("%32C*",$funame);
                   2480:     my $cudom=unpack("%32C*",$fudom);
                   2481:     my $cucourseid=unpack("%32C*",$fucourseid);
                   2482:     my $cusymb=unpack("%32C*",$fusymb);
1.77      www      2483:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76      www      2484:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
                   2485:            ($cunique%$cuname+
                   2486:             $cunique%$cudom+
                   2487:             $cusymb%$cuname+
                   2488:             $cusymb%$cudom+
                   2489:             $cucourseid%$cuname+
                   2490:             $cucourseid%$cudom);
                   2491: }
                   2492: 
                   2493: sub receipt {
                   2494:     return &ireceipt($ENV{'user.name'},$ENV{'user.domain'},
                   2495:                      $ENV{'request.course.id'},&symbread());
                   2496: }
                   2497:   
1.36      albertel 2498: # ------------------------------------------------------------ Serves up a file
                   2499: # returns either the contents of the file or a -1
                   2500: sub getfile {
                   2501:   my $file=shift;
1.37      www      2502:   &repcopy($file);
1.36      albertel 2503:   if (! -e $file ) { return -1; };
                   2504:   my $fh=Apache::File->new($file);
                   2505:   my $a='';
                   2506:   while (<$fh>) { $a .=$_; }
                   2507:   return $a
                   2508: }
                   2509: 
                   2510: sub filelocation {
                   2511:   my ($dir,$file) = @_;
                   2512:   my $location;
                   2513:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59      albertel 2514:   if ($file=~m:^/~:) { # is a contruction space reference
                   2515:     $location = $file;
                   2516:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.36      albertel 2517:   } else {
1.59      albertel 2518:     $file=~s/^$perlvar{'lonDocRoot'}//;
                   2519:     $file=~s:^/*res::;
                   2520:     if ( !( $file =~ m:^/:) ) {
                   2521:       $location = $dir. '/'.$file;
                   2522:     } else {
                   2523:       $location = '/home/httpd/html/res'.$file;
                   2524:     }
1.36      albertel 2525:   }
                   2526:   $location=~s://+:/:g; # remove duplicate /
1.46      www      2527:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   2528:   return $location;
                   2529: }
1.36      albertel 2530: 
1.46      www      2531: sub hreflocation {
                   2532:     my ($dir,$file)=@_;
1.191     harris41 2533:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46      www      2534:        my $finalpath=filelocation($dir,$file);
                   2535:        $finalpath=~s/^\/home\/httpd\/html//;
                   2536:        return $finalpath;
                   2537:     } else {
                   2538:        return $file;
                   2539:     }
1.31      www      2540: }
                   2541: 
                   2542: # ------------------------------------------------------------- Declutters URLs
                   2543: 
                   2544: sub declutter {
                   2545:     my $thisfn=shift;
                   2546:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
                   2547:     $thisfn=~s/^\///;
                   2548:     $thisfn=~s/^res\///;
                   2549:     return $thisfn;
1.12      www      2550: }
                   2551: 
                   2552: # -------------------------------------------------------- Escape Special Chars
                   2553: 
                   2554: sub escape {
                   2555:     my $str=shift;
                   2556:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   2557:     return $str;
                   2558: }
                   2559: 
                   2560: # ----------------------------------------------------- Un-Escape Special Chars
                   2561: 
                   2562: sub unescape {
                   2563:     my $str=shift;
                   2564:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2565:     return $str;
                   2566: }
1.11      www      2567: 
1.1       albertel 2568: # ================================================================ Main Program
                   2569: 
1.184     www      2570: sub goodbye {
                   2571:    &flushcourselogs();
                   2572:    &logthis("Shutting down");
                   2573: }
                   2574: 
1.179     www      2575: BEGIN {
1.1       albertel 2576: # ------------------------------------------------------------ Read access.conf
1.195     www      2577:     unless ($readit) {
1.1       albertel 2578: {
                   2579:     my $config=Apache::File->new("/etc/httpd/conf/access.conf");
                   2580: 
                   2581:     while (my $configline=<$config>) {
                   2582:         if ($configline =~ /PerlSetVar/) {
                   2583: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      2584:            chomp($varvalue);
1.1       albertel 2585:            $perlvar{$varname}=$varvalue;
                   2586:         }
                   2587:     }
                   2588: }
                   2589: 
                   2590: # ------------------------------------------------------------- Read hosts file
                   2591: {
                   2592:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
                   2593: 
                   2594:     while (my $configline=<$config>) {
1.154     www      2595:        chomp($configline);
1.1       albertel 2596:        my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                   2597:        $hostname{$id}=$name;
                   2598:        $hostdom{$id}=$domain;
1.150     www      2599:        $hostip{$id}=$ip;
1.1       albertel 2600:        if ($role eq 'library') { $libserv{$id}=$name; }
                   2601:     }
                   2602: }
                   2603: 
                   2604: # ------------------------------------------------------ Read spare server file
                   2605: {
                   2606:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
                   2607: 
                   2608:     while (my $configline=<$config>) {
                   2609:        chomp($configline);
                   2610:        if (($configline) && ($configline ne $perlvar{'lonHostID'})) {
                   2611:           $spareid{$configline}=1;
                   2612:        }
                   2613:     }
                   2614: }
1.11      www      2615: # ------------------------------------------------------------ Read permissions
                   2616: {
                   2617:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
                   2618: 
                   2619:     while (my $configline=<$config>) {
                   2620:        chomp($configline);
1.160     www      2621:       if ($configline) {
1.11      www      2622:        my ($role,$perm)=split(/ /,$configline);
                   2623:        if ($perm ne '') { $pr{$role}=$perm; }
1.160     www      2624:       }
1.11      www      2625:     }
                   2626: }
                   2627: 
                   2628: # -------------------------------------------- Read plain texts for permissions
                   2629: {
                   2630:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
                   2631: 
                   2632:     while (my $configline=<$config>) {
                   2633:        chomp($configline);
1.160     www      2634:       if ($configline) {
1.11      www      2635:        my ($short,$plain)=split(/:/,$configline);
                   2636:        if ($plain ne '') { $prp{$short}=$plain; }
1.160     www      2637:       }
1.135     www      2638:     }
                   2639: }
                   2640: 
                   2641: # ---------------------------------------------------------- Read package table
                   2642: {
                   2643:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
                   2644: 
                   2645:     while (my $configline=<$config>) {
                   2646:        chomp($configline);
                   2647:        my ($short,$plain)=split(/:/,$configline);
1.143     www      2648:        my ($pack,$name)=split(/\&/,$short);
                   2649:        if ($plain ne '') {
                   2650:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   2651:           $packagetab{$short}=$plain; 
1.25      www      2652:        }
1.11      www      2653:     }
                   2654: }
                   2655: 
1.71      www      2656: %metacache=();
1.185     www      2657: 
                   2658: $processmarker=$$.'_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      2659: $dumpcount=0;
1.22      www      2660: 
1.163     harris41 2661: &logtouch();
1.12      www      2662: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      2663: $readit=1;
                   2664: }
1.1       albertel 2665: }
1.179     www      2666: 
1.1       albertel 2667: 1;
1.191     harris41 2668: __END__
                   2669: 
                   2670: =head1 NAME
                   2671: 
                   2672: Apache::lonnet - TCP networking package
                   2673: 
                   2674: =head1 SYNOPSIS
                   2675: 
                   2676: Invoked by other LON-CAPA modules.
                   2677: 
                   2678:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   2679: 
                   2680: =head1 INTRODUCTION
                   2681: 
                   2682: This module provides subroutines which interact with the
                   2683: lonc/lond (TCP) network layer of LON-CAPA.
                   2684: 
                   2685: This is part of the LearningOnline Network with CAPA project
                   2686: described at http://www.lon-capa.org.
                   2687: 
                   2688: =head1 HANDLER SUBROUTINE
                   2689: 
                   2690: There is no handler routine for this module.
                   2691: 
                   2692: =head1 OTHER SUBROUTINES
                   2693: 
                   2694: =over 4
                   2695: 
                   2696: =item *
                   2697: 
                   2698: logtouch() : make sure the logfile, lonnet.log, exists
                   2699: 
                   2700: =item *
                   2701: 
                   2702: logthis() : append message to lonnet.log
                   2703: 
                   2704: =item *
                   2705: 
                   2706: logperm() : append a permanent message to lonnet.perm.log
                   2707: 
                   2708: =item *
                   2709: 
                   2710: subreply() : non-critical communication, called by &reply
                   2711: 
                   2712: =item *
                   2713: 
                   2714: reply() : makes two attempts to pass message; logs refusals and rejections
                   2715: 
                   2716: =item *
                   2717: 
                   2718: reconlonc() : tries to reconnect lonc client processes.
                   2719: 
                   2720: =item *
                   2721: 
                   2722: critical() : passes a critical message to another server; if cannot get
                   2723: through then place message in connection buffer
                   2724: 
                   2725: =item *
                   2726: 
                   2727: appenv(%hash) : read in current user environment, append new environment
                   2728: values to make new user environment
                   2729: 
                   2730: =item *
                   2731: 
                   2732: delenv($varname) : read in current user environment, remove all values
                   2733: beginning with $varname, write new user environment (note: flock is used
                   2734: to prevent conflicting shared read/writes with file)
                   2735: 
                   2736: =item *
                   2737: 
                   2738: spareserver() : find server with least workload from spare.tab
                   2739: 
                   2740: =item *
                   2741: 
                   2742: queryauthenticate($uname,$udom) : try to determine user's current
                   2743: authentication scheme
                   2744: 
                   2745: =item *
                   2746: 
                   2747: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
                   2748: servers (first use the current one)
                   2749: 
                   2750: =item *
                   2751: 
                   2752: homeserver($uname,$udom) : find the homebase for a user from domain's lib
                   2753: servers
                   2754: 
                   2755: =item *
                   2756: 
                   2757: idget($udom,@ids) : find the usernames behind a list of IDs (returns hash:
                   2758: id=>name,id=>name)
                   2759: 
                   2760: =item *
                   2761: 
                   2762: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
                   2763: name=>id,name=>id)
                   2764: 
                   2765: =item *
                   2766: 
                   2767: idput($udom,%ids) : store away a list of names and associated IDs
                   2768: 
                   2769: =item *
                   2770: 
                   2771: usection($domain,$user,$courseid) : output of section name/number or '' for
                   2772: "not in course" and '-1' for "no section"
                   2773: 
                   2774: =item *
                   2775: 
                   2776: userenvironment($domain,$user,$what) : puts out any environment parameter 
                   2777: for a user
                   2778: 
                   2779: =item *
                   2780: 
                   2781: subscribe($fname) : subscribe to a resource, return URL if possible
                   2782: 
                   2783: =item *
                   2784: 
                   2785: repcopy($filename) : replicate file
                   2786: 
                   2787: =item *
                   2788: 
                   2789: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   2790: localhost, posts hash
                   2791: 
                   2792: =item *
                   2793: 
                   2794: log($domain,$name,$home,$message) : write to permanent log for user; use
                   2795: critical subroutine
                   2796: 
                   2797: =item *
                   2798: 
                   2799: flushcourselogs() : flush (save) buffer logs and access logs
                   2800: 
                   2801: =item *
                   2802: 
                   2803: courselog($what) : save message for course in hash
                   2804: 
                   2805: =item *
                   2806: 
                   2807: courseacclog($what) : save message for course using &courselog().  Perform
                   2808: special processing for specific resource types (problems, exams, quizzes, etc).
                   2809: 
                   2810: =item *
                   2811: 
                   2812: countacc($url) : count the number of accesses to a given URL
                   2813: 
                   2814: =item *
                   2815: 
                   2816: sub checkout($symb,$tuname,$tudom,$tcrsid) : check out an item
                   2817: 
                   2818: =item *
                   2819: 
                   2820: sub checkin($token) : check in an item
                   2821: 
                   2822: =item *
                   2823: 
                   2824: sub expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
                   2825: 
                   2826: =item *
                   2827: 
                   2828: devalidate($symb) : devalidate spreadsheets
                   2829: 
                   2830: =item *
                   2831: 
                   2832: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   2833: and '&' separators
                   2834: 
                   2835: =item *
                   2836: 
                   2837: str2hash($string) : convert string to hash using unescaping and splitting on
                   2838: '=' and '&'
                   2839: 
                   2840: =item *
                   2841: 
                   2842: tmpreset($symb,$namespace,$domain,$stuname) : temporary storage
                   2843: 
                   2844: =item *
                   2845: 
                   2846: tmprestore($symb,$namespace,$domain,$stuname) : temporary restore
                   2847: 
                   2848: =item *
                   2849: 
                   2850: store($storehash,$symb,$namespace,$domain,$stuname) : stores hash permanently
                   2851: for this url; hashref needs to be given and should be a \%hashname; the
                   2852: remaining args aren't required and if they aren't passed or are '' they will
                   2853: be derived from the ENV
                   2854: 
                   2855: =item *
                   2856: 
                   2857: cstore($storehash,$symb,$namespace,$domain,$stuname) : same as store but
                   2858: uses critical subroutine
                   2859: 
                   2860: =item *
                   2861: 
                   2862: restore($symb,$namespace,$domain,$stuname) : returns hash for this symb;
                   2863: all args are optional
                   2864: 
                   2865: =item *
                   2866: 
                   2867: coursedescription($courseid) : course description
                   2868: 
                   2869: =item *
                   2870: 
                   2871: rolesinit($domain,$username,$authhost) : get user privileges
                   2872: 
                   2873: =item *
                   2874: 
                   2875: get($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
                   2876: reference filled in from namesp ($udomain and $uname are optional)
                   2877: 
                   2878: =item *
                   2879: 
                   2880: del($namespace,$storearr,$udomain,$uname) : deletes keys out of array from
                   2881: namesp ($udomain and $uname are optional)
                   2882: 
                   2883: =item *
                   2884: 
1.193     www      2885: dump($namespace,$udomain,$uname,$regexp) : 
                   2886: dumps the complete (or key matching regexp) namespace into a hash
                   2887: ($udomain, $uname and $regexp are optional)
1.191     harris41 2888: 
                   2889: =item *
                   2890: 
                   2891: put($namespace,$storehash,$udomain,$uname) : stores hash in namesp
                   2892: ($udomain and $uname are optional)
                   2893: 
                   2894: =item *
                   2895: 
                   2896: cput($namespace,$storehash,$udomain,$uname) : critical put
                   2897: ($udomain and $uname are optional)
                   2898: 
                   2899: =item *
                   2900: 
                   2901: eget($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
                   2902: reference filled in from namesp (encrypts the return communication)
                   2903: ($udomain and $uname are optional)
                   2904: 
                   2905: =item *
                   2906: 
                   2907: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   2908: actions
                   2909:  F: full access
                   2910:  U,I,K: authentication modes (cxx only)
                   2911:  '': forbidden
                   2912:  1: user needs to choose course
                   2913:  2: browse allowed
                   2914: 
                   2915: =item *
                   2916: 
                   2917: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   2918: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   2919: and course level
                   2920: 
                   2921: =item *
                   2922: 
                   2923: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   2924: network of library servers; returns file handle of where SQL and regex results
                   2925: will be stored for query
                   2926: 
                   2927: =item *
                   2928: 
                   2929: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   2930: explanation of a user role term
                   2931: 
                   2932: =item *
                   2933: 
                   2934: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   2935: user for the level given by URL.  Optional start and end dates (leave empty
                   2936: string or zero for "no date")
                   2937: 
                   2938: =item *
                   2939: 
                   2940: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
                   2941: 
                   2942: =item *
                   2943: 
                   2944: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   2945: modify user
                   2946: 
                   2947: =item *
                   2948: 
                   2949: modifystudent($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
                   2950: $end,$start) : modify student
                   2951: 
                   2952: =item *
                   2953: 
                   2954: writecoursepref($courseid,%prefs) : write preferences for a course
                   2955: 
                   2956: =item *
                   2957: 
                   2958: createcourse($udom,$description,$url) : make/modify course
                   2959: 
                   2960: =item *
                   2961: 
                   2962: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   2963: custom role; give a custom role to a user for the level given by URL.  Specify
                   2964: name and domain of role author, and role name
                   2965: 
                   2966: =item *
                   2967: 
                   2968: revokerole($udom,$uname,$url,$role) : revoke a role for url
                   2969: 
                   2970: =item *
                   2971: 
                   2972: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   2973: 
                   2974: =item *
                   2975: 
                   2976: dirlist($uri) : return directory list based on URI
                   2977: 
                   2978: =item *
                   2979: 
                   2980: directcondval($number) : get current value of a condition; reads from a state
                   2981: string
                   2982: 
                   2983: =item *
                   2984: 
                   2985: condval($condidx) : value of condition index based on state
                   2986: 
                   2987: =item *
                   2988: 
                   2989: EXT($varname,$symbparm) : value of a variable
                   2990: 
                   2991: =item *
                   2992: 
                   2993: metadata($uri,$what,$liburi,$prefix,$depthcount) : get metadata; returns the
                   2994: metadata entry for a file; entry='keys', returns a comma separated list of keys
                   2995: 
                   2996: =item *
                   2997: 
                   2998: symblist($mapname,%newhash) : update symbolic storage links
                   2999: 
                   3000: =item *
                   3001: 
                   3002: symbread($filename) : return symbolic list entry (filename argument optional);
                   3003: returns the data handle
                   3004: 
                   3005: =item *
                   3006: 
                   3007: numval($salt) : return random seed value (addend for rndseed)
                   3008: 
                   3009: =item *
                   3010: 
                   3011: rndseed($symb,$courseid,$domain,$username) : create a random sum; returns
                   3012: a random seed, all arguments are optional, if they aren't sent it uses the
                   3013: environment to derive them. Note: if symb isn't sent and it can't get one
                   3014: from &symbread it will use the current time as its return value
                   3015: 
                   3016: =item *
                   3017: 
                   3018: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   3019: unfakeable, receipt
                   3020: 
                   3021: =item *
                   3022: 
                   3023: receipt() : API to ireceipt working off of ENV values; given out to users
                   3024: 
                   3025: =item *
                   3026: 
                   3027: getfile($file) : serves up a file, returns the contents of a file or -1;
                   3028: replicates and subscribes to the file
                   3029: 
                   3030: =item *
                   3031: 
                   3032: filelocation($dir,$file) : returns file system location of a file based on URI;
                   3033: meant to be "fairly clean" absolute reference
                   3034: 
                   3035: =item *
                   3036: 
                   3037: hreflocation($dir,$file) : returns file system location or a URL; same as
                   3038: filelocation except for hrefs
                   3039: 
                   3040: =item *
                   3041: 
                   3042: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   3043: 
                   3044: =item *
                   3045: 
                   3046: escape() : unpack non-word characters into CGI-compatible hex codes
                   3047: 
                   3048: =item *
                   3049: 
                   3050: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   3051: 
                   3052: =item *
                   3053: 
                   3054: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   3055: as a PerlChildExitHandler
                   3056: 
                   3057: =back
                   3058: 
                   3059: =cut

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