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

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

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