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

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

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