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

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

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