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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.413   ! www         4: # $Id: lonnet.pm,v 1.412 2003/09/15 18:43:54 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: # 3/2 Gerd Kortemeyer
                     51: # 3/19,3/20 Gerd Kortemeyer
                     52: # 5/26,5/28 Gerd Kortemeyer
                     53: # 5/30 H. K. Ng
                     54: # 6/1 Gerd Kortemeyer
                     55: # July Guy Albertelli
                     56: # 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,
                     57: # 10/2 Gerd Kortemeyer
1.179     www        58: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
1.182     matthew    59: # 12/5 Matthew Hall
1.184     www        60: # 12/5 Guy Albertelli
1.190     www        61: # 12/6,12/7,12/12 Gerd Kortemeyer
1.195     www        62: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
1.196     www        63: # YEAR=2002
1.200     www        64: # 1/4,2/4,2/7 Gerd Kortemeyer
1.171     www        65: #
1.169     harris41   66: ###
                     67: 
1.1       albertel   68: package Apache::lonnet;
                     69: 
                     70: use strict;
                     71: use Apache::File;
1.8       www        72: use LWP::UserAgent();
1.15      www        73: use HTTP::Headers;
1.11      www        74: use vars 
1.300     albertel   75: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom 
1.301     www        76:    %libserv %pr %prp %metacache %packagetab %titlecache 
1.349     www        77:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
1.352     www        78:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseresdatacache 
1.403     www        79:    %domaindescription %domain_auth_def %domain_auth_arg_def 
                     80:    %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir);
                     81: 
1.1       albertel   82: use IO::Socket;
1.31      www        83: use GDBM_File;
1.8       www        84: use Apache::Constants qw(:common :http);
1.208     albertel   85: use HTML::LCParser;
1.88      www        86: use Fcntl qw(:flock);
1.294     matthew    87: use Apache::loncoursedata;
                     88: 
1.195     www        89: my $readit;
1.1       albertel   90: 
                     91: # --------------------------------------------------------------------- Logging
                     92: 
1.163     harris41   93: sub logtouch {
                     94:     my $execdir=$perlvar{'lonDaemons'};
                     95:     unless (-e "$execdir/logs/lonnet.log") {
                     96: 	my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
                     97: 	close $fh;
                     98:     }
                     99:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    100:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    101: }
                    102: 
1.1       albertel  103: sub logthis {
                    104:     my $message=shift;
                    105:     my $execdir=$perlvar{'lonDaemons'};
                    106:     my $now=time;
                    107:     my $local=localtime($now);
1.162     harris41  108:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
                    109:     print $fh "$local ($$): $message\n";
1.1       albertel  110:     return 1;
                    111: }
                    112: 
                    113: sub logperm {
                    114:     my $message=shift;
                    115:     my $execdir=$perlvar{'lonDaemons'};
                    116:     my $now=time;
                    117:     my $local=localtime($now);
1.162     harris41  118:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
                    119:     print $fh "$now:$message:$local\n";
1.1       albertel  120:     return 1;
                    121: }
                    122: 
                    123: # -------------------------------------------------- Non-critical communication
                    124: sub subreply {
                    125:     my ($cmd,$server)=@_;
                    126:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                    127:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    128:                                      Type    => SOCK_STREAM,
                    129:                                      Timeout => 10)
                    130:        or return "con_lost";
                    131:     print $client "$cmd\n";
                    132:     my $answer=<$client>;
1.9       www       133:     if (!$answer) { $answer="con_lost"; }
1.1       albertel  134:     chomp($answer);
                    135:     return $answer;
                    136: }
                    137: 
                    138: sub reply {
                    139:     my ($cmd,$server)=@_;
1.205     www       140:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  141:     my $answer=subreply($cmd,$server);
1.203     www       142:     if ($answer eq 'con_lost') {
1.311     matthew   143:         #sleep 5; 
                    144:         #$answer=subreply($cmd,$server);
                    145:         #if ($answer eq 'con_lost') {
1.233     albertel  146: 	#   &logthis("Second attempt con_lost on $server");
                    147:         #   my $peerfile="$perlvar{'lonSockDir'}/$server";
                    148:         #   my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    149:         #                                    Type    => SOCK_STREAM,
                    150:         #                                    Timeout => 10)
                    151:         #              or return "con_lost";
                    152:         #   &logthis("Killing socket");
                    153:         #   print $client "close_connection_exit\n";
                    154:            #sleep 5;
                    155:         #   $answer=subreply($cmd,$server);       
                    156:        #}   
1.203     www       157:     }
1.65      www       158:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12      www       159:        &logthis("<font color=blue>WARNING:".
                    160:                 " $cmd to $server returned $answer</font>");
                    161:     }
1.1       albertel  162:     return $answer;
                    163: }
                    164: 
                    165: # ----------------------------------------------------------- Send USR1 to lonc
                    166: 
                    167: sub reconlonc {
                    168:     my $peerfile=shift;
                    169:     &logthis("Trying to reconnect for $peerfile");
                    170:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                    171:     if (my $fh=Apache::File->new("$loncfile")) {
                    172: 	my $loncpid=<$fh>;
                    173:         chomp($loncpid);
                    174:         if (kill 0 => $loncpid) {
                    175: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    176:             kill USR1 => $loncpid;
                    177:             sleep 1;
                    178:             if (-e "$peerfile") { return; }
                    179:             &logthis("$peerfile still not there, give it another try");
                    180:             sleep 5;
                    181:             if (-e "$peerfile") { return; }
1.12      www       182:             &logthis(
                    183:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  184:         } else {
1.12      www       185: 	    &logthis(
                    186:                "<font color=blue>WARNING:".
                    187:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  188:         }
                    189:     } else {
1.12      www       190:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1       albertel  191:     }
                    192: }
                    193: 
                    194: # ------------------------------------------------------ Critical communication
1.12      www       195: 
1.1       albertel  196: sub critical {
                    197:     my ($cmd,$server)=@_;
1.89      www       198:     unless ($hostname{$server}) {
                    199:         &logthis("<font color=blue>WARNING:".
                    200:                " Critical message to unknown server ($server)</font>");
                    201:         return 'no_such_host';
                    202:     }
1.1       albertel  203:     my $answer=reply($cmd,$server);
                    204:     if ($answer eq 'con_lost') {
                    205:         my $pingreply=reply('ping',$server);
                    206: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
                    207:         my $pongreply=reply('pong',$server);
                    208:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
                    209:         $answer=reply($cmd,$server);
                    210:         if ($answer eq 'con_lost') {
                    211:             my $now=time;
                    212:             my $middlename=$cmd;
1.5       www       213:             $middlename=substr($middlename,0,16);
1.1       albertel  214:             $middlename=~s/\W//g;
                    215:             my $dfilename=
1.305     www       216:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    217:             $dumpcount++;
1.1       albertel  218:             {
                    219:              my $dfh;
                    220:              if ($dfh=Apache::File->new(">$dfilename")) {
1.7       www       221:                 print $dfh "$cmd\n";
1.1       albertel  222: 	     }
                    223:             }
                    224:             sleep 2;
                    225:             my $wcmd='';
                    226:             {
                    227: 	     my $dfh;
                    228:              if ($dfh=Apache::File->new("$dfilename")) {
                    229:                 $wcmd=<$dfh>;
                    230: 	     }
                    231:             }
                    232:             chomp($wcmd);
1.7       www       233:             if ($wcmd eq $cmd) {
1.12      www       234: 		&logthis("<font color=blue>WARNING: ".
                    235:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  236:                 &logperm("D:$server:$cmd");
                    237: 	        return 'con_delayed';
                    238:             } else {
1.12      www       239:                 &logthis("<font color=red>CRITICAL:"
                    240:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  241:                 &logperm("F:$server:$cmd");
                    242:                 return 'con_failed';
                    243:             }
                    244:         }
                    245:     }
                    246:     return $answer;
1.405     albertel  247: }
                    248: 
1.412     www       249: #
1.405     albertel  250: # -------------- Remove all key from the env that start witha lowercase letter
1.412     www       251: #                (Which is always a lon-capa value)
                    252: 
1.405     albertel  253: sub cleanenv {
1.412     www       254: #    unless (defined(&Apache::exists_config_define("MODPERL2"))) { return; }
                    255: #    unless (&Apache::exists_config_define("MODPERL2")) { return; }
1.405     albertel  256:     foreach my $key (keys(%ENV)) {
                    257: 	if ($key =~ /^[a-z]/) {
                    258: 	    delete($ENV{$key});
                    259: 	}
                    260:     }
1.374     www       261: }
                    262:  
                    263: # ------------------------------------------- Transfer profile into environment
                    264: 
                    265: sub transfer_profile_to_env {
                    266:     my ($lonidsdir,$handle)=@_;
                    267:     my @profile;
                    268:     {
                    269: 	my $idf=Apache::File->new("$lonidsdir/$handle.id");
                    270: 	flock($idf,LOCK_SH);
                    271: 	@profile=<$idf>;
                    272: 	$idf->close();
                    273:     }
                    274:     my $envi;
                    275:     for ($envi=0;$envi<=$#profile;$envi++) {
                    276: 	chomp($profile[$envi]);
                    277: 	my ($envname,$envvalue)=split(/=/,$profile[$envi]);
                    278: 	$ENV{$envname} = $envvalue;
                    279:     }
                    280:     $ENV{'user.environment'} = "$lonidsdir/$handle.id";
1.1       albertel  281: }
                    282: 
1.5       www       283: # ---------------------------------------------------------- Append Environment
                    284: 
                    285: sub appenv {
1.6       www       286:     my %newenv=@_;
1.191     harris41  287:     foreach (keys %newenv) {
1.35      www       288: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
                    289:             &logthis("<font color=blue>WARNING: ".
1.151     www       290:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    291:                 .'</font>');
1.35      www       292: 	    delete($newenv{$_});
                    293:         } else {
                    294:             $ENV{$_}=$newenv{$_};
                    295:         }
1.191     harris41  296:     }
1.95      www       297: 
                    298:     my $lockfh;
                    299:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       300:        return 'error: '.$!;
1.95      www       301:     }
                    302:     unless (flock($lockfh,LOCK_EX)) {
                    303:          &logthis("<font color=blue>WARNING: ".
                    304:                   'Could not obtain exclusive lock in appenv: '.$!);
                    305:          $lockfh->close();
                    306:          return 'error: '.$!;
                    307:     }
                    308: 
1.6       www       309:     my @oldenv;
                    310:     {
                    311:      my $fh;
                    312:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       313: 	return 'error: '.$!;
1.6       www       314:      }
                    315:      @oldenv=<$fh>;
1.89      www       316:      $fh->close();
1.6       www       317:     }
                    318:     for (my $i=0; $i<=$#oldenv; $i++) {
                    319:         chomp($oldenv[$i]);
1.9       www       320:         if ($oldenv[$i] ne '') {
                    321:            my ($name,$value)=split(/=/,$oldenv[$i]);
1.24      www       322:            unless (defined($newenv{$name})) {
                    323: 	      $newenv{$name}=$value;
                    324: 	   }
1.9       www       325:         }
1.6       www       326:     }
                    327:     {
                    328:      my $fh;
                    329:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    330: 	return 'error';
                    331:      }
                    332:      my $newname;
1.93      www       333:      foreach $newname (keys %newenv) {
1.6       www       334: 	 print $fh "$newname=$newenv{$newname}\n";
                    335:      }
1.86      albertel  336:      $fh->close();
1.56      www       337:     }
1.95      www       338: 
                    339:     $lockfh->close();
1.56      www       340:     return 'ok';
                    341: }
                    342: # ----------------------------------------------------- Delete from Environment
                    343: 
                    344: sub delenv {
                    345:     my $delthis=shift;
                    346:     my %newenv=();
                    347:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
                    348:         &logthis("<font color=blue>WARNING: ".
                    349:                 "Attempt to delete from environment ".$delthis);
                    350:         return 'error';
                    351:     }
                    352:     my @oldenv;
                    353:     {
                    354:      my $fh;
                    355:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
                    356: 	return 'error';
                    357:      }
1.89      www       358:      unless (flock($fh,LOCK_SH)) {
                    359:          &logthis("<font color=blue>WARNING: ".
                    360:                   'Could not obtain shared lock in delenv: '.$!);
                    361:          $fh->close();
                    362:          return 'error: '.$!;
                    363:      }
1.56      www       364:      @oldenv=<$fh>;
1.89      www       365:      $fh->close();
1.56      www       366:     }
                    367:     {
                    368:      my $fh;
                    369:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    370: 	return 'error';
                    371:      }
1.89      www       372:      unless (flock($fh,LOCK_EX)) {
                    373:          &logthis("<font color=blue>WARNING: ".
                    374:                   'Could not obtain exclusive lock in delenv: '.$!);
                    375:          $fh->close();
                    376:          return 'error: '.$!;
                    377:      }
1.191     harris41  378:      foreach (@oldenv) {
1.56      www       379: 	 unless ($_=~/^$delthis/) { print $fh $_; }
1.191     harris41  380:      }
1.87      www       381:      $fh->close();
1.5       www       382:     }
                    383:     return 'ok';
1.369     albertel  384: }
                    385: 
                    386: # ------------------------------------------ Find out current server userload
                    387: # there is a copy in lond
                    388: sub userload {
                    389:     my $numusers=0;
                    390:     {
                    391: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    392: 	my $filename;
                    393: 	my $curtime=time;
                    394: 	while ($filename=readdir(LONIDS)) {
                    395: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  396: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
                    397: 	    if ($curtime-$mtime < 3600) { $numusers++; }
1.369     albertel  398: 	}
                    399: 	closedir(LONIDS);
                    400:     }
                    401:     my $userloadpercent=0;
                    402:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    403:     if ($maxuserload) {
1.371     albertel  404: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  405:     }
1.372     albertel  406:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  407:     return $userloadpercent;
1.283     www       408: }
                    409: 
                    410: # ------------------------------------------ Fight off request when overloaded
                    411: 
                    412: sub overloaderror {
                    413:     my ($r,$checkserver)=@_;
                    414:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    415:     my $loadavg;
                    416:     if ($checkserver eq $perlvar{'lonHostID'}) {
                    417:        my $loadfile=Apache::File->new('/proc/loadavg');
                    418:        $loadavg=<$loadfile>;
                    419:        $loadavg =~ s/\s.*//g;
1.285     matthew   420:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.283     www       421:     } else {
                    422:        $loadavg=&reply('load',$checkserver);
                    423:     }
1.285     matthew   424:     my $overload=$loadavg-100;
1.283     www       425:     if ($overload>0) {
1.285     matthew   426: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       427:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
                    428:         return 413;
                    429:     }    
                    430:     return '';
1.5       www       431: }
1.1       albertel  432: 
                    433: # ------------------------------ Find server with least workload from spare.tab
1.11      www       434: 
1.1       albertel  435: sub spareserver {
1.370     albertel  436:     my ($loadpercent,$userloadpercent) = @_;
1.1       albertel  437:     my $tryserver;
                    438:     my $spareserver='';
1.370     albertel  439:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    440:     my $lowestserver=$loadpercent > $userloadpercent?
                    441: 	             $loadpercent :  $userloadpercent;
1.1       albertel  442:     foreach $tryserver (keys %spareid) {
1.411     albertel  443: 	my $loadans=reply('load',$tryserver);
                    444: 	my $userloadans=reply('userload',$tryserver);
                    445: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    446: 	    next; #didn't get a number from the server
                    447: 	}
                    448: 	my $answer;
                    449: 	if ($loadans =~ /\d/) {
                    450: 	    if ($userloadans =~ /\d/) {
                    451: 		#both are numbers, pick the bigger one
                    452: 		$answer=$loadans > $userloadans?
                    453: 		    $loadans :  $userloadans;
                    454: 	    } else {
                    455: 		$answer = $loadans;
                    456: 	    }
                    457: 	} else {
                    458: 	    $answer = $userloadans;
                    459: 	}
                    460: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
                    461: 	    $spareserver="http://$hostname{$tryserver}";
                    462: 	    $lowestserver=$answer;
                    463: 	}
1.370     albertel  464:     }
1.1       albertel  465:     return $spareserver;
1.202     matthew   466: }
                    467: 
                    468: # --------------------------------------------- Try to change a user's password
                    469: 
                    470: sub changepass {
                    471:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    472:     $currentpass = &escape($currentpass);
                    473:     $newpass     = &escape($newpass);
                    474:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    475: 		       $server);
                    476:     if (! $answer) {
                    477: 	&logthis("No reply on password change request to $server ".
                    478: 		 "by $uname in domain $udom.");
                    479:     } elsif ($answer =~ "^ok") {
                    480:         &logthis("$uname in $udom successfully changed their password ".
                    481: 		 "on $server.");
                    482:     } elsif ($answer =~ "^pwchange_failure") {
                    483: 	&logthis("$uname in $udom was unable to change their password ".
                    484: 		 "on $server.  The action was blocked by either lcpasswd ".
                    485: 		 "or pwchange");
                    486:     } elsif ($answer =~ "^non_authorized") {
                    487:         &logthis("$uname in $udom did not get their password correct when ".
                    488: 		 "attempting to change it on $server.");
                    489:     } elsif ($answer =~ "^auth_mode_error") {
                    490:         &logthis("$uname in $udom attempted to change their password despite ".
                    491: 		 "not being locally or internally authenticated on $server.");
                    492:     } elsif ($answer =~ "^unknown_user") {
                    493:         &logthis("$uname in $udom attempted to change their password ".
                    494: 		 "on $server but were unable to because $server is not ".
                    495: 		 "their home server.");
                    496:     } elsif ($answer =~ "^refused") {
                    497: 	&logthis("$server refused to change $uname in $udom password because ".
                    498: 		 "it was sent an unencrypted request to change the password.");
                    499:     }
                    500:     return $answer;
1.1       albertel  501: }
                    502: 
1.169     harris41  503: # ----------------------- Try to determine user's current authentication scheme
                    504: 
                    505: sub queryauthenticate {
                    506:     my ($uname,$udom)=@_;
                    507:     if (($perlvar{'lonRole'} eq 'library') && 
                    508:         ($udom eq $perlvar{'lonDefDomain'})) {
                    509: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
                    510: 			 $perlvar{'lonHostID'});
                    511: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    512: 	    if (length($answer)) {
                    513: 		return $answer;
                    514: 	    }
                    515: 	    else {
                    516: 	&logthis("User $uname at $udom lacks an authentication mechanism");
                    517: 		return 'no_host';
                    518: 	    }
                    519: 	}
                    520:     }
                    521: 
                    522:     my $tryserver;
                    523:     foreach $tryserver (keys %libserv) {
                    524: 	if ($hostdom{$tryserver} eq $udom) {
                    525:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
                    526: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    527: 	       if (length($answer)) {
                    528: 		   return $answer;
                    529: 	       }
                    530: 	       else {
                    531: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
                    532: 		   return 'no_host';
                    533: 	       }
                    534: 	   }
                    535:        }
                    536:     }
                    537:     &logthis("User $uname at $udom lacks an authentication mechanism");    
                    538:     return 'no_host';
                    539: }
                    540: 
1.1       albertel  541: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       542: 
1.1       albertel  543: sub authenticate {
                    544:     my ($uname,$upass,$udom)=@_;
1.12      www       545:     $upass=escape($upass);
1.199     www       546:     $uname=~s/\W//g;
1.1       albertel  547:     if (($perlvar{'lonRole'} eq 'library') && 
                    548:         ($udom eq $perlvar{'lonDefDomain'})) {
1.3       www       549:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
1.2       www       550:         if ($answer =~ /authorized/) {
1.9       www       551:               if ($answer eq 'authorized') {
                    552:                  &logthis("User $uname at $udom authorized by local server"); 
                    553:                  return $perlvar{'lonHostID'}; 
                    554:               }
                    555:               if ($answer eq 'non_authorized') {
                    556:                  &logthis("User $uname at $udom rejected by local server"); 
                    557:                  return 'no_host'; 
                    558:               }
1.2       www       559: 	}
1.1       albertel  560:     }
                    561: 
                    562:     my $tryserver;
                    563:     foreach $tryserver (keys %libserv) {
                    564: 	if ($hostdom{$tryserver} eq $udom) {
1.10      www       565:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
1.1       albertel  566:            if ($answer =~ /authorized/) {
1.9       www       567:               if ($answer eq 'authorized') {
                    568:                  &logthis("User $uname at $udom authorized by $tryserver"); 
                    569:                  return $tryserver; 
                    570:               }
                    571:               if ($answer eq 'non_authorized') {
                    572:                  &logthis("User $uname at $udom rejected by $tryserver");
                    573:                  return 'no_host';
                    574:               } 
1.1       albertel  575: 	   }
                    576:        }
1.9       www       577:     }
                    578:     &logthis("User $uname at $udom could not be authenticated");    
1.1       albertel  579:     return 'no_host';
                    580: }
                    581: 
                    582: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       583: 
1.1       albertel  584: sub homeserver {
1.230     stredwic  585:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  586:     my $index="$uname:$udom";
1.221     matthew   587:     if ($homecache{$index}) { 
                    588:         return "$homecache{$index}"; 
                    589:     }
1.1       albertel  590:     my $tryserver;
                    591:     foreach $tryserver (keys %libserv) {
1.230     stredwic  592:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  593: 		 exists($badServerCache{$tryserver}));
1.1       albertel  594: 	if ($hostdom{$tryserver} eq $udom) {
                    595:            my $answer=reply("home:$udom:$uname",$tryserver);
                    596:            if ($answer eq 'found') { 
1.221     matthew   597:               $homecache{$index}=$tryserver;
1.1       albertel  598:               return $tryserver; 
1.231     stredwic  599:            } elsif ($answer eq 'no_host') {
                    600: 	       $badServerCache{$tryserver}=1;
1.221     matthew   601:            }
1.1       albertel  602:        }
                    603:     }    
                    604:     return 'no_host';
1.70      www       605: }
                    606: 
                    607: # ------------------------------------- Find the usernames behind a list of IDs
                    608: 
                    609: sub idget {
                    610:     my ($udom,@ids)=@_;
                    611:     my %returnhash=();
                    612:     
                    613:     my $tryserver;
                    614:     foreach $tryserver (keys %libserv) {
                    615:        if ($hostdom{$tryserver} eq $udom) {
                    616: 	  my $idlist=join('&',@ids);
                    617:           $idlist=~tr/A-Z/a-z/; 
                    618: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    619:           my @answer=();
1.76      www       620:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       621: 	      @answer=split(/\&/,$reply);
                    622:           }                    ;
                    623:           my $i;
                    624:           for ($i=0;$i<=$#ids;$i++) {
                    625:               if ($answer[$i]) {
                    626: 		  $returnhash{$ids[$i]}=$answer[$i];
                    627:               } 
                    628:           }
                    629:        }
                    630:     }    
                    631:     return %returnhash;
                    632: }
                    633: 
                    634: # ------------------------------------- Find the IDs behind a list of usernames
                    635: 
                    636: sub idrget {
                    637:     my ($udom,@unames)=@_;
                    638:     my %returnhash=();
1.191     harris41  639:     foreach (@unames) {
1.70      www       640:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  641:     }
1.70      www       642:     return %returnhash;
                    643: }
                    644: 
                    645: # ------------------------------- Store away a list of names and associated IDs
                    646: 
                    647: sub idput {
                    648:     my ($udom,%ids)=@_;
                    649:     my %servers=();
1.191     harris41  650:     foreach (keys %ids) {
1.70      www       651:         my $uhom=&homeserver($_,$udom);
                    652:         if ($uhom ne 'no_host') {
                    653:             my $id=&escape($ids{$_});
                    654:             $id=~tr/A-Z/a-z/;
                    655:             my $unam=&escape($_);
                    656: 	    if ($servers{$uhom}) {
                    657: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    658:             } else {
                    659:                 $servers{$uhom}=$id.'='.$unam;
                    660:             }
                    661:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
                    662:         }
1.191     harris41  663:     }
                    664:     foreach (keys %servers) {
1.70      www       665:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  666:     }
1.344     www       667: }
                    668: 
                    669: # --------------------------------------------------- Assign a key to a student
                    670: 
                    671: sub assign_access_key {
1.364     www       672: #
                    673: # a valid key looks like uname:udom#comments
                    674: # comments are being appended
                    675: #
                    676:     my ($ckey,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1.344     www       677:     $cdom=
                    678:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    679:     $cnum=
                    680:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    681:     $udom=$ENV{'user.name'} unless (defined($udom));
                    682:     $uname=$ENV{'user.domain'} unless (defined($uname));
1.345     www       683:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364     www       684:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
                    685:         ($existing{$ckey}=~/^$uname\:$udom\#(.*)$/)) { 
                    686:                                                   # assigned to this person
                    687:                                                   # - this should not happen,
1.345     www       688:                                                   # unless something went wrong
                    689:                                                   # the first time around
                    690: # ready to assign
1.364     www       691:         $logentry=$1.'; '.$logentry;
                    692:         if (&put('accesskey',{$ckey=>$uname.':'.$udom.'#'.$logentry},
                    693:                                                  $cdom,$cnum) eq 'ok') {
1.345     www       694: # key now belongs to user
1.346     www       695: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       696:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    697:                 &appenv('environment.'.$envkey => $ckey);
                    698:                 return 'ok';
                    699:             } else {
                    700:                 return 
                    701:   'error: Count not permanently assign key, will need to be re-entered later.';
                    702: 	    }
                    703:         } else {
                    704:             return 'error: Could not assign key, try again later.';
                    705:         }
1.364     www       706:     } elsif (!$existing{$ckey}) {
1.345     www       707: # the key does not exist
                    708: 	return 'error: The key does not exist';
                    709:     } else {
                    710: # the key is somebody else's
                    711: 	return 'error: The key is already in use';
                    712:     }
1.344     www       713: }
                    714: 
1.364     www       715: # ------------------------------------------ put an additional comment on a key
                    716: 
                    717: sub comment_access_key {
                    718: #
                    719: # a valid key looks like uname:udom#comments
                    720: # comments are being appended
                    721: #
                    722:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    723:     $cdom=
                    724:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    725:     $cnum=
                    726:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    727:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    728:     if ($existing{$ckey}) {
                    729:         $existing{$ckey}.='; '.$logentry;
                    730: # ready to assign
1.367     www       731:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       732:                                                  $cdom,$cnum) eq 'ok') {
                    733: 	    return 'ok';
                    734:         } else {
                    735: 	    return 'error: Count not store comment.';
                    736:         }
                    737:     } else {
                    738: # the key does not exist
                    739: 	return 'error: The key does not exist';
                    740:     }
                    741: }
                    742: 
1.344     www       743: # ------------------------------------------------------ Generate a set of keys
                    744: 
                    745: sub generate_access_keys {
1.364     www       746:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       747:     $cdom=
                    748:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    749:     $cnum=
                    750:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       751:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       752:     unless (($cdom) && ($cnum)) { return 0; }
                    753:     if ($number>10000) { return 0; }
                    754:     sleep(2); # make sure don't get same seed twice
                    755:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    756:     my $total=0;
                    757:     for (my $i=1;$i<=$number;$i++) {
                    758:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    759:                   sprintf("%lx",int(100000*rand)).'-'.
                    760:                   sprintf("%lx",int(100000*rand));
                    761:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    762:        $newkey=~s/0/h/g; # and also 0 and O
                    763:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    764:        if ($existing{$newkey}) {
                    765:            $i--;
                    766:        } else {
1.364     www       767: 	  if (&put('accesskeys',
                    768:               { $newkey => '# generated '.localtime().
                    769:                            ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
                    770:                            '; '.$logentry },
                    771: 		   $cdom,$cnum) eq 'ok') {
1.344     www       772:               $total++;
                    773: 	  }
                    774:        }
                    775:     }
                    776:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                    777:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    778:     return $total;
                    779: }
                    780: 
                    781: # ------------------------------------------------------- Validate an accesskey
                    782: 
                    783: sub validate_access_key {
                    784:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    785:     $cdom=
                    786:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    787:     $cnum=
                    788:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    789:     $udom=$ENV{'user.name'} unless (defined($udom));
                    790:     $uname=$ENV{'user.domain'} unless (defined($uname));
1.345     www       791:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364     www       792:     return ($existing{$ckey}=~/^$uname\:$udom\#/);
1.70      www       793: }
                    794: 
                    795: # ------------------------------------- Find the section of student in a course
1.298     matthew   796: 
                    797: sub getsection {
                    798:     my ($udom,$unam,$courseid)=@_;
                    799:     $courseid=~s/\_/\//g;
                    800:     $courseid=~s/^(\w)/\/$1/;
                    801:     my %Pending; 
                    802:     my %Expired;
                    803:     #
                    804:     # Each role can either have not started yet (pending), be active, 
                    805:     #    or have expired.
                    806:     #
                    807:     # If there is an active role, we are done.
                    808:     #
                    809:     # If there is more than one role which has not started yet, 
                    810:     #     choose the one which will start sooner
                    811:     # If there is one role which has not started yet, return it.
                    812:     #
                    813:     # If there is more than one expired role, choose the one which ended last.
                    814:     # If there is a role which has expired, return it.
                    815:     #
                    816:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    817:                         &homeserver($unam,$udom)))) {
                    818:         my ($key,$value)=split(/\=/,$_);
                    819:         $key=&unescape($key);
                    820:         next if ($key !~/^$courseid(?:\/)*(\w+)*\_st$/);
                    821:         my $section=$1;
                    822:         if ($key eq $courseid.'_st') { $section=''; }
                    823:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    824:         my $now=time;
                    825:         if (defined($end) && ($now > $end)) {
                    826:             $Expired{$end}=$section;
                    827:             next;
                    828:         }
                    829:         if (defined($start) && ($now < $start)) {
                    830:             $Pending{$start}=$section;
                    831:             next;
                    832:         }
                    833:         return $section;
                    834:     }
                    835:     #
                    836:     # Presumedly there will be few matching roles from the above
                    837:     # loop and the sorting time will be negligible.
                    838:     if (scalar(keys(%Pending))) {
                    839:         my ($time) = sort {$a <=> $b} keys(%Pending);
                    840:         return $Pending{$time};
                    841:     } 
                    842:     if (scalar(keys(%Expired))) {
                    843:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    844:         my $time = pop(@sorted);
                    845:         return $Expired{$time};
                    846:     }
                    847:     return '-1';
                    848: }
1.70      www       849: 
                    850: sub usection {
                    851:     my ($udom,$unam,$courseid)=@_;
                    852:     $courseid=~s/\_/\//g;
                    853:     $courseid=~s/^(\w)/\/$1/;
1.191     harris41  854:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    855:                         &homeserver($unam,$udom)))) {
1.70      www       856:         my ($key,$value)=split(/\=/,$_);
                    857:         $key=&unescape($key);
                    858:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
                    859:             my $section=$1;
                    860:             if ($key eq $courseid.'_st') { $section=''; }
                    861: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    862:             my $now=time;
                    863:             my $notactive=0;
                    864:             if ($start) {
                    865: 		if ($now<$start) { $notactive=1; }
                    866:             }
                    867:             if ($end) {
                    868:                 if ($now>$end) { $notactive=1; }
                    869:             } 
                    870:             unless ($notactive) { return $section; }
                    871:         }
1.191     harris41  872:     }
1.70      www       873:     return '-1';
                    874: }
                    875: 
                    876: # ------------------------------------- Read an entry from a user's environment
                    877: 
                    878: sub userenvironment {
                    879:     my ($udom,$unam,@what)=@_;
                    880:     my %returnhash=();
                    881:     my @answer=split(/\&/,
                    882:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    883:                       &homeserver($unam,$udom)));
                    884:     my $i;
                    885:     for ($i=0;$i<=$#what;$i++) {
                    886: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    887:     }
                    888:     return %returnhash;
1.1       albertel  889: }
                    890: 
1.263     www       891: # -------------------------------------------------------------------- New chat
                    892: 
                    893: sub chatsend {
                    894:     my ($newentry,$anon)=@_;
                    895:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                    896:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                    897:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                    898:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
                    899: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
                    900: 		   &escape($newentry)),$chome);
1.292     www       901: }
                    902: 
                    903: # ------------------------------------------ Find current version of a resource
                    904: 
                    905: sub getversion {
                    906:     my $fname=&clutter(shift);
                    907:     unless ($fname=~/^\/res\//) { return -1; }
                    908:     return &currentversion(&filelocation('',$fname));
                    909: }
                    910: 
                    911: sub currentversion {
                    912:     my $fname=shift;
                    913:     my $author=$fname;
                    914:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    915:     my ($udom,$uname)=split(/\//,$author);
                    916:     my $home=homeserver($uname,$udom);
                    917:     if ($home eq 'no_host') { 
                    918:         return -1; 
                    919:     }
                    920:     my $answer=reply("currentversion:$fname",$home);
                    921:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    922: 	return -1;
                    923:     }
                    924:     return $answer;
1.263     www       925: }
                    926: 
1.1       albertel  927: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www       928: 
1.1       albertel  929: sub subscribe {
                    930:     my $fname=shift;
1.312     www       931:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.1       albertel  932:     my $author=$fname;
                    933:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    934:     my ($udom,$uname)=split(/\//,$author);
                    935:     my $home=homeserver($uname,$udom);
1.335     albertel  936:     if ($home eq 'no_host') {
                    937:         return 'not_found';
1.1       albertel  938:     }
                    939:     my $answer=reply("sub:$fname",$home);
1.64      www       940:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    941: 	$answer.=' by '.$home;
                    942:     }
1.1       albertel  943:     return $answer;
                    944: }
                    945:     
1.8       www       946: # -------------------------------------------------------------- Replicate file
                    947: 
                    948: sub repcopy {
                    949:     my $filename=shift;
1.23      www       950:     $filename=~s/\/+/\//g;
1.214     www       951:     if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
1.8       www       952:     my $transname="$filename.in.transfer";
1.17      www       953:     if ((-e $filename) || (-e $transname)) { return OK; }
1.8       www       954:     my $remoteurl=subscribe($filename);
1.64      www       955:     if ($remoteurl =~ /^con_lost by/) {
                    956: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       957:            return HTTP_SERVICE_UNAVAILABLE;
                    958:     } elsif ($remoteurl eq 'not_found') {
                    959: 	   &logthis("Subscribe returned not_found: $filename");
                    960: 	   return HTTP_NOT_FOUND;
1.64      www       961:     } elsif ($remoteurl =~ /^rejected by/) {
                    962: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       963:            return FORBIDDEN;
1.20      www       964:     } elsif ($remoteurl eq 'directory') {
                    965:            return OK;
1.8       www       966:     } else {
1.290     www       967:         my $author=$filename;
                    968:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    969:         my ($udom,$uname)=split(/\//,$author);
                    970:         my $home=homeserver($uname,$udom);
                    971:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www       972:            my @parts=split(/\//,$filename);
                    973:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                    974:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                    975:                &logthis("Malconfiguration for replication: $filename");
                    976: 	       return HTTP_BAD_REQUEST;
                    977:            }
                    978:            my $count;
                    979:            for ($count=5;$count<$#parts;$count++) {
                    980:                $path.="/$parts[$count]";
                    981:                if ((-e $path)!=1) {
                    982: 		   mkdir($path,0777);
                    983:                }
                    984:            }
                    985:            my $ua=new LWP::UserAgent;
                    986:            my $request=new HTTP::Request('GET',"$remoteurl");
                    987:            my $response=$ua->request($request,$transname);
                    988:            if ($response->is_error()) {
                    989: 	       unlink($transname);
                    990:                my $message=$response->status_line;
1.12      www       991:                &logthis("<font color=blue>WARNING:"
                    992:                        ." LWP get: $message: $filename</font>");
1.8       www       993:                return HTTP_SERVICE_UNAVAILABLE;
                    994:            } else {
1.16      www       995: 	       if ($remoteurl!~/\.meta$/) {
                    996:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                    997:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                    998:                   if ($mresponse->is_error()) {
                    999: 		      unlink($filename.'.meta');
                   1000:                       &logthis(
                   1001:                      "<font color=yellow>INFO: No metadata: $filename</font>");
                   1002:                   }
                   1003: 	       }
1.8       www      1004:                rename($transname,$filename);
                   1005:                return OK;
                   1006:            }
1.290     www      1007:        }
1.8       www      1008:     }
1.330     www      1009: }
                   1010: 
                   1011: # ------------------------------------------------ Get server side include body
                   1012: sub ssi_body {
1.381     albertel 1013:     my ($filelink,%form)=@_;
1.330     www      1014:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1015:                                      &ssi($filelink,%form));
1.330     www      1016:     $output=~s/^.*\<body[^\>]*\>//si;
                   1017:     $output=~s/\<\/body\s*\>.*$//si;
1.331     www      1018:     $output=~
                   1019:             s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
1.330     www      1020:     return $output;
1.8       www      1021: }
                   1022: 
1.15      www      1023: # --------------------------------------------------------- Server Side Include
                   1024: 
                   1025: sub ssi {
                   1026: 
1.23      www      1027:     my ($fn,%form)=@_;
1.15      www      1028: 
                   1029:     my $ua=new LWP::UserAgent;
1.23      www      1030:     
                   1031:     my $request;
                   1032:     
                   1033:     if (%form) {
                   1034:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1035:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1036:     } else {
                   1037:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1038:     }
                   1039: 
1.15      www      1040:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1041:     my $response=$ua->request($request);
                   1042: 
1.324     www      1043:     return $response->content;
                   1044: }
                   1045: 
                   1046: sub externalssi {
                   1047:     my ($url)=@_;
                   1048:     my $ua=new LWP::UserAgent;
                   1049:     my $request=new HTTP::Request('GET',$url);
                   1050:     my $response=$ua->request($request);
1.15      www      1051:     return $response->content;
                   1052: }
1.254     www      1053: 
                   1054: # ------- Add a token to a remote URI's query string to vouch for access rights
                   1055: 
                   1056: sub tokenwrapper {
                   1057:     my $uri=shift;
1.259     www      1058:     $uri=~s/^http\:\/\/([^\/]+)//;
                   1059:     $uri=~s/^\///;
                   1060:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
                   1061:     my $token=$1;
                   1062:     if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
                   1063: 	&appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
                   1064:         return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
1.304     www      1065:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   1066:                                '&tokenissued='.$perlvar{'lonHostID'};
1.259     www      1067:     } else {
                   1068: 	return '/adm/notfound.html';
                   1069:     }
1.254     www      1070: }
                   1071:     
1.257     www      1072: # --------------- Take an uploaded file and put it into the userfiles directory
1.259     www      1073: # input: name of form element, coursedoc=1 means this is for the course
1.257     www      1074: # output: url of file in userspace
                   1075: 
                   1076: sub userfileupload {
1.259     www      1077:     my ($formname,$coursedoc)=@_;
1.257     www      1078:     my $fname=$ENV{'form.'.$formname.'.filename'};
1.315     www      1079: # Replace Windows backslashes by forward slashes
1.257     www      1080:     $fname=~s/\\/\//g;
1.315     www      1081: # Get rid of everything but the actual filename
1.257     www      1082:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1083: # Replace spaces by underscores
                   1084:     $fname=~s/\s+/\_/g;
                   1085: # Replace all other weird characters by nothing
1.317     www      1086:     $fname=~s/[^\w\.\-]//g;
1.315     www      1087: # See if there is anything left
1.257     www      1088:     unless ($fname) { return 'error: no uploaded file'; }
                   1089:     chop($ENV{'form.'.$formname});
1.258     www      1090: # Create the directory if not present
1.259     www      1091:     my $docuname='';
                   1092:     my $docudom='';
                   1093:     my $docuhome='';
                   1094:     if ($coursedoc) {
                   1095: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1096: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1097: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                   1098:     } else {
                   1099:         $docuname=$ENV{'user.name'};
                   1100:         $docudom=$ENV{'user.domain'};
                   1101:         $docuhome=$ENV{'user.home'};
                   1102:     }
1.271     www      1103:     return 
                   1104:         &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
                   1105: }
                   1106: 
                   1107: sub finishuserfileupload {
                   1108:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
1.259     www      1109:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1110:     my $filepath=$perlvar{'lonDocRoot'};
1.259     www      1111:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1112:     my $count;
                   1113:     for ($count=4;$count<=$#parts;$count++) {
                   1114:         $filepath.="/$parts[$count]";
                   1115:         if ((-e $filepath)!=1) {
                   1116: 	    mkdir($filepath,0777);
                   1117:         }
                   1118:     }
                   1119: # Save the file
                   1120:     {
                   1121:        my $fh=Apache::File->new('>'.$filepath.'/'.$fname);
                   1122:        print $fh $ENV{'form.'.$formname};
                   1123:     }
1.259     www      1124: # Notify homeserver to grep it
                   1125: #
1.295     www      1126:     
                   1127:     my $fetchresult= 
                   1128:  &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
                   1129:     if ($fetchresult eq 'ok') {
1.259     www      1130: #
1.258     www      1131: # Return the URL to it
1.263     www      1132:         return '/uploaded/'.$path.$fname;
                   1133:     } else {
1.295     www      1134:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
                   1135:          ' to host '.$docuhome.': '.$fetchresult);
1.263     www      1136:         return '/adm/notfound.html';
                   1137:     }    
1.257     www      1138: }
1.15      www      1139: 
1.14      www      1140: # ------------------------------------------------------------------------- Log
                   1141: 
                   1142: sub log {
                   1143:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1144:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1145: }
                   1146: 
                   1147: # ------------------------------------------------------------------ Course Log
1.352     www      1148: #
                   1149: # This routine flushes several buffers of non-mission-critical nature
                   1150: #
1.157     www      1151: 
                   1152: sub flushcourselogs {
1.352     www      1153:     &logthis('Flushing log buffers');
                   1154: #
                   1155: # course logs
                   1156: # This is a log of all transactions in a course, which can be used
                   1157: # for data mining purposes
                   1158: #
                   1159: # It also collects the courseid database, which lists last transaction
                   1160: # times and course titles for all courseids
                   1161: #
                   1162:     my %courseidbuffer=();
1.191     harris41 1163:     foreach (keys %courselogs) {
1.157     www      1164:         my $crsid=$_;
1.352     www      1165:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1166: 		          &escape($courselogs{$crsid}),
                   1167: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1168: 	    delete $courselogs{$crsid};
                   1169:         } else {
                   1170:             &logthis('Failed to flush log buffer for '.$crsid);
                   1171:             if (length($courselogs{$crsid})>40000) {
                   1172:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
                   1173:                         " exceeded maximum size, deleting.</font>");
                   1174:                delete $courselogs{$crsid};
                   1175:             }
1.352     www      1176:         }
                   1177:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1178:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
                   1179: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
                   1180:         } else {
                   1181:            $courseidbuffer{$coursehombuf{$crsid}}=
                   1182: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
                   1183:         }    
1.191     harris41 1184:     }
1.352     www      1185: #
                   1186: # Write course id database (reverse lookup) to homeserver of courses 
                   1187: # Is used in pickcourse
                   1188: #
                   1189:     foreach (keys %courseidbuffer) {
1.353     www      1190:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1191:     }
                   1192: #
                   1193: # File accesses
                   1194: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1195: #
1.191     harris41 1196:     foreach (keys %accesshash) {
1.185     www      1197:         my $entry=$_;
                   1198:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
                   1199:         my %temphash=($entry => $accesshash{$entry});
1.266     albertel 1200:         if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
1.185     www      1201: 	    delete $accesshash{$entry};
                   1202:         }
1.191     harris41 1203:     }
1.352     www      1204: #
                   1205: # Roles
                   1206: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1207: #
1.349     www      1208:     foreach (keys %userrolehash) {
                   1209:         my $entry=$_;
1.351     www      1210:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1211: 	    split(/\:/,$entry);
                   1212:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1213:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1214:                 $rudom,$runame) eq 'ok') {
                   1215: 	    delete $userrolehash{$entry};
                   1216:         }
                   1217:     }
1.186     www      1218:     $dumpcount++;
1.157     www      1219: }
                   1220: 
                   1221: sub courselog {
                   1222:     my $what=shift;
1.158     www      1223:     $what=time.':'.$what;
1.157     www      1224:     unless ($ENV{'request.course.id'}) { return ''; }
1.188     www      1225:     $coursedombuf{$ENV{'request.course.id'}}=
1.352     www      1226:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1227:     $coursenumbuf{$ENV{'request.course.id'}}=
1.188     www      1228:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1229:     $coursehombuf{$ENV{'request.course.id'}}=
                   1230:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.352     www      1231:     $coursedescrbuf{$ENV{'request.course.id'}}=
                   1232:        $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.157     www      1233:     if (defined $courselogs{$ENV{'request.course.id'}}) {
                   1234: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
                   1235:     } else {
                   1236: 	$courselogs{$ENV{'request.course.id'}}.=$what;
                   1237:     }
                   1238:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
                   1239: 	&flushcourselogs();
                   1240:     }
1.158     www      1241: }
                   1242: 
                   1243: sub courseacclog {
                   1244:     my $fnsymb=shift;
                   1245:     unless ($ENV{'request.course.id'}) { return ''; }
                   1246:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.408     www      1247:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) {
1.187     www      1248:         $what.=':POST';
1.191     harris41 1249: 	foreach (keys %ENV) {
1.158     www      1250:             if ($_=~/^form\.(.*)/) {
                   1251: 		$what.=':'.$1.'='.$ENV{$_};
                   1252:             }
1.191     harris41 1253:         }
1.158     www      1254:     }
                   1255:     &courselog($what);
1.149     www      1256: }
                   1257: 
1.185     www      1258: sub countacc {
                   1259:     my $url=&declutter(shift);
                   1260:     unless ($ENV{'request.course.id'}) { return ''; }
                   1261:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1262:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.185     www      1263:     if (defined($accesshash{$key})) {
                   1264: 	$accesshash{$key}++;
                   1265:     } else {
                   1266:         $accesshash{$key}=1;
                   1267:     }
                   1268: }
1.349     www      1269: 
1.361     www      1270: sub linklog {
                   1271:     my ($from,$to)=@_;
                   1272:     $from=&declutter($from);
                   1273:     $to=&declutter($to);
                   1274:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1275:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1276: }
                   1277:   
1.349     www      1278: sub userrolelog {
                   1279:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
                   1280:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
                   1281:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   1282:         ($trole=~/^cr/)) {
1.350     www      1283:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1284:        $userrolehash
                   1285:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1286:                     =$tend.':'.$tstart;
                   1287:    }
1.351     www      1288: }
                   1289: 
                   1290: sub get_course_adv_roles {
                   1291:     my $cid=shift;
                   1292:     $cid=$ENV{'request.course.id'} unless (defined($cid));
                   1293:     my %coursehash=&coursedescription($cid);
                   1294:     my %returnhash=();
                   1295:     my %dumphash=
                   1296:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1297:     my $now=time;
                   1298:     foreach (keys %dumphash) {
                   1299: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1300:         if (($tstart) && ($tstart<0)) { next; }
                   1301:         if (($tend) && ($tend<$now)) { next; }
                   1302:         if (($tstart) && ($now<$tstart)) { next; }
                   1303:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1304:         my $key=&plaintext($role);
                   1305:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1306:         if ($returnhash{$key}) {
                   1307: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1308:         } else {
                   1309:             $returnhash{$key}=$username.':'.$domain;
                   1310:         }
1.400     www      1311:      }
                   1312:     return %returnhash;
                   1313: }
                   1314: 
                   1315: sub get_my_roles {
                   1316:     my ($uname,$udom)=@_;
                   1317:     unless (defined($uname)) { $uname=$ENV{'user.name'}; }
                   1318:     unless (defined($udom)) { $udom=$ENV{'user.domain'}; }
                   1319:     my %dumphash=
                   1320:             &dump('nohist_userroles',$udom,$uname);
                   1321:     my %returnhash=();
                   1322:     my $now=time;
                   1323:     foreach (keys %dumphash) {
                   1324: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1325:         if (($tstart) && ($tstart<0)) { next; }
                   1326:         if (($tend) && ($tend<$now)) { next; }
                   1327:         if (($tstart) && ($now<$tstart)) { next; }
                   1328:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1329: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1330:      }
                   1331:     return %returnhash;
1.399     www      1332: }
                   1333: 
                   1334: # ----------------------------------------------------- Frontpage Announcements
                   1335: #
                   1336: #
                   1337: 
                   1338: sub postannounce {
                   1339:     my ($server,$text)=@_;
                   1340:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1341:     unless ($text=~/\w/) { $text=''; }
                   1342:     return &reply('setannounce:'.&escape($text),$server);
                   1343: }
                   1344: 
                   1345: sub getannounce {
                   1346:     if (my $fh=Apache::File->new($perlvar{'lonDocRoot'}.'/announcement.txt')) {
                   1347: 	my $announcement='';
                   1348: 	while (<$fh>) { $announcement .=$_; }
                   1349: 	$fh->close();
                   1350: 	if ($announcement=~/\w/) { 
                   1351: 	    return 
                   1352:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
                   1353:    '<tr><td bgcolor="#FFFFFF"><pre>'.$announcement.'</pre></td></tr></table>'; 
                   1354: 	} else {
                   1355: 	    return '';
                   1356: 	}
                   1357:     } else {
                   1358: 	return '';
                   1359:     }
1.351     www      1360: }
1.353     www      1361: 
                   1362: # ---------------------------------------------------------- Course ID routines
                   1363: # Deal with domain's nohist_courseid.db files
                   1364: #
                   1365: 
                   1366: sub courseidput {
                   1367:     my ($domain,$what,$coursehome)=@_;
                   1368:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1369: }
                   1370: 
                   1371: sub courseiddump {
                   1372:     my ($domfilter,$descfilter,$sincefilter)=@_;
                   1373:     my %returnhash=();
1.355     www      1374:     unless ($domfilter) { $domfilter=''; }
1.353     www      1375:     foreach my $tryserver (keys %libserv) {
1.355     www      1376: 	if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.353     www      1377: 	    foreach (
                   1378:              split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.354     www      1379: 			       $sincefilter.':'.&escape($descfilter),
                   1380:                                $tryserver))) {
1.353     www      1381: 		my ($key,$value)=split(/\=/,$_);
                   1382:                 if (($key) && ($value)) {
                   1383: 		    $returnhash{&unescape($key)}=&unescape($value);
                   1384:                 }
                   1385:             }
                   1386: 
                   1387:         }
                   1388:     }
                   1389:     return %returnhash;
                   1390: }
                   1391: 
                   1392: #
1.149     www      1393: # ----------------------------------------------------------- Check out an item
                   1394: 
                   1395: sub checkout {
                   1396:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   1397:     my $now=time;
                   1398:     my $lonhost=$perlvar{'lonHostID'};
                   1399:     my $infostr=&escape(
1.234     www      1400:                  'CHECKOUTTOKEN&'.
1.149     www      1401:                  $tuname.'&'.
                   1402:                  $tudom.'&'.
                   1403:                  $tcrsid.'&'.
                   1404:                  $symb.'&'.
                   1405: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   1406:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      1407:     if ($token=~/^error\:/) { 
                   1408:         &logthis("<font color=blue>WARNING: ".
                   1409:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1410:                  "</font>");
                   1411:         return ''; 
                   1412:     }
                   1413: 
1.149     www      1414:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   1415:     $token=~tr/a-z/A-Z/;
                   1416: 
1.153     www      1417:     my %infohash=('resource.0.outtoken' => $token,
                   1418:                   'resource.0.checkouttime' => $now,
                   1419:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      1420: 
                   1421:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1422:        return '';
1.151     www      1423:     } else {
                   1424:         &logthis("<font color=blue>WARNING: ".
                   1425:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1426:                  "</font>");
1.149     www      1427:     }    
                   1428: 
                   1429:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1430:                          &escape('Checkout '.$infostr.' - '.
                   1431:                                                  $token)) ne 'ok') {
                   1432: 	return '';
1.151     www      1433:     } else {
                   1434:         &logthis("<font color=blue>WARNING: ".
                   1435:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1436:                  "</font>");
1.149     www      1437:     }
1.151     www      1438:     return $token;
1.149     www      1439: }
                   1440: 
                   1441: # ------------------------------------------------------------ Check in an item
                   1442: 
                   1443: sub checkin {
                   1444:     my $token=shift;
1.150     www      1445:     my $now=time;
                   1446:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   1447:     $lonhost=~tr/A-Z/a-z/;
                   1448:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
                   1449:     $dtoken=~s/\W/\_/g;
1.234     www      1450:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      1451:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   1452: 
1.154     www      1453:     unless (($tuname) && ($tudom)) {
                   1454:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   1455:         return '';
                   1456:     }
                   1457:     
                   1458:     unless (&allowed('mgr',$tcrsid)) {
                   1459:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   1460:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
                   1461:         return '';
                   1462:     }
                   1463: 
1.153     www      1464:     my %infohash=('resource.0.intoken' => $token,
                   1465:                   'resource.0.checkintime' => $now,
                   1466:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      1467: 
                   1468:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1469:        return '';
                   1470:     }    
                   1471: 
                   1472:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1473:                          &escape('Checkin - '.$token)) ne 'ok') {
                   1474: 	return '';
                   1475:     }
                   1476: 
                   1477:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      1478: }
                   1479: 
                   1480: # --------------------------------------------- Set Expire Date for Spreadsheet
                   1481: 
                   1482: sub expirespread {
                   1483:     my ($uname,$udom,$stype,$usymb)=@_;
                   1484:     my $cid=$ENV{'request.course.id'}; 
                   1485:     if ($cid) {
                   1486:        my $now=time;
                   1487:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
                   1488:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
                   1489:                             $ENV{'course.'.$cid.'.num'}.
                   1490: 	        	    ':nohist_expirationdates:'.
                   1491:                             &escape($key).'='.$now,
                   1492:                             $ENV{'course.'.$cid.'.home'})
                   1493:     }
                   1494:     return 'ok';
1.14      www      1495: }
                   1496: 
1.109     www      1497: # ----------------------------------------------------- Devalidate Spreadsheets
                   1498: 
                   1499: sub devalidate {
1.325     www      1500:     my ($symb,$uname,$udom)=@_;
1.109     www      1501:     my $cid=$ENV{'request.course.id'}; 
                   1502:     if ($cid) {
1.391     matthew  1503:         # delete the stored spreadsheets for
                   1504:         # - the student level sheet of this user in course's homespace
                   1505:         # - the assessment level sheet for this resource 
                   1506:         #   for this user in user's homespace
1.325     www      1507: 	my $key=$uname.':'.$udom.':';
1.109     www      1508:         my $status=
1.299     matthew  1509: 	    &del('nohist_calculatedsheets',
1.391     matthew  1510: 		 [$key.'studentcalc:'],
1.133     albertel 1511: 		 $ENV{'course.'.$cid.'.domain'},
                   1512: 		 $ENV{'course.'.$cid.'.num'})
                   1513: 		.' '.
                   1514: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  1515: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      1516:         unless ($status eq 'ok ok') {
                   1517:            &logthis('Could not devalidate spreadsheet '.
1.325     www      1518:                     $uname.' at '.$udom.' for '.
1.109     www      1519: 		    $symb.': '.$status);
1.133     albertel 1520:         }
1.109     www      1521:     }
                   1522: }
                   1523: 
1.265     albertel 1524: sub get_scalar {
                   1525:     my ($string,$end) = @_;
                   1526:     my $value;
                   1527:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   1528: 	$value = $1;
                   1529:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   1530: 	$value = $1;
                   1531:     }
                   1532:     return &unescape($value);
                   1533: }
                   1534: 
                   1535: sub array2str {
                   1536:   my (@array) = @_;
                   1537:   my $result=&arrayref2str(\@array);
                   1538:   $result=~s/^__ARRAY_REF__//;
                   1539:   $result=~s/__END_ARRAY_REF__$//;
                   1540:   return $result;
                   1541: }
                   1542: 
1.204     albertel 1543: sub arrayref2str {
                   1544:   my ($arrayref) = @_;
1.265     albertel 1545:   my $result='__ARRAY_REF__';
1.204     albertel 1546:   foreach my $elem (@$arrayref) {
1.265     albertel 1547:     if(ref($elem) eq 'ARRAY') {
                   1548:       $result.=&arrayref2str($elem).'&';
                   1549:     } elsif(ref($elem) eq 'HASH') {
                   1550:       $result.=&hashref2str($elem).'&';
                   1551:     } elsif(ref($elem)) {
                   1552:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 1553:     } else {
                   1554:       $result.=&escape($elem).'&';
                   1555:     }
                   1556:   }
                   1557:   $result=~s/\&$//;
1.265     albertel 1558:   $result .= '__END_ARRAY_REF__';
1.204     albertel 1559:   return $result;
                   1560: }
                   1561: 
1.168     albertel 1562: sub hash2str {
1.204     albertel 1563:   my (%hash) = @_;
                   1564:   my $result=&hashref2str(\%hash);
1.265     albertel 1565:   $result=~s/^__HASH_REF__//;
                   1566:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 1567:   return $result;
                   1568: }
                   1569: 
                   1570: sub hashref2str {
                   1571:   my ($hashref)=@_;
1.265     albertel 1572:   my $result='__HASH_REF__';
1.204     albertel 1573:   foreach (keys(%$hashref)) {
                   1574:     if (ref($_) eq 'ARRAY') {
1.265     albertel 1575:       $result.=&arrayref2str($_).'=';
1.204     albertel 1576:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 1577:       $result.=&hashref2str($_).'=';
1.204     albertel 1578:     } elsif (ref($_)) {
1.265     albertel 1579:       $result.='=';
                   1580:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 1581:     } else {
1.265     albertel 1582: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 1583:     }
                   1584: 
1.265     albertel 1585:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   1586:       $result.=&arrayref2str($hashref->{$_}).'&';
                   1587:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   1588:       $result.=&hashref2str($hashref->{$_}).'&';
                   1589:     } elsif(ref($hashref->{$_})) {
                   1590:        $result.='&';
                   1591:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 1592:     } else {
1.265     albertel 1593:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 1594:     }
                   1595:   }
1.168     albertel 1596:   $result=~s/\&$//;
1.265     albertel 1597:   $result .= '__END_HASH_REF__';
1.168     albertel 1598:   return $result;
                   1599: }
                   1600: 
                   1601: sub str2hash {
1.265     albertel 1602:     my ($string)=@_;
                   1603:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   1604:     return %$hash;
                   1605: }
                   1606: 
                   1607: sub str2hashref {
1.168     albertel 1608:   my ($string) = @_;
1.265     albertel 1609: 
                   1610:   my %hash;
                   1611: 
                   1612:   if($string !~ /^__HASH_REF__/) {
                   1613:       if (! ($string eq '' || !defined($string))) {
                   1614: 	  $hash{'error'}='Not hash reference';
                   1615:       }
                   1616:       return (\%hash, $string);
                   1617:   }
                   1618: 
                   1619:   $string =~ s/^__HASH_REF__//;
                   1620: 
                   1621:   while($string !~ /^__END_HASH_REF__/) {
                   1622:       #key
                   1623:       my $key='';
                   1624:       if($string =~ /^__HASH_REF__/) {
                   1625:           ($key, $string)=&str2hashref($string);
                   1626:           if(defined($key->{'error'})) {
                   1627:               $hash{'error'}='Bad data';
                   1628:               return (\%hash, $string);
                   1629:           }
                   1630:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1631:           ($key, $string)=&str2arrayref($string);
                   1632:           if($key->[0] eq 'Array reference error') {
                   1633:               $hash{'error'}='Bad data';
                   1634:               return (\%hash, $string);
                   1635:           }
                   1636:       } else {
                   1637:           $string =~ s/^(.*?)=//;
1.267     albertel 1638: 	  $key=&unescape($1);
1.265     albertel 1639:       }
                   1640:       $string =~ s/^=//;
                   1641: 
                   1642:       #value
                   1643:       my $value='';
                   1644:       if($string =~ /^__HASH_REF__/) {
                   1645:           ($value, $string)=&str2hashref($string);
                   1646:           if(defined($value->{'error'})) {
                   1647:               $hash{'error'}='Bad data';
                   1648:               return (\%hash, $string);
                   1649:           }
                   1650:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1651:           ($value, $string)=&str2arrayref($string);
                   1652:           if($value->[0] eq 'Array reference error') {
                   1653:               $hash{'error'}='Bad data';
                   1654:               return (\%hash, $string);
                   1655:           }
                   1656:       } else {
                   1657: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   1658:       }
                   1659:       $string =~ s/^&//;
                   1660: 
                   1661:       $hash{$key}=$value;
1.204     albertel 1662:   }
1.265     albertel 1663: 
                   1664:   $string =~ s/^__END_HASH_REF__//;
                   1665: 
                   1666:   return (\%hash, $string);
1.204     albertel 1667: }
                   1668: 
                   1669: sub str2array {
1.265     albertel 1670:     my ($string)=@_;
                   1671:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   1672:     return @$array;
                   1673: }
                   1674: 
                   1675: sub str2arrayref {
1.204     albertel 1676:   my ($string) = @_;
1.265     albertel 1677:   my @array;
                   1678: 
                   1679:   if($string !~ /^__ARRAY_REF__/) {
                   1680:       if (! ($string eq '' || !defined($string))) {
                   1681: 	  $array[0]='Array reference error';
                   1682:       }
                   1683:       return (\@array, $string);
                   1684:   }
                   1685: 
                   1686:   $string =~ s/^__ARRAY_REF__//;
                   1687: 
                   1688:   while($string !~ /^__END_ARRAY_REF__/) {
                   1689:       my $value='';
                   1690:       if($string =~ /^__HASH_REF__/) {
                   1691:           ($value, $string)=&str2hashref($string);
                   1692:           if(defined($value->{'error'})) {
                   1693:               $array[0] ='Array reference error';
                   1694:               return (\@array, $string);
                   1695:           }
                   1696:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1697:           ($value, $string)=&str2arrayref($string);
                   1698:           if($value->[0] eq 'Array reference error') {
                   1699:               $array[0] ='Array reference error';
                   1700:               return (\@array, $string);
                   1701:           }
                   1702:       } else {
                   1703: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   1704:       }
                   1705:       $string =~ s/^&//;
                   1706: 
                   1707:       push(@array, $value);
1.191     harris41 1708:   }
1.265     albertel 1709: 
                   1710:   $string =~ s/^__END_ARRAY_REF__//;
                   1711: 
                   1712:   return (\@array, $string);
1.168     albertel 1713: }
                   1714: 
1.167     albertel 1715: # -------------------------------------------------------------------Temp Store
                   1716: 
1.168     albertel 1717: sub tmpreset {
                   1718:   my ($symb,$namespace,$domain,$stuname) = @_;
                   1719:   if (!$symb) {
                   1720:     $symb=&symbread();
1.380     albertel 1721:     if (!$symb) { $symb= $ENV{'request.url'}; }
1.168     albertel 1722:   }
                   1723:   $symb=escape($symb);
                   1724: 
                   1725:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1726:   $namespace=~s/\//\_/g;
                   1727:   $namespace=~s/\W//g;
                   1728: 
                   1729:   #FIXME needs to do something for /pub resources
                   1730:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1731:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1732:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1733:   my %hash;
                   1734:   if (tie(%hash,'GDBM_File',
                   1735: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1736: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1737:     foreach my $key (keys %hash) {
1.180     albertel 1738:       if ($key=~ /:$symb/) {
1.168     albertel 1739: 	delete($hash{$key});
                   1740:       }
                   1741:     }
                   1742:   }
                   1743: }
                   1744: 
1.167     albertel 1745: sub tmpstore {
1.168     albertel 1746:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1747: 
                   1748:   if (!$symb) {
                   1749:     $symb=&symbread();
                   1750:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1751:   }
                   1752:   $symb=escape($symb);
                   1753: 
                   1754:   if (!$namespace) {
                   1755:     # I don't think we would ever want to store this for a course.
                   1756:     # it seems this will only be used if we don't have a course.
                   1757:     #$namespace=$ENV{'request.course.id'};
                   1758:     #if (!$namespace) {
                   1759:       $namespace=$ENV{'request.state'};
                   1760:     #}
                   1761:   }
                   1762:   $namespace=~s/\//\_/g;
                   1763:   $namespace=~s/\W//g;
                   1764: #FIXME needs to do something for /pub resources
                   1765:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1766:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1767:   my $now=time;
                   1768:   my %hash;
                   1769:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1770:   if (tie(%hash,'GDBM_File',
                   1771: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1772: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1773:     $hash{"version:$symb"}++;
                   1774:     my $version=$hash{"version:$symb"};
                   1775:     my $allkeys=''; 
                   1776:     foreach my $key (keys(%$storehash)) {
                   1777:       $allkeys.=$key.':';
                   1778:       $hash{"$version:$symb:$key"}=$$storehash{$key};
                   1779:     }
                   1780:     $hash{"$version:$symb:timestamp"}=$now;
                   1781:     $allkeys.='timestamp';
                   1782:     $hash{"$version:keys:$symb"}=$allkeys;
                   1783:     if (untie(%hash)) {
                   1784:       return 'ok';
                   1785:     } else {
                   1786:       return "error:$!";
                   1787:     }
                   1788:   } else {
                   1789:     return "error:$!";
                   1790:   }
                   1791: }
1.167     albertel 1792: 
1.168     albertel 1793: # -----------------------------------------------------------------Temp Restore
1.167     albertel 1794: 
1.168     albertel 1795: sub tmprestore {
                   1796:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 1797: 
1.168     albertel 1798:   if (!$symb) {
                   1799:     $symb=&symbread();
                   1800:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1801:   }
                   1802:   $symb=escape($symb);
                   1803: 
                   1804:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1805:   #FIXME needs to do something for /pub resources
                   1806:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1807:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1808: 
                   1809:   my %returnhash;
                   1810:   $namespace=~s/\//\_/g;
                   1811:   $namespace=~s/\W//g;
                   1812:   my %hash;
                   1813:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1814:   if (tie(%hash,'GDBM_File',
                   1815: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1816: 	  &GDBM_READER(),0640)) {
1.168     albertel 1817:     my $version=$hash{"version:$symb"};
                   1818:     $returnhash{'version'}=$version;
                   1819:     my $scope;
                   1820:     for ($scope=1;$scope<=$version;$scope++) {
                   1821:       my $vkeys=$hash{"$scope:keys:$symb"};
                   1822:       my @keys=split(/:/,$vkeys);
                   1823:       my $key;
                   1824:       $returnhash{"$scope:keys"}=$vkeys;
                   1825:       foreach $key (@keys) {
                   1826: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
                   1827: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1.167     albertel 1828:       }
                   1829:     }
1.168     albertel 1830:     if (!(untie(%hash))) {
                   1831:       return "error:$!";
                   1832:     }
                   1833:   } else {
                   1834:     return "error:$!";
                   1835:   }
                   1836:   return %returnhash;
1.167     albertel 1837: }
                   1838: 
1.9       www      1839: # ----------------------------------------------------------------------- Store
                   1840: 
                   1841: sub store {
1.124     www      1842:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1843:     my $home='';
                   1844: 
1.168     albertel 1845:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1846: 
1.213     www      1847:     $symb=&symbclean($symb);
1.122     albertel 1848:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1849: 
1.325     www      1850:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1851:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1852: 
                   1853:     &devalidate($symb,$stuname,$domain);
1.109     www      1854: 
                   1855:     $symb=escape($symb);
1.187     www      1856:     if (!$namespace) { 
                   1857:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1858:           return ''; 
                   1859:        } 
                   1860:     }
1.122     albertel 1861:     if (!$home) { $home=$ENV{'user.home'}; }
1.12      www      1862:     my $namevalue='';
1.191     harris41 1863:     foreach (keys %$storehash) {
1.122     albertel 1864:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1865:     }
1.12      www      1866:     $namevalue=~s/\&$//;
1.187     www      1867:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      1868:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      1869: }
                   1870: 
1.47      www      1871: # -------------------------------------------------------------- Critical Store
                   1872: 
                   1873: sub cstore {
1.124     www      1874:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1875:     my $home='';
                   1876: 
1.168     albertel 1877:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1878: 
1.213     www      1879:     $symb=&symbclean($symb);
1.122     albertel 1880:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1881: 
1.325     www      1882:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1883:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1884: 
                   1885:     &devalidate($symb,$stuname,$domain);
1.109     www      1886: 
                   1887:     $symb=escape($symb);
1.187     www      1888:     if (!$namespace) { 
                   1889:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1890:           return ''; 
                   1891:        } 
                   1892:     }
1.122     albertel 1893:     if (!$home) { $home=$ENV{'user.home'}; }
                   1894: 
1.47      www      1895:     my $namevalue='';
1.191     harris41 1896:     foreach (keys %$storehash) {
1.122     albertel 1897:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1898:     }
1.47      www      1899:     $namevalue=~s/\&$//;
1.187     www      1900:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      1901:     return critical
                   1902:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      1903: }
                   1904: 
1.9       www      1905: # --------------------------------------------------------------------- Restore
                   1906: 
                   1907: sub restore {
1.124     www      1908:     my ($symb,$namespace,$domain,$stuname) = @_;
                   1909:     my $home='';
                   1910: 
1.168     albertel 1911:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1912: 
1.122     albertel 1913:     if (!$symb) {
                   1914:       unless ($symb=escape(&symbread())) { return ''; }
                   1915:     } else {
1.213     www      1916:       $symb=&escape(&symbclean($symb));
1.122     albertel 1917:     }
1.188     www      1918:     if (!$namespace) { 
                   1919:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1920:           return ''; 
                   1921:        } 
                   1922:     }
1.122     albertel 1923:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1924:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1925:     if (!$home) { $home=$ENV{'user.home'}; }
                   1926:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   1927: 
1.12      www      1928:     my %returnhash=();
1.191     harris41 1929:     foreach (split(/\&/,$answer)) {
1.12      www      1930: 	my ($name,$value)=split(/\=/,$_);
                   1931:         $returnhash{&unescape($name)}=&unescape($value);
1.191     harris41 1932:     }
1.75      www      1933:     my $version;
                   1934:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 1935:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      1936:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 1937:        }
1.75      www      1938:     }
1.13      www      1939:     return %returnhash;
1.34      www      1940: }
                   1941: 
                   1942: # ---------------------------------------------------------- Course Description
                   1943: 
                   1944: sub coursedescription {
                   1945:     my $courseid=shift;
                   1946:     $courseid=~s/^\///;
1.49      www      1947:     $courseid=~s/\_/\//g;
1.34      www      1948:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 1949:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 1950:     my $normalid=$cdomain.'_'.$cnum;
                   1951:     # need to always cache even if we get errors otherwise we keep 
                   1952:     # trying and trying and trying to get the course description.
                   1953:     my %envhash=();
                   1954:     my %returnhash=();
                   1955:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      1956:     if ($chome ne 'no_host') {
1.302     albertel 1957:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 1958:        if (!exists($returnhash{'con_lost'})) {
                   1959:            $returnhash{'home'}= $chome;
                   1960: 	   $returnhash{'domain'} = $cdomain;
                   1961: 	   $returnhash{'num'} = $cnum;
1.130     albertel 1962:            while (my ($name,$value) = each %returnhash) {
1.53      www      1963:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 1964:            }
1.270     www      1965:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      1966:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.38      www      1967: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      1968:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   1969:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   1970:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      1971:        }
                   1972:     }
1.302     albertel 1973:     &appenv(%envhash);
                   1974:     return %returnhash;
1.9       www      1975: }
1.1       albertel 1976: 
1.103     harris41 1977: # -------------------------------------------------------- Get user privileges
1.11      www      1978: 
                   1979: sub rolesinit {
                   1980:     my ($domain,$username,$authhost)=@_;
                   1981:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      1982:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      1983:     my %allroles=();
                   1984:     my %thesepriv=();
                   1985:     my $now=time;
1.21      www      1986:     my $userroles="user.login.time=$now\n";
1.11      www      1987:     my $thesestr;
                   1988: 
                   1989:     if ($rolesdump ne '') {
1.191     harris41 1990:         foreach (split(/&/,$rolesdump)) {
1.21      www      1991: 	  if ($_!~/^rolesdef\&/) {
1.11      www      1992:             my ($area,$role)=split(/=/,$_);
1.21      www      1993:             $area=~s/\_\w\w$//;
1.11      www      1994:             my ($trole,$tend,$tstart)=split(/_/,$role);
1.21      www      1995:             $userroles.='user.role.'.$trole.'.'.$area.'='.
                   1996:                         $tstart.'.'.$tend."\n";
1.349     www      1997: # log the associated role with the area
                   1998:             &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.11      www      1999:             if ($tend!=0) {
                   2000: 	        if ($tend<$now) {
                   2001: 	            $trole='';
                   2002:                 } 
                   2003:             }
                   2004:             if ($tstart!=0) {
                   2005:                 if ($tstart>$now) {
                   2006:                    $trole='';        
                   2007:                 }
                   2008:             }
                   2009:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2010: 		my $spec=$trole.'.'.$area;
                   2011: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2012: 		if ($trole =~ /^cr\//) {
                   2013: 		    my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.392     www      2014:  		    my $homsvr=homeserver($rauthor,$rdomain);
1.347     albertel 2015: 		    if ($hostname{$homsvr} ne '') {
1.392     www      2016: 			my ($rdummy,$roledef)=
                   2017: 			   &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2018: 				
                   2019: 			if (($rdummy ne 'con_lost') && ($roledef ne '')) {
1.347     albertel 2020: 			    my ($syspriv,$dompriv,$coursepriv)=
1.392     www      2021: 				split(/\_/,$roledef);
1.347     albertel 2022: 			    if (defined($syspriv)) {
                   2023: 				$allroles{'cm./'}.=':'.$syspriv;
                   2024: 				$allroles{$spec.'./'}.=':'.$syspriv;
                   2025: 			    }
                   2026: 			    if ($tdomain ne '') {
                   2027: 				if (defined($dompriv)) {
                   2028: 				    $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2029: 				    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2030: 				}
                   2031: 				if ($trest ne '') {
                   2032: 				    if (defined($coursepriv)) {
                   2033: 					$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2034: 					$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2035: 				    }
                   2036: 				}
                   2037: 			    }
                   2038: 			}
                   2039: 		    }
                   2040: 		} else {
                   2041: 		    if (defined($pr{$trole.':s'})) {
                   2042: 			$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2043: 			$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2044: 		    }
                   2045: 		    if ($tdomain ne '') {
                   2046: 			if (defined($pr{$trole.':d'})) {
                   2047: 			    $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2048: 			    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2049: 			}
                   2050: 			if ($trest ne '') {
                   2051: 			    if (defined($pr{$trole.':c'})) {
                   2052: 				$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2053: 				$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2054: 			    }
                   2055: 			}
                   2056: 		    }
                   2057: 		}
1.12      www      2058:             }
                   2059:           } 
1.191     harris41 2060:         }
1.125     www      2061:         my $adv=0;
1.128     www      2062:         my $author=0;
1.191     harris41 2063:         foreach (keys %allroles) {
1.11      www      2064:             %thesepriv=();
1.146     www      2065:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1.128     www      2066:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1.191     harris41 2067:             foreach (split(/:/,$allroles{$_})) {
1.11      www      2068:                 if ($_ ne '') {
1.103     harris41 2069: 		    my ($privilege,$restrictions)=split(/&/,$_);
1.11      www      2070:                     if ($restrictions eq '') {
1.103     harris41 2071: 			$thesepriv{$privilege}='F';
1.11      www      2072:                     } else {
1.103     harris41 2073:                         if ($thesepriv{$privilege} ne 'F') {
                   2074: 			    $thesepriv{$privilege}.=$restrictions;
1.11      www      2075:                         }
                   2076:                     }
                   2077:                 }
1.191     harris41 2078:             }
1.11      www      2079:             $thesestr='';
1.191     harris41 2080:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.11      www      2081:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1.191     harris41 2082:         }
1.128     www      2083:         $userroles.='user.adv='.$adv."\n".
                   2084: 	            'user.author='.$author."\n";
1.126     www      2085:         $ENV{'user.adv'}=$adv;
1.11      www      2086:     }
                   2087:     return $userroles;  
                   2088: }
                   2089: 
1.12      www      2090: # --------------------------------------------------------------- get interface
                   2091: 
                   2092: sub get {
1.131     albertel 2093:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2094:    my $items='';
1.191     harris41 2095:    foreach (@$storearr) {
1.12      www      2096:        $items.=escape($_).'&';
1.191     harris41 2097:    }
1.12      www      2098:    $items=~s/\&$//;
1.131     albertel 2099:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2100:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2101:    my $uhome=&homeserver($uname,$udomain);
                   2102: 
1.133     albertel 2103:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2104:    my @pairs=split(/\&/,$rep);
1.273     albertel 2105:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2106:      return @pairs;
                   2107:    }
1.15      www      2108:    my %returnhash=();
1.42      www      2109:    my $i=0;
1.191     harris41 2110:    foreach (@$storearr) {
1.42      www      2111:       $returnhash{$_}=unescape($pairs[$i]);
                   2112:       $i++;
1.191     harris41 2113:    }
1.15      www      2114:    return %returnhash;
1.27      www      2115: }
                   2116: 
                   2117: # --------------------------------------------------------------- del interface
                   2118: 
                   2119: sub del {
1.133     albertel 2120:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2121:    my $items='';
1.191     harris41 2122:    foreach (@$storearr) {
1.27      www      2123:        $items.=escape($_).'&';
1.191     harris41 2124:    }
1.27      www      2125:    $items=~s/\&$//;
1.133     albertel 2126:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2127:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2128:    my $uhome=&homeserver($uname,$udomain);
                   2129: 
                   2130:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2131: }
                   2132: 
                   2133: # -------------------------------------------------------------- dump interface
                   2134: 
                   2135: sub dump {
1.193     www      2136:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.129     albertel 2137:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2138:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2139:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2140:    if ($regexp) {
                   2141:        $regexp=&escape($regexp);
                   2142:    } else {
                   2143:        $regexp='.';
                   2144:    }
                   2145:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      2146:    my @pairs=split(/\&/,$rep);
                   2147:    my %returnhash=();
1.191     harris41 2148:    foreach (@pairs) {
1.12      www      2149:       my ($key,$value)=split(/=/,$_);
1.29      www      2150:       $returnhash{unescape($key)}=unescape($value);
1.318     matthew  2151:    }
                   2152:    return %returnhash;
1.407     www      2153: }
                   2154: 
                   2155: # -------------------------------------------------------------- keys interface
                   2156: 
                   2157: sub getkeys {
                   2158:    my ($namespace,$udomain,$uname)=@_;
                   2159:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2160:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2161:    my $uhome=&homeserver($uname,$udomain);
                   2162:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2163:    my @keyarray=();
                   2164:    foreach (split(/\&/,$rep)) {
                   2165:       push (@keyarray,&unescape($_));
                   2166:    }
                   2167:    return @keyarray;
1.318     matthew  2168: }
                   2169: 
1.319     matthew  2170: # --------------------------------------------------------------- currentdump
                   2171: sub currentdump {
1.328     matthew  2172:    my ($courseid,$sdom,$sname)=@_;
1.326     matthew  2173:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2174:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
                   2175:    $sname    = $ENV{'user.name'}         if (! defined($sname));
                   2176:    my $uhome = &homeserver($sname,$sdom);
                   2177:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2178:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2179:    #
1.318     matthew  2180:    my %returnhash=();
1.319     matthew  2181:    #
                   2182:    if ($rep eq "unknown_cmd") { 
                   2183:        # an old lond will not know currentdump
                   2184:        # Do a dump and make it look like a currentdump
1.326     matthew  2185:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2186:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2187:        my %hash = @tmp;
                   2188:        @tmp=();
                   2189:        # Code ripped from lond, essentially.  The only difference
                   2190:        # here is the unescaping done by lonnet::dump().  Conceivably
                   2191:        # we might run in to problems with parameter names =~ /^v\./
                   2192:        while (my ($key,$value) = each(%hash)) {
                   2193:            my ($v,$symb,$param) = split(/:/,$key);
                   2194:            next if ($v eq 'version' || $symb eq 'keys');
                   2195:            next if (exists($returnhash{$symb}) &&
                   2196:                     exists($returnhash{$symb}->{$param}) &&
                   2197:                     $returnhash{$symb}->{'v.'.$param} > $v);
                   2198:            $returnhash{$symb}->{$param}=$value;
                   2199:            $returnhash{$symb}->{'v.'.$param}=$v;
                   2200:        }
                   2201:        #
                   2202:        # Remove all of the keys in the hashes which keep track of
                   2203:        # the version of the parameter.
                   2204:        while (my ($symb,$param_hash) = each(%returnhash)) {
                   2205:            # use a foreach because we are going to delete from the hash.
                   2206:            foreach my $key (keys(%$param_hash)) {
                   2207:                delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2208:            }
                   2209:        }
                   2210:    } else {
                   2211:        my @pairs=split(/\&/,$rep);
                   2212:        foreach (@pairs) {
                   2213:            my ($key,$value)=split(/=/,$_);
                   2214:            my ($symb,$param) = split(/:/,$key);
                   2215:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
                   2216:                                                           &unescape($value);
                   2217:        }
1.191     harris41 2218:    }
1.12      www      2219:    return %returnhash;
                   2220: }
                   2221: 
                   2222: # --------------------------------------------------------------- put interface
                   2223: 
                   2224: sub put {
1.134     albertel 2225:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2226:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2227:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2228:    my $uhome=&homeserver($uname,$udomain);
1.12      www      2229:    my $items='';
1.191     harris41 2230:    foreach (keys %$storehash) {
1.134     albertel 2231:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1.191     harris41 2232:    }
1.12      www      2233:    $items=~s/\&$//;
1.134     albertel 2234:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      2235: }
                   2236: 
                   2237: # ------------------------------------------------------ critical put interface
                   2238: 
                   2239: sub cput {
1.134     albertel 2240:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2241:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2242:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2243:    my $uhome=&homeserver($uname,$udomain);
1.47      www      2244:    my $items='';
1.191     harris41 2245:    foreach (keys %$storehash) {
1.134     albertel 2246:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 2247:    }
1.47      www      2248:    $items=~s/\&$//;
1.134     albertel 2249:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2250: }
                   2251: 
                   2252: # -------------------------------------------------------------- eget interface
                   2253: 
                   2254: sub eget {
1.133     albertel 2255:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2256:    my $items='';
1.191     harris41 2257:    foreach (@$storearr) {
1.12      www      2258:        $items.=escape($_).'&';
1.191     harris41 2259:    }
1.12      www      2260:    $items=~s/\&$//;
1.133     albertel 2261:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2262:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2263:    my $uhome=&homeserver($uname,$udomain);
                   2264:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2265:    my @pairs=split(/\&/,$rep);
                   2266:    my %returnhash=();
1.42      www      2267:    my $i=0;
1.191     harris41 2268:    foreach (@$storearr) {
1.42      www      2269:       $returnhash{$_}=unescape($pairs[$i]);
                   2270:       $i++;
1.191     harris41 2271:    }
1.12      www      2272:    return %returnhash;
                   2273: }
                   2274: 
1.341     www      2275: # ---------------------------------------------- Custom access rule evaluation
                   2276: 
                   2277: sub customaccess {
                   2278:     my ($priv,$uri)=@_;
1.342     www      2279:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
1.343     www      2280:     $urealm=~s/^\W//;
                   2281:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      2282:     my $access=0;
                   2283:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      2284: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      2285:         if ($role) {
                   2286: 	   if ($role ne $urole) { next; }
                   2287:         }
                   2288:         foreach (split(/\s*\,\s*/,$realm)) {
                   2289:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   2290:             if ($tdom) {
                   2291: 		if ($tdom ne $udom) { next; }
                   2292:             }
                   2293:             if ($tcrs) {
                   2294: 		if ($tcrs ne $ucrs) { next; }
                   2295:             }
                   2296:             if ($tsec) {
                   2297: 		if ($tsec ne $usec) { next; }
                   2298:             }
                   2299:             $access=($effect eq 'allow');
                   2300:             last;
1.342     www      2301:         }
1.402     bowersj2 2302: 	if ($realm eq '' && $role eq '') {
                   2303:             $access=($effect eq 'allow');
                   2304: 	}
1.341     www      2305:     }
                   2306:     return $access;
                   2307: }
                   2308: 
1.103     harris41 2309: # ------------------------------------------------- Check for a user privilege
1.12      www      2310: 
                   2311: sub allowed {
                   2312:     my ($priv,$uri)=@_;
1.152     www      2313: 
                   2314:     my $orguri=$uri;
1.52      www      2315:     $uri=&declutter($uri);
1.29      www      2316: 
1.398     albertel 2317:     if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; }
1.54      www      2318: # Free bre access to adm and meta resources
1.29      www      2319: 
1.54      www      2320:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      2321: 	return 'F';
1.159     www      2322:     }
                   2323: 
                   2324: # Free bre to public access
                   2325: 
                   2326:     if ($priv eq 'bre') {
1.238     www      2327:         my $copyright=&metadata($uri,'copyright');
1.301     www      2328: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
                   2329:            return 'F'; 
                   2330:         }
1.238     www      2331:         if ($copyright eq 'priv') {
                   2332:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   2333: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
                   2334: 		return '';
                   2335:             }
                   2336:         }
                   2337:         if ($copyright eq 'domain') {
                   2338:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   2339: 	    unless (($ENV{'user.domain'} eq $1) ||
                   2340:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
                   2341: 		return '';
                   2342:             }
1.262     matthew  2343:         }
                   2344:         if ($ENV{'request.role'}=~ /li\.\//) {
                   2345:             # Library role, so allow browsing of resources in this domain.
                   2346:             return 'F';
1.238     www      2347:         }
1.341     www      2348:         if ($copyright eq 'custom') {
                   2349: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   2350:         }
1.14      www      2351:     }
1.264     matthew  2352:     # Domain coordinator is trying to create a course
                   2353:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
                   2354:         # uri is the requested domain in this case.
                   2355:         # comparison to 'request.role.domain' shows if the user has selected
                   2356:         # a role of dc for the domain in question. 
                   2357:         return 'F' if ($uri eq $ENV{'request.role.domain'});
                   2358:     }
1.29      www      2359: 
1.52      www      2360:     my $thisallowed='';
                   2361:     my $statecond=0;
                   2362:     my $courseprivid='';
                   2363: 
                   2364: # Course
                   2365: 
                   2366:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
                   2367:        $thisallowed.=$1;
                   2368:     }
1.29      www      2369: 
1.52      www      2370: # Domain
                   2371: 
                   2372:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
                   2373:        =~/$priv\&([^\:]*)/) {
1.12      www      2374:        $thisallowed.=$1;
                   2375:     }
1.52      www      2376: 
                   2377: # Course: uri itself is a course
1.66      www      2378:     my $courseuri=$uri;
                   2379:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      2380:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      2381: 
1.83      www      2382:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.52      www      2383:        =~/$priv\&([^\:]*)/) {
1.12      www      2384:        $thisallowed.=$1;
                   2385:     }
1.29      www      2386: 
1.314     www      2387: # URI is an uploaded document for this course
                   2388: 
                   2389:     if (($priv eq 'bre') && 
                   2390:         ($uri=~/^uploaded\/$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}\/$ENV{'course.'.$ENV{'request.course.id'}.'.num'}/)) {
                   2391:         return 'F';
                   2392:     }
1.52      www      2393: # Full access at system, domain or course-wide level? Exit.
1.29      www      2394: 
                   2395:     if ($thisallowed=~/F/) {
                   2396: 	return 'F';
                   2397:     }
                   2398: 
1.52      www      2399: # If this is generating or modifying users, exit with special codes
1.29      www      2400: 
1.166     www      2401:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1.52      www      2402: 	return $thisallowed;
                   2403:     }
                   2404: #
1.103     harris41 2405: # Gathered so far: system, domain and course wide privileges
1.52      www      2406: #
                   2407: # Course: See if uri or referer is an individual resource that is part of 
                   2408: # the course
                   2409: 
                   2410:     if ($ENV{'request.course.id'}) {
1.232     www      2411: 
1.52      www      2412:        $courseprivid=$ENV{'request.course.id'};
                   2413:        if ($ENV{'request.course.sec'}) {
                   2414:           $courseprivid.='/'.$ENV{'request.course.sec'};
                   2415:        }
                   2416:        $courseprivid=~s/\_/\//;
                   2417:        my $checkreferer=1;
1.232     www      2418:        my ($match,$cond)=&is_on_map($uri);
                   2419:        if ($match) {
                   2420:            $statecond=$cond;
1.52      www      2421:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   2422:                =~/$priv\&([^\:]*)/) {
                   2423:                $thisallowed.=$1;
                   2424:                $checkreferer=0;
                   2425:            }
1.29      www      2426:        }
1.83      www      2427:        
1.148     www      2428:        if ($checkreferer) {
1.152     www      2429: 	  my $refuri=$ENV{'httpref.'.$orguri};
1.148     www      2430:             unless ($refuri) {
1.191     harris41 2431:                 foreach (keys %ENV) {
1.148     www      2432: 		    if ($_=~/^httpref\..*\*/) {
                   2433: 			my $pattern=$_;
1.156     www      2434:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      2435:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   2436:                         $pattern=~s/\//\\\//g;
1.152     www      2437:                         if ($orguri=~/$pattern/) {
1.148     www      2438: 			    $refuri=$ENV{$_};
                   2439:                         }
                   2440:                     }
1.191     harris41 2441:                 }
1.148     www      2442:             }
1.232     www      2443: 
1.148     www      2444:          if ($refuri) { 
1.152     www      2445: 	  $refuri=&declutter($refuri);
1.232     www      2446:           my ($match,$cond)=&is_on_map($refuri);
                   2447:             if ($match) {
                   2448:               my $refstatecond=$cond;
1.52      www      2449:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   2450:                   =~/$priv\&([^\:]*)/) {
                   2451:                   $thisallowed.=$1;
1.53      www      2452:                   $uri=$refuri;
                   2453:                   $statecond=$refstatecond;
1.52      www      2454:               }
                   2455:           }
1.148     www      2456:         }
1.29      www      2457:        }
1.52      www      2458:    }
1.29      www      2459: 
1.52      www      2460: #
1.103     harris41 2461: # Gathered now: all privileges that could apply, and condition number
1.52      www      2462: # 
                   2463: #
                   2464: # Full or no access?
                   2465: #
1.29      www      2466: 
1.52      www      2467:     if ($thisallowed=~/F/) {
                   2468: 	return 'F';
                   2469:     }
1.29      www      2470: 
1.52      www      2471:     unless ($thisallowed) {
                   2472:         return '';
                   2473:     }
1.29      www      2474: 
1.52      www      2475: # Restrictions exist, deal with them
                   2476: #
                   2477: #   C:according to course preferences
                   2478: #   R:according to resource settings
                   2479: #   L:unless locked
                   2480: #   X:according to user session state
                   2481: #
                   2482: 
                   2483: # Possibly locked functionality, check all courses
1.54      www      2484: # Locks might take effect only after 10 minutes cache expiration for other
                   2485: # courses, and 2 minutes for current course
1.52      www      2486: 
                   2487:     my $envkey;
                   2488:     if ($thisallowed=~/L/) {
                   2489:         foreach $envkey (keys %ENV) {
1.54      www      2490:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   2491:                my $courseid=$2;
                   2492:                my $roleid=$1.'.'.$2;
1.92      www      2493:                $courseid=~s/^\///;
1.54      www      2494:                my $expiretime=600;
                   2495:                if ($ENV{'request.role'} eq $roleid) {
                   2496: 		  $expiretime=120;
                   2497:                }
                   2498: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   2499:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
                   2500:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
                   2501: 		   &coursedescription($courseid);
                   2502:                }
                   2503:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
                   2504:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   2505: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57      www      2506:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      2507:                             $ENV{'user.home'},
1.57      www      2508:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      2509:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      2510:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2511: 		       return '';
                   2512:                    }
                   2513:                }
1.54      www      2514:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
                   2515:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   2516: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57      www      2517:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      2518:                             $ENV{'user.home'},
1.57      www      2519:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      2520:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      2521:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2522: 		       return '';
                   2523:                    }
                   2524:                }
                   2525: 	   }
1.29      www      2526:        }
1.52      www      2527:     }
                   2528:    
                   2529: #
                   2530: # Rest of the restrictions depend on selected course
                   2531: #
                   2532: 
                   2533:     unless ($ENV{'request.course.id'}) {
                   2534:        return '1';
                   2535:     }
1.29      www      2536: 
1.52      www      2537: #
                   2538: # Now user is definitely in a course
                   2539: #
1.53      www      2540: 
                   2541: 
                   2542: # Course preferences
                   2543: 
                   2544:    if ($thisallowed=~/C/) {
1.54      www      2545:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.237     www      2546:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.54      www      2547:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.194     www      2548: 	   =~/$rolecode/) {
1.57      www      2549:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   2550:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.237     www      2551:                 $ENV{'request.course.id'});
                   2552:            return '';
                   2553:        }
                   2554: 
                   2555:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
                   2556: 	   =~/$unamedom/) {
                   2557:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   2558:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.54      www      2559:                 $ENV{'request.course.id'});
                   2560:            return '';
                   2561:        }
1.53      www      2562:    }
                   2563: 
                   2564: # Resource preferences
                   2565: 
                   2566:    if ($thisallowed=~/R/) {
1.54      www      2567:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.341     www      2568:        if (&metadata($uri,'roledeny')=~/$rolecode/) {
                   2569: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1.57      www      2570:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341     www      2571:           return '';
1.54      www      2572:        }
1.53      www      2573:    }
1.30      www      2574: 
1.246     www      2575: # Restricted by state or randomout?
1.30      www      2576: 
1.52      www      2577:    if ($thisallowed=~/X/) {
1.247     www      2578:       if ($ENV{'acc.randomout'}) {
1.249     www      2579:          my $symb=&symbread($uri,1);
1.248     www      2580:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
                   2581:             return ''; 
                   2582:          }
1.247     www      2583:       }
                   2584:       if (&condval($statecond)) {
1.52      www      2585: 	 return '2';
                   2586:       } else {
                   2587:          return '';
                   2588:       }
                   2589:    }
1.30      www      2590: 
1.52      www      2591:    return 'F';
1.232     www      2592: }
                   2593: 
                   2594: # --------------------------------------------------- Is a resource on the map?
                   2595: 
                   2596: sub is_on_map {
                   2597:     my $uri=&declutter(shift);
                   2598:     my @uriparts=split(/\//,$uri);
                   2599:     my $filename=$uriparts[$#uriparts];
                   2600:     my $pathname=$uri;
1.289     bowersj2 2601:     $pathname=~s|/\Q$filename\E$||;
1.332     www      2602:     $pathname=~s/^adm\/wrapper\///;    
1.289     bowersj2 2603:     #Trying to find the conditional for the file
1.232     www      2604:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 2605: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      2606:     if ($match) {
1.289     bowersj2 2607: 	return (1,$1);
                   2608:     } else {
1.413   ! www      2609: 	my ($name,$ext)=($filename=~/^(.+)\.(\w+)$/);
        !          2610:         $ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
        !          2611: 	       /\&(\Q$name\E\.\d+\.$ext)\:([\d\|]+)\&/;
        !          2612: 	return (0,$2,$pathname.'/'.$1);
1.289     bowersj2 2613:     }
1.12      www      2614: }
                   2615: 
                   2616: # ----------------------------------------------------------------- Define Role
                   2617: 
                   2618: sub definerole {
                   2619:   if (allowed('mcr','/')) {
                   2620:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      2621:     foreach (split(':',$sysrole)) {
1.21      www      2622: 	my ($crole,$cqual)=split(/\&/,$_);
                   2623:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
                   2624:         if ($pr{'cr:s'}=~/$crole\&/) {
                   2625: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
                   2626:                return "refused:s:$crole&$cqual"; 
                   2627:             }
                   2628:         }
1.191     harris41 2629:     }
1.392     www      2630:     foreach (split(':',$domrole)) {
1.21      www      2631: 	my ($crole,$cqual)=split(/\&/,$_);
                   2632:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
                   2633:         if ($pr{'cr:d'}=~/$crole\&/) {
                   2634: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
                   2635:                return "refused:d:$crole&$cqual"; 
                   2636:             }
                   2637:         }
1.191     harris41 2638:     }
1.392     www      2639:     foreach (split(':',$courole)) {
1.21      www      2640: 	my ($crole,$cqual)=split(/\&/,$_);
                   2641:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
                   2642:         if ($pr{'cr:c'}=~/$crole\&/) {
                   2643: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
                   2644:                return "refused:c:$crole&$cqual"; 
                   2645:             }
                   2646:         }
1.191     harris41 2647:     }
1.12      www      2648:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2649:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21      www      2650: 	        "rolesdef_$rolename=".
                   2651:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.12      www      2652:     return reply($command,$ENV{'user.home'});
                   2653:   } else {
                   2654:     return 'refused';
                   2655:   }
1.105     harris41 2656: }
                   2657: 
                   2658: # ---------------- Make a metadata query against the network of library servers
                   2659: 
                   2660: sub metadata_query {
1.244     matthew  2661:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 2662:     my %rhash;
1.244     matthew  2663:     my @server_list = (defined($server_array) ? @$server_array
                   2664:                                               : keys(%libserv) );
                   2665:     for my $server (@server_list) {
1.118     harris41 2666: 	unless ($custom or $customshow) {
                   2667: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   2668: 	    $rhash{$server}=$reply;
                   2669: 	}
                   2670: 	else {
                   2671: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   2672: 			     &escape($custom).':'.&escape($customshow),
                   2673: 			     $server);
                   2674: 	    $rhash{$server}=$reply;
                   2675: 	}
1.112     harris41 2676:     }
1.118     harris41 2677:     return \%rhash;
1.240     www      2678: }
                   2679: 
                   2680: # ----------------------------------------- Send log queries and wait for reply
                   2681: 
                   2682: sub log_query {
                   2683:     my ($uname,$udom,$query,%filters)=@_;
                   2684:     my $uhome=&homeserver($uname,$udom);
                   2685:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   2686:     my $uhost=$hostname{$uhome};
1.241     www      2687:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      2688:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   2689:                        $uhome);
                   2690:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
1.242     www      2691:     return get_query_reply($queryid);
                   2692: }
                   2693: 
                   2694: sub get_query_reply {
                   2695:     my $queryid=shift;
1.240     www      2696:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   2697:     my $reply='';
                   2698:     for (1..100) {
                   2699: 	sleep 2;
                   2700:         if (-e $replyfile.'.end') {
                   2701: 	    if (my $fh=Apache::File->new($replyfile)) {
                   2702:                $reply.=<$fh>;
                   2703:                $fh->close;
                   2704: 	   } else { return 'error: reply_file_error'; }
1.242     www      2705:            return &unescape($reply);
                   2706: 	}
1.240     www      2707:     }
1.242     www      2708:     return 'timeout:'.$queryid;
1.240     www      2709: }
                   2710: 
                   2711: sub courselog_query {
1.241     www      2712: #
                   2713: # possible filters:
                   2714: # url: url or symb
                   2715: # username
                   2716: # domain
                   2717: # action: view, submit, grade
                   2718: # start: timestamp
                   2719: # end: timestamp
                   2720: #
1.240     www      2721:     my (%filters)=@_;
                   2722:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
1.241     www      2723:     if ($filters{'url'}) {
                   2724: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   2725:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   2726:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   2727:     }
1.240     www      2728:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   2729:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   2730:     return &log_query($cname,$cdom,'courselog',%filters);
                   2731: }
                   2732: 
                   2733: sub userlog_query {
                   2734:     my ($uname,$udom,%filters)=@_;
                   2735:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      2736: }
                   2737: 
                   2738: # ------------------------------------------------------------------ Plain Text
                   2739: 
                   2740: sub plaintext {
1.22      www      2741:     my $short=shift;
                   2742:     return $prp{$short};
1.12      www      2743: }
                   2744: 
                   2745: # ----------------------------------------------------------------- Assign Role
                   2746: 
                   2747: sub assignrole {
1.357     www      2748:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      2749:     my $mrole;
                   2750:     if ($role =~ /^cr\//) {
1.393     www      2751:         my $cwosec=$url;
                   2752:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   2753: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      2754:            &logthis('Refused custom assignrole: '.
                   2755:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2756: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2757:            return 'refused'; 
                   2758:         }
1.21      www      2759:         $mrole='cr';
                   2760:     } else {
1.82      www      2761:         my $cwosec=$url;
1.83      www      2762:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      2763:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      2764:            &logthis('Refused assignrole: '.
                   2765:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2766: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2767:            return 'refused'; 
                   2768:         }
1.21      www      2769:         $mrole=$role;
                   2770:     }
                   2771:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2772:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      2773:     if ($end) { $command.='_'.$end; }
1.21      www      2774:     if ($start) {
                   2775: 	if ($end) { 
1.81      www      2776:            $command.='_'.$start; 
1.21      www      2777:         } else {
1.81      www      2778:            $command.='_0_'.$start;
1.21      www      2779:         }
                   2780:     }
1.357     www      2781: # actually delete
                   2782:     if ($deleteflag) {
1.373     www      2783: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      2784: # modify command to delete the role
                   2785:            $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2786:                 "$udom:$uname:$url".'_'."$mrole";
1.373     www      2787: 	   &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      2788: # set start and finish to negative values for userrolelog
                   2789:            $start=-1;
                   2790:            $end=-1;
                   2791:         }
                   2792:     }
                   2793: # send command
1.349     www      2794:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      2795: # log new user role if status is ok
1.349     www      2796:     if ($answer eq 'ok') {
                   2797: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
                   2798:     }
                   2799:     return $answer;
1.169     harris41 2800: }
                   2801: 
                   2802: # -------------------------------------------------- Modify user authentication
1.197     www      2803: # Overrides without validation
                   2804: 
1.169     harris41 2805: sub modifyuserauth {
                   2806:     my ($udom,$uname,$umode,$upass)=@_;
                   2807:     my $uhome=&homeserver($uname,$udom);
1.197     www      2808:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   2809:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.272     matthew  2810:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   2811:              ' in domain '.$ENV{'request.role.domain'});  
1.169     harris41 2812:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   2813: 		     &escape($upass),$uhome);
1.197     www      2814:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                   2815:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   2816:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   2817:     &log($udom,,$uname,$uhome,
                   2818:         'Authentication changed by '.$ENV{'user.domain'}.', '.
                   2819:                                      $ENV{'user.name'}.', '.$umode.
                   2820:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 2821:     unless ($reply eq 'ok') {
1.197     www      2822:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 2823: 	return 'error: '.$reply;
                   2824:     }   
1.170     harris41 2825:     return 'ok';
1.80      www      2826: }
                   2827: 
1.81      www      2828: # --------------------------------------------------------------- Modify a user
1.80      www      2829: 
1.81      www      2830: sub modifyuser {
1.206     matthew  2831:     my ($udom,    $uname, $uid,
                   2832:         $umode,   $upass, $first,
                   2833:         $middle,  $last,  $gene,
1.387     www      2834:         $forceid, $desiredhome, $email)=@_;
1.198     www      2835:     $udom=~s/\W//g;
                   2836:     $uname=~s/\W//g;
1.81      www      2837:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2838:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  2839: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   2840:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   2841:                                      ' desiredhome not specified'). 
1.272     matthew  2842:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   2843:              ' in domain '.$ENV{'request.role.domain'});
1.230     stredwic 2844:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      2845: # ----------------------------------------------------------------- Create User
1.406     albertel 2846:     if (($uhome eq 'no_host') && 
                   2847: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      2848:         my $unhome='';
1.209     matthew  2849:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   2850:             $unhome = $desiredhome;
                   2851: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1.80      www      2852: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.209     matthew  2853:         } else { # load balancing routine for determining $unhome
1.80      www      2854:             my $tryserver;
1.81      www      2855:             my $loadm=10000000;
1.80      www      2856:             foreach $tryserver (keys %libserv) {
                   2857: 	       if ($hostdom{$tryserver} eq $udom) {
                   2858:                   my $answer=reply('load',$tryserver);
                   2859:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   2860: 		      $loadm=$answer;
                   2861:                       $unhome=$tryserver;
                   2862:                   }
                   2863: 	       }
                   2864: 	    }
                   2865:         }
                   2866:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  2867: 	    return 'error: unable to find a home server for '.$uname.
                   2868:                    ' in domain '.$udom;
1.80      www      2869:         }
                   2870:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   2871:                          &escape($upass),$unhome);
                   2872: 	unless ($reply eq 'ok') {
                   2873:             return 'error: '.$reply;
                   2874:         }   
1.230     stredwic 2875:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      2876:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  2877: 	    return 'error: unable verify users home machine.';
1.80      www      2878:         }
1.209     matthew  2879:     }   # End of creation of new user
1.80      www      2880: # ---------------------------------------------------------------------- Add ID
                   2881:     if ($uid) {
                   2882:        $uid=~tr/A-Z/a-z/;
                   2883:        my %uidhash=&idrget($udom,$uname);
1.196     www      2884:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   2885:          && (!$forceid)) {
1.80      www      2886: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  2887: 	      return 'error: user id "'.$uid.'" does not match '.
                   2888:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      2889:           }
                   2890:        } else {
                   2891: 	  &idput($udom,($uname => $uid));
                   2892:        }
                   2893:     }
                   2894: # -------------------------------------------------------------- Add names, etc
1.313     matthew  2895:     my @tmp=&get('environment',
1.134     albertel 2896: 		   ['firstname','middlename','lastname','generation'],
                   2897: 		   $udom,$uname);
1.313     matthew  2898:     my %names;
                   2899:     if ($tmp[0] =~ m/^error:.*/) { 
                   2900:         %names=(); 
                   2901:     } else {
                   2902:         %names = @tmp;
                   2903:     }
1.388     www      2904: #
                   2905: # Make sure to not trash student environment if instructor does not bother
                   2906: # to supply name and email information
                   2907: #
                   2908:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  2909:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      2910:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  2911:     if (defined($gene))   { $names{'generation'} = $gene; }
1.388     www      2912:     if ($email)  { $names{'notification'} = $email;
                   2913:                    $names{'critnotification'} = $email; }
1.387     www      2914: 
1.134     albertel 2915:     my $reply = &put('environment', \%names, $udom,$uname);
                   2916:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      2917:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2918:              $umode.', '.$first.', '.$middle.', '.
                   2919: 	     $last.', '.$gene.' by '.
                   2920:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134     albertel 2921:     return 'ok';
1.80      www      2922: }
                   2923: 
1.81      www      2924: # -------------------------------------------------------------- Modify student
1.80      www      2925: 
1.81      www      2926: sub modifystudent {
                   2927:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.387     www      2928:         $end,$start,$forceid,$desiredhome,$email)=@_;
1.81      www      2929:     my $cid='';
                   2930:     unless ($cid=$ENV{'request.course.id'}) {
1.80      www      2931: 	return 'not_in_class';
                   2932:     }
                   2933: # --------------------------------------------------------------- Make the user
1.81      www      2934:     my $reply=&modifyuser
1.209     matthew  2935: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      2936:          $desiredhome,$email);
1.80      www      2937:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  2938:     # This will cause &modify_student_enrollment to get the uid from the
                   2939:     # students environment
                   2940:     $uid = undef if (!$forceid);
                   2941:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
                   2942:                                         $last,$gene,$usec,$end,$start);
                   2943:     return $reply;
                   2944: }
                   2945: 
                   2946: sub modify_student_enrollment {
                   2947:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
                   2948:     # Get the course id from the environment
                   2949:     my $cid='';
                   2950:     unless ($cid=$ENV{'request.course.id'}) {
                   2951: 	return 'not_in_class';
                   2952:     }
                   2953:     # Make sure the user exists
1.81      www      2954:     my $uhome=&homeserver($uname,$udom);
                   2955:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   2956: 	return 'error: no such user';
                   2957:     }
1.297     matthew  2958:     #
                   2959:     # Get student data if we were not given enough information
                   2960:     if (!defined($first)  || $first  eq '' || 
                   2961:         !defined($last)   || $last   eq '' || 
                   2962:         !defined($uid)    || $uid    eq '' || 
                   2963:         !defined($middle) || $middle eq '' || 
                   2964:         !defined($gene)   || $gene   eq '') {
1.294     matthew  2965:         # They did not supply us with enough data to enroll the student, so
                   2966:         # we need to pick up more information.
1.297     matthew  2967:         my %tmp = &get('environment',
1.294     matthew  2968:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  2969:                        ,$udom,$uname);
                   2970: 
                   2971:         foreach (keys(%tmp)) {
                   2972:             &logthis("key $_ = ".$tmp{$_});
                   2973:         }
1.294     matthew  2974:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   2975:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   2976:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  2977:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  2978:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   2979:     }
                   2980:     my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
                   2981:                                                            $first,$middle);
1.297     matthew  2982:     my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1.81      www      2983: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
                   2984:                       &escape($uname.':'.$udom).'='.
1.294     matthew  2985:                       &escape(join(':',$end,$start,$uid,$usec,$fullname)),
1.81      www      2986: 	              $ENV{'course.'.$cid.'.home'});
                   2987:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   2988: 	return 'error: '.$reply;
                   2989:     }
1.297     matthew  2990:     # Add student role to user
1.83      www      2991:     my $uurl='/'.$cid;
1.81      www      2992:     $uurl=~s/\_/\//g;
                   2993:     if ($usec) {
                   2994: 	$uurl.='/'.$usec;
                   2995:     }
                   2996:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      2997: }
                   2998: 
1.84      www      2999: # ------------------------------------------------- Write to course preferences
                   3000: 
                   3001: sub writecoursepref {
                   3002:     my ($courseid,%prefs)=@_;
                   3003:     $courseid=~s/^\///;
                   3004:     $courseid=~s/\_/\//g;
                   3005:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   3006:     my $chome=homeserver($cnum,$cdomain);
                   3007:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   3008: 	return 'error: no such course';
                   3009:     }
                   3010:     my $cstring='';
1.191     harris41 3011:     foreach (keys %prefs) {
1.84      www      3012: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 3013:     }
1.84      www      3014:     $cstring=~s/\&$//;
                   3015:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   3016: }
                   3017: 
                   3018: # ---------------------------------------------------------- Make/modify course
                   3019: 
                   3020: sub createcourse {
1.271     www      3021:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
1.84      www      3022:     $url=&declutter($url);
                   3023:     my $cid='';
1.264     matthew  3024:     unless (&allowed('ccc',$udom)) {
1.84      www      3025:         return 'refused';
                   3026:     }
                   3027: # ------------------------------------------------------------------- Create ID
                   3028:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3029:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   3030: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 3031:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      3032:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3033:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3034:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 3035:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      3036:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3037:            return 'error: unable to generate unique course-ID';
                   3038:        } 
                   3039:    }
1.264     matthew  3040: # ------------------------------------------------ Check supplied server name
                   3041:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
                   3042:     if (! exists($libserv{$course_server})) {
                   3043:         return 'error:bad server name '.$course_server;
                   3044:     }
1.84      www      3045: # ------------------------------------------------------------- Make the course
                   3046:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  3047:                       $course_server);
1.84      www      3048:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 3049:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      3050:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3051: 	return 'error: no such course';
                   3052:     }
1.271     www      3053: # ----------------------------------------------------------------- Course made
1.358     www      3054: # log existance
                   3055:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
                   3056:                  $uhome);
                   3057:     &flushcourselogs();
                   3058: # set toplevel url
1.271     www      3059:     my $topurl=$url;
                   3060:     unless ($nonstandard) {
                   3061: # ------------------------------------------ For standard courses, make top url
                   3062:         my $mapurl=&clutter($url);
1.278     www      3063:         if ($mapurl eq '/res/') { $mapurl=''; }
1.271     www      3064:         $ENV{'form.initmap'}=(<<ENDINITMAP);
                   3065: <map>
                   3066: <resource id="1" type="start"></resource>
                   3067: <resource id="2" src="$mapurl"></resource>
                   3068: <resource id="3" type="finish"></resource>
                   3069: <link index="1" from="1" to="2"></link>
                   3070: <link index="2" from="2" to="3"></link>
                   3071: </map>
                   3072: ENDINITMAP
                   3073:         $topurl=&declutter(
                   3074:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
                   3075:                           );
                   3076:     }
                   3077: # ----------------------------------------------------------- Write preferences
1.84      www      3078:     &writecoursepref($udom.'_'.$uname,
                   3079:                      ('description' => $description,
1.271     www      3080:                       'url'         => $topurl));
1.84      www      3081:     return '/'.$udom.'/'.$uname;
                   3082: }
                   3083: 
1.21      www      3084: # ---------------------------------------------------------- Assign Custom Role
                   3085: 
                   3086: sub assigncustomrole {
1.357     www      3087:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      3088:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      3089:                        $end,$start,$deleteflag);
1.21      www      3090: }
                   3091: 
                   3092: # ----------------------------------------------------------------- Revoke Role
                   3093: 
                   3094: sub revokerole {
1.357     www      3095:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      3096:     my $now=time;
1.357     www      3097:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      3098: }
                   3099: 
                   3100: # ---------------------------------------------------------- Revoke Custom Role
                   3101: 
                   3102: sub revokecustomrole {
1.357     www      3103:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      3104:     my $now=time;
1.357     www      3105:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   3106:            $deleteflag);
1.17      www      3107: }
                   3108: 
                   3109: # ------------------------------------------------------------ Directory lister
                   3110: 
                   3111: sub dirlist {
1.253     stredwic 3112:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   3113: 
1.18      www      3114:     $uri=~s/^\///;
                   3115:     $uri=~s/\/$//;
1.253     stredwic 3116:     my ($udom, $uname);
                   3117:     (undef,$udom,$uname)=split(/\//,$uri);
                   3118:     if(defined($userdomain)) {
                   3119:         $udom = $userdomain;
                   3120:     }
                   3121:     if(defined($username)) {
                   3122:         $uname = $username;
                   3123:     }
                   3124: 
                   3125:     my $dirRoot = $perlvar{'lonDocRoot'};
                   3126:     if(defined($alternateDirectoryRoot)) {
                   3127:         $dirRoot = $alternateDirectoryRoot;
                   3128:         $dirRoot =~ s/\/$//;
                   3129:     }
                   3130: 
                   3131:     if($udom) {
                   3132:         if($uname) {
                   3133:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   3134:                               homeserver($uname,$udom));
                   3135:             return split(/:/,$listing);
                   3136:         } elsif(!defined($alternateDirectoryRoot)) {
                   3137:             my $tryserver;
                   3138:             my %allusers=();
                   3139:             foreach $tryserver (keys %libserv) {
                   3140:                 if($hostdom{$tryserver} eq $udom) {
                   3141:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   3142:                                       $udom, $tryserver);
                   3143:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
                   3144:                         && ($listing ne 'con_lost')) {
                   3145:                         foreach (split(/:/,$listing)) {
                   3146:                             my ($entry,@stat)=split(/&/,$_);
                   3147:                             $allusers{$entry}=1;
                   3148:                         }
                   3149:                     }
1.191     harris41 3150:                 }
1.253     stredwic 3151:             }
                   3152:             my $alluserstr='';
                   3153:             foreach (sort keys %allusers) {
                   3154:                 $alluserstr.=$_.'&user:';
                   3155:             }
                   3156:             $alluserstr=~s/:$//;
                   3157:             return split(/:/,$alluserstr);
                   3158:         } else {
                   3159:             my @emptyResults = ();
                   3160:             push(@emptyResults, 'missing user name');
                   3161:             return split(':',@emptyResults);
                   3162:         }
                   3163:     } elsif(!defined($alternateDirectoryRoot)) {
                   3164:         my $tryserver;
                   3165:         my %alldom=();
                   3166:         foreach $tryserver (keys %libserv) {
                   3167:             $alldom{$hostdom{$tryserver}}=1;
                   3168:         }
                   3169:         my $alldomstr='';
                   3170:         foreach (sort keys %alldom) {
1.397     albertel 3171:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 3172:         }
                   3173:         $alldomstr=~s/:$//;
                   3174:         return split(/:/,$alldomstr);       
                   3175:     } else {
                   3176:         my @emptyResults = ();
                   3177:         push(@emptyResults, 'missing domain');
                   3178:         return split(':',@emptyResults);
1.275     stredwic 3179:     }
                   3180: }
                   3181: 
                   3182: # --------------------------------------------- GetFileTimestamp
                   3183: # This function utilizes dirlist and returns the date stamp for
                   3184: # when it was last modified.  It will also return an error of -1
                   3185: # if an error occurs
                   3186: 
1.410     matthew  3187: ##
                   3188: ## FIXME: This subroutine assumes its caller knows something about the
                   3189: ## directory structure of the home server for the student ($root).
                   3190: ## Not a good assumption to make.  Since this is for looking up files
                   3191: ## in user directories, the full path should be constructed by lond, not
                   3192: ## whatever machine we request data from.
                   3193: ##
1.275     stredwic 3194: sub GetFileTimestamp {
                   3195:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   3196:     $studentDomain=~s/\W//g;
                   3197:     $studentName=~s/\W//g;
                   3198:     my $subdir=$studentName.'__';
                   3199:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3200:     my $proname="$studentDomain/$subdir/$studentName";
                   3201:     $proname .= '/'.$filename;
1.375     matthew  3202:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   3203:                                               $studentName, $root);
1.275     stredwic 3204:     my @stats = split('&', $fileStat);
                   3205:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  3206:         # @stats contains first the filename, then the stat output
                   3207:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 3208:     } else {
                   3209:         return -1;
1.253     stredwic 3210:     }
1.26      www      3211: }
                   3212: 
                   3213: # -------------------------------------------------------- Value of a Condition
                   3214: 
1.40      www      3215: sub directcondval {
                   3216:     my $number=shift;
                   3217:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
                   3218:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
                   3219:     } else {
                   3220:        return 2;
                   3221:     }
                   3222: }
                   3223: 
1.26      www      3224: sub condval {
                   3225:     my $condidx=shift;
                   3226:     my $result=0;
1.54      www      3227:     my $allpathcond='';
1.191     harris41 3228:     foreach (split(/\|/,$condidx)) {
1.54      www      3229:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
                   3230: 	   $allpathcond.=
                   3231:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
                   3232:        }
1.191     harris41 3233:     }
1.54      www      3234:     $allpathcond=~s/\|$//;
1.33      www      3235:     if ($ENV{'request.course.id'}) {
1.54      www      3236:        if ($allpathcond) {
1.26      www      3237:           my $operand='|';
                   3238: 	  my @stack;
1.191     harris41 3239:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      3240:               if ($_ eq '(') {
                   3241:                  push @stack,($operand,$result)
                   3242:               } elsif ($_ eq ')') {
                   3243:                   my $before=pop @stack;
                   3244: 		  if (pop @stack eq '&') {
                   3245: 		      $result=$result>$before?$before:$result;
                   3246:                   } else {
                   3247:                       $result=$result>$before?$result:$before;
                   3248:                   }
                   3249:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   3250:                   $operand=$_;
                   3251:               } else {
1.40      www      3252:                   my $new=directcondval($_);
1.26      www      3253:                   if ($operand eq '&') {
                   3254:                      $result=$result>$new?$new:$result;
                   3255:                   } else {
                   3256:                      $result=$result>$new?$result:$new;
1.191     harris41 3257:                   }
1.26      www      3258:               }
1.191     harris41 3259:           }
1.26      www      3260:        }
                   3261:     }
                   3262:     return $result;
1.279     www      3263: }
                   3264: 
                   3265: # ---------------------------------------------------- Devalidate courseresdata
                   3266: 
                   3267: sub devalidatecourseresdata {
                   3268:     my ($coursenum,$coursedomain)=@_;
                   3269:     my $hashid=$coursenum.':'.$coursedomain;
                   3270:     delete $courseresdatacache{$hashid.'.time'};
1.28      www      3271: }
                   3272: 
1.200     www      3273: # --------------------------------------------------- Course Resourcedata Query
                   3274: 
                   3275: sub courseresdata {
                   3276:     my ($coursenum,$coursedomain,@which)=@_;
                   3277:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   3278:     my $hashid=$coursenum.':'.$coursedomain;
1.250     albertel 3279:     my $dodump=0;
                   3280:     if (!defined($courseresdatacache{$hashid.'.time'})) {
                   3281: 	$dodump=1;
                   3282:     } else {
                   3283: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
                   3284:     }
                   3285:     if ($dodump) {
1.251     albertel 3286: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
                   3287: 	my ($tmp) = keys(%dumpreply);
                   3288: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   3289: 	    $courseresdatacache{$hashid.'.time'}=time;
                   3290: 	    $courseresdatacache{$hashid}=\%dumpreply;
1.306     albertel 3291: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   3292: 	    return $tmp;
1.250     albertel 3293: 	}
                   3294:     }
1.251     albertel 3295:     foreach my $item (@which) {
1.287     albertel 3296: 	if (defined($courseresdatacache{$hashid}->{$item})) {
1.251     albertel 3297: 	    return $courseresdatacache{$hashid}->{$item};
                   3298: 	}
1.250     albertel 3299:     }
1.291     albertel 3300:     return undef;
1.200     www      3301: }
                   3302: 
1.379     matthew  3303: #
                   3304: # EXT resource caching routines
                   3305: #
                   3306: 
                   3307: sub clear_EXT_cache_status {
1.383     albertel 3308:     &delenv('cache.EXT.');
1.379     matthew  3309: }
                   3310: 
                   3311: sub EXT_cache_status {
                   3312:     my ($target_domain,$target_user) = @_;
1.383     albertel 3313:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.389     www      3314:     if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
1.379     matthew  3315:         # We know already the user has no data
                   3316:         return 1;
                   3317:     } else {
                   3318:         return 0;
                   3319:     }
                   3320: }
                   3321: 
                   3322: sub EXT_cache_set {
                   3323:     my ($target_domain,$target_user) = @_;
1.383     albertel 3324:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.379     matthew  3325:     &appenv($cachename => time);
                   3326: }
                   3327: 
1.28      www      3328: # --------------------------------------------------------- Value of a Variable
1.58      www      3329: sub EXT {
1.395     albertel 3330:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218     albertel 3331: 
1.68      www      3332:     unless ($varname) { return ''; }
1.218     albertel 3333:     #get real user name/domain, courseid and symb
                   3334:     my $courseid;
1.359     albertel 3335:     my $publicuser;
1.218     albertel 3336:     if (!($uname && $udom)) {
1.360     albertel 3337:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  3338: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 3339:       if (!$symbparm) {	$symbparm=$cursymb; }
                   3340:     } else {
                   3341: 	$courseid=$ENV{'request.course.id'};
                   3342:     }
1.48      www      3343:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   3344:     my $rest;
1.320     albertel 3345:     if (defined($therest[0])) {
1.48      www      3346:        $rest=join('.',@therest);
                   3347:     } else {
                   3348:        $rest='';
                   3349:     }
1.320     albertel 3350: 
1.57      www      3351:     my $qualifierrest=$qualifier;
                   3352:     if ($rest) { $qualifierrest.='.'.$rest; }
                   3353:     my $spacequalifierrest=$space;
                   3354:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      3355:     if ($realm eq 'user') {
1.48      www      3356: # --------------------------------------------------------------- user.resource
                   3357: 	if ($space eq 'resource') {
1.335     albertel 3358: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
                   3359: 		return $Apache::lonhomework::history{$qualifierrest};
                   3360: 	    } else {
1.359     albertel 3361: 		my %restored;
                   3362: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
                   3363: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   3364: 		} else {
                   3365: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   3366: 		}
1.335     albertel 3367: 		return $restored{$qualifierrest};
                   3368: 	    }
1.48      www      3369: # ----------------------------------------------------------------- user.access
                   3370:         } elsif ($space eq 'access') {
1.218     albertel 3371: 	    # FIXME - not supporting calls for a specific user
1.48      www      3372:             return &allowed($qualifier,$rest);
                   3373: # ------------------------------------------ user.preferences, user.environment
                   3374:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218     albertel 3375: 	    if (($uname eq $ENV{'user.name'}) &&
                   3376: 		($udom eq $ENV{'user.domain'})) {
                   3377: 		return $ENV{join('.',('environment',$qualifierrest))};
                   3378: 	    } else {
1.359     albertel 3379: 		my %returnhash;
                   3380: 		if (!$publicuser) {
                   3381: 		    %returnhash=&userenvironment($udom,$uname,
                   3382: 						 $qualifierrest);
                   3383: 		}
1.218     albertel 3384: 		return $returnhash{$qualifierrest};
                   3385: 	    }
1.48      www      3386: # ----------------------------------------------------------------- user.course
                   3387:         } elsif ($space eq 'course') {
1.218     albertel 3388: 	    # FIXME - not supporting calls for a specific user
1.48      www      3389:             return $ENV{join('.',('request.course',$qualifier))};
                   3390: # ------------------------------------------------------------------- user.role
                   3391:         } elsif ($space eq 'role') {
1.218     albertel 3392: 	    # FIXME - not supporting calls for a specific user
1.48      www      3393:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   3394:             if ($qualifier eq 'value') {
                   3395: 		return $role;
                   3396:             } elsif ($qualifier eq 'extent') {
                   3397:                 return $where;
                   3398:             }
                   3399: # ----------------------------------------------------------------- user.domain
                   3400:         } elsif ($space eq 'domain') {
1.218     albertel 3401:             return $udom;
1.48      www      3402: # ------------------------------------------------------------------- user.name
                   3403:         } elsif ($space eq 'name') {
1.218     albertel 3404:             return $uname;
1.48      www      3405: # ---------------------------------------------------- Any other user namespace
1.29      www      3406:         } else {
1.359     albertel 3407: 	    my %reply;
                   3408: 	    if (!$publicuser) {
                   3409: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   3410: 	    }
                   3411: 	    return $reply{$qualifierrest};
1.48      www      3412:         }
1.236     www      3413:     } elsif ($realm eq 'query') {
                   3414: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 3415:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   3416: 						[$spacequalifierrest]);
1.376     albertel 3417: 	return $ENV{'form.'.$spacequalifierrest}; 
1.236     www      3418:    } elsif ($realm eq 'request') {
1.48      www      3419: # ------------------------------------------------------------- request.browser
                   3420:         if ($space eq 'browser') {
                   3421: 	    return $ENV{'browser.'.$qualifier};
1.57      www      3422: # ------------------------------------------------------------ request.filename
                   3423:         } else {
                   3424:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      3425:         }
1.28      www      3426:     } elsif ($realm eq 'course') {
1.48      www      3427: # ---------------------------------------------------------- course.description
1.218     albertel 3428:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      3429:     } elsif ($realm eq 'resource') {
1.165     www      3430: 
1.395     albertel 3431: 	my $section;
1.359     albertel 3432: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
1.165     www      3433: 
1.218     albertel 3434: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      3435: 
1.60      www      3436: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 3437: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   3438: 	    my $symbp=$symbparm;
1.409     www      3439: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 3440: 
                   3441: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   3442: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   3443: 
                   3444: 	    if (($ENV{'user.name'} eq $uname) &&
                   3445: 		($ENV{'user.domain'} eq $udom)) {
1.255     albertel 3446: 		$section=$ENV{'request.course.sec'};
1.218     albertel 3447: 	    } else {
1.377     matthew  3448:                 if (! defined($usection)) {
                   3449:                     $section=&usection($udom,$uname,$courseid);
                   3450:                 } else {
                   3451:                     $section = $usection;
                   3452:                 }
1.218     albertel 3453: 	    }
                   3454: 
                   3455: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   3456: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   3457: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   3458: 
                   3459: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
                   3460: 	    my $courselevelr=$courseid.'.'.$symbparm;
                   3461: 	    my $courselevelm=$courseid.'.'.$mapparm;
1.69      www      3462: 
1.60      www      3463: # ----------------------------------------------------------- first, check user
1.379     matthew  3464: 	    #most student don\'t have any data set, check if there is some data
1.308     albertel 3465:             #every thirty minutes
1.379     matthew  3466: 	    if (! &EXT_cache_status($udom,$uname)) {
1.308     albertel 3467: 		my %resourcedata=&get('resourcedata',
                   3468: 				      [$courselevelr,$courselevelm,$courselevel],
                   3469: 				      $udom,$uname);
                   3470: 		my ($tmp)=keys(%resourcedata);
                   3471: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   3472: 		    if ($resourcedata{$courselevelr}) {
                   3473: 			return $resourcedata{$courselevelr}; }
                   3474: 		    if ($resourcedata{$courselevelm}) {
                   3475: 			return $resourcedata{$courselevelm}; }
                   3476: 		    if ($resourcedata{$courselevel}) {
                   3477: 			return $resourcedata{$courselevel}; }
                   3478: 		} else {
                   3479: 		    if ($tmp!~/No such file/) {
                   3480: 			&logthis("<font color=blue>WARNING:".
                   3481: 				 " Trying to get resource data for ".
                   3482: 				 $uname." at ".$udom.": ".
                   3483: 				 $tmp."</font>");
                   3484: 		    } elsif ($tmp=~/error:No such file/) {
1.379     matthew  3485:                         &EXT_cache_set($udom,$uname);
1.308     albertel 3486: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   3487: 			return $tmp;
                   3488: 		    }
1.218     albertel 3489: 		}
                   3490: 	    }
1.95      www      3491: 
1.60      www      3492: # -------------------------------------------------------- second, check course
1.96      www      3493: 
1.218     albertel 3494: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
                   3495: 					  $ENV{'course.'.$courseid.'.domain'},
                   3496: 					  ($seclevelr,$seclevelm,$seclevel,
                   3497: 					   $courselevelr,$courselevelm,
                   3498: 					   $courselevel));
1.287     albertel 3499: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      3500: 
1.60      www      3501: # ------------------------------------------------------ third, check map parms
1.218     albertel 3502: 	    my %parmhash=();
                   3503: 	    my $thisparm='';
                   3504: 	    if (tie(%parmhash,'GDBM_File',
                   3505: 		    $ENV{'request.course.fn'}.'_parms.db',
1.256     albertel 3506: 		    &GDBM_READER(),0640)) {
1.218     albertel 3507: 		$thisparm=$parmhash{$symbparm};
                   3508: 		untie(%parmhash);
                   3509: 	    }
                   3510: 	    if ($thisparm) { return $thisparm; }
                   3511: 	}
1.60      www      3512: # --------------------------------------------- last, look in resource metadata
1.71      www      3513: 
1.218     albertel 3514: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 3515: 	my $filename;
                   3516: 	if (!$symbparm) { $symbparm=&symbread(); }
                   3517: 	if ($symbparm) {
1.409     www      3518: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 3519: 	} else {
                   3520: 	    $filename=$ENV{'request.filename'};
                   3521: 	}
                   3522: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 3523: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 3524: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 3525: 	if (defined($metadata)) { return $metadata; }
1.142     www      3526: 
1.145     www      3527: # ------------------------------------------------------------------ Cascade up
1.218     albertel 3528: 	unless ($space eq '0') {
1.336     albertel 3529: 	    my @parts=split(/_/,$space);
                   3530: 	    my $id=pop(@parts);
                   3531: 	    my $part=join('_',@parts);
                   3532: 	    if ($part eq '') { $part='0'; }
                   3533: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 3534: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 3535: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 3536: 	}
1.395     albertel 3537: 	if ($recurse) { return undef; }
                   3538: 	my $pack_def=&packages_tab_default($filename,$varname);
                   3539: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      3540: 
1.48      www      3541: # ---------------------------------------------------- Any other user namespace
                   3542:     } elsif ($realm eq 'environment') {
                   3543: # ----------------------------------------------------------------- environment
1.219     albertel 3544: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
                   3545: 	    return $ENV{'environment.'.$spacequalifierrest};
                   3546: 	} else {
                   3547: 	    my %returnhash=&userenvironment($udom,$uname,
                   3548: 					    $spacequalifierrest);
                   3549: 	    return $returnhash{$spacequalifierrest};
                   3550: 	}
1.28      www      3551:     } elsif ($realm eq 'system') {
1.48      www      3552: # ----------------------------------------------------------------- system.time
                   3553: 	if ($space eq 'time') {
                   3554: 	    return time;
                   3555:         }
1.28      www      3556:     }
1.48      www      3557:     return '';
1.61      www      3558: }
                   3559: 
1.395     albertel 3560: sub packages_tab_default {
                   3561:     my ($uri,$varname)=@_;
                   3562:     my (undef,$part,$name)=split(/\./,$varname);
                   3563:     my $packages=&metadata($uri,'packages');
                   3564:     foreach my $package (split(/,/,$packages)) {
                   3565: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
                   3566: 	if ($pack_part eq $part) {
                   3567: 	    return $packagetab{"$pack_type&$name&default"};
                   3568: 	}
                   3569:     }
                   3570:     return undef;
                   3571: }
                   3572: 
1.334     albertel 3573: sub add_prefix_and_part {
                   3574:     my ($prefix,$part)=@_;
                   3575:     my $keyroot;
                   3576:     if (defined($prefix) && $prefix !~ /^__/) {
                   3577: 	# prefix that has a part already
                   3578: 	$keyroot=$prefix;
                   3579:     } elsif (defined($prefix)) {
                   3580: 	# prefix that is missing a part
                   3581: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   3582:     } else {
                   3583: 	# no prefix at all
                   3584: 	if (defined($part)) { $keyroot='_'.$part; }
                   3585:     }
                   3586:     return $keyroot;
                   3587: }
                   3588: 
1.71      www      3589: # ---------------------------------------------------------------- Get metadata
                   3590: 
                   3591: sub metadata {
1.176     www      3592:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.78      www      3593: 
1.71      www      3594:     $uri=&declutter($uri);
1.288     albertel 3595:     # if it is a non metadata possible uri return quickly
1.293     matthew  3596:     if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
                   3597:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
1.288     albertel 3598: 	return '';
                   3599:     }
1.73      www      3600:     my $filename=$uri;
                   3601:     $uri=~s/\.meta$//;
1.172     www      3602: #
                   3603: # Is the metadata already cached?
1.177     www      3604: # Look at timestamp of caching
1.172     www      3605: # Everything is cached by the main uri, libraries are never directly cached
                   3606: #
1.277     albertel 3607:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
1.172     www      3608: #
                   3609: # Is this a recursive call for a library?
                   3610: #
1.171     www      3611:         if ($liburi) {
                   3612: 	    $liburi=&declutter($liburi);
                   3613:             $filename=$liburi;
1.401     bowersj2 3614:         } else {
                   3615: 	    delete($metacache{$uri.':packages'});
                   3616: 	}
1.140     www      3617:         my %metathesekeys=();
1.73      www      3618:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.335     albertel 3619: 	my $metastring=&getfile(&filelocation('',&clutter($filename)));
1.208     albertel 3620:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      3621:         my $token;
1.140     www      3622:         undef %metathesekeys;
1.71      www      3623:         while ($token=$parser->get_token) {
1.339     albertel 3624: 	    if ($token->[0] eq 'S') {
                   3625: 		if (defined($token->[2]->{'package'})) {
1.172     www      3626: #
                   3627: # This is a package - get package info
                   3628: #
1.339     albertel 3629: 		    my $package=$token->[2]->{'package'};
                   3630: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   3631: 		    if (defined($token->[2]->{'id'})) { 
                   3632: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   3633: 		    }
                   3634: 		    if ($metacache{$uri.':packages'}) {
                   3635: 			$metacache{$uri.':packages'}.=','.$package.$keyroot;
                   3636: 		    } else {
                   3637: 			$metacache{$uri.':packages'}=$package.$keyroot;
                   3638: 		    }
                   3639: 		    foreach (keys %packagetab) {
                   3640: 			if ($_=~/^$package\&/) {
                   3641: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 3642: 			    # ignore package.tab specified default values
                   3643:                             # here &package_tab_default() will fetch those
                   3644: 			    if ($subp eq 'default') { next; }
1.339     albertel 3645: 			    my $value=$packagetab{$_};
                   3646: 			    my $part=$keyroot;
                   3647: 			    $part=~s/^\_//;
                   3648: 			    if ($subp eq 'display') {
                   3649: 				$value.=' [Part: '.$part.']';
                   3650: 			    }
                   3651: 			    my $unikey='parameter'.$keyroot.'_'.$name;
1.395     albertel 3652: 			    $metacache{$uri.':'.$unikey.'.part'}=$part;
                   3653: 			    $metathesekeys{$unikey}=1;
1.339     albertel 3654: 			    unless (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
                   3655: 				$metacache{$uri.':'.$unikey.'.'.$subp}=$value;
                   3656: 			    }
                   3657: 			    if (defined($metacache{$uri.':'.$unikey.'.default'})) {
                   3658: 				$metacache{$uri.':'.$unikey}=
1.356     albertel 3659: 				    $metacache{$uri.':'.$unikey.'.default'};
                   3660: 			    }
1.339     albertel 3661: 			}
                   3662: 		    }
                   3663: 		} else {
1.172     www      3664: #
                   3665: # This is not a package - some other kind of start tag
1.339     albertel 3666: #
                   3667: 		    my $entry=$token->[1];
                   3668: 		    my $unikey;
                   3669: 		    if ($entry eq 'import') {
                   3670: 			$unikey='';
                   3671: 		    } else {
                   3672: 			$unikey=$entry;
                   3673: 		    }
                   3674: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   3675: 
                   3676: 		    if (defined($token->[2]->{'id'})) { 
                   3677: 			$unikey.='_'.$token->[2]->{'id'}; 
                   3678: 		    }
1.175     www      3679: 
1.339     albertel 3680: 		    if ($entry eq 'import') {
1.175     www      3681: #
                   3682: # Importing a library here
1.339     albertel 3683: #
                   3684: 			if ($depthcount<20) {
                   3685: 			    my $location=$parser->get_text('/import');
                   3686: 			    my $dir=$filename;
                   3687: 			    $dir=~s|[^/]*$||;
                   3688: 			    $location=&filelocation($dir,$location);
                   3689: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   3690: 							       $location,$unikey,
                   3691: 							       $depthcount+1)))) {
                   3692: 				$metathesekeys{$_}=1;
                   3693: 			    }
                   3694: 			}
                   3695: 		    } else { 
                   3696: 			
                   3697: 			if (defined($token->[2]->{'name'})) { 
                   3698: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   3699: 			}
                   3700: 			$metathesekeys{$unikey}=1;
                   3701: 			foreach (@{$token->[3]}) {
                   3702: 			    $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
                   3703: 			}
                   3704: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
                   3705: 			my $default=$metacache{$uri.':'.$unikey.'.default'};
                   3706: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   3707: 		 # only ws inside the tag, and not in default, so use default
                   3708: 		 # as value
                   3709: 			    $metacache{$uri.':'.$unikey}=$default;
                   3710: 			} else {
1.321     albertel 3711: 		  # either something interesting inside the tag or default
                   3712:                   # uninteresting
1.339     albertel 3713: 			    $metacache{$uri.':'.$unikey}=$internaltext;
                   3714: 			}
1.172     www      3715: # end of not-a-package not-a-library import
1.339     albertel 3716: 		    }
1.172     www      3717: # end of not-a-package start tag
1.339     albertel 3718: 		}
1.172     www      3719: # the next is the end of "start tag"
1.339     albertel 3720: 	    }
                   3721: 	}
1.338     www      3722: # are there custom rights to evaluate
                   3723: 	if ($metacache{$uri.':copyright'} eq 'custom') {
1.339     albertel 3724: 
1.338     www      3725:     #
                   3726:     # Importing a rights file here
1.339     albertel 3727:     #
                   3728: 	    unless ($depthcount) {
                   3729: 		my $location=$metacache{$uri.':customdistributionfile'};
                   3730: 		my $dir=$filename;
                   3731: 		$dir=~s|[^/]*$||;
                   3732: 		$location=&filelocation($dir,$location);
                   3733: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   3734: 						   $location,'_rights',
                   3735: 						   $depthcount+1)))) {
                   3736: 		    $metathesekeys{$_}=1;
                   3737: 		}
                   3738: 	    }
                   3739: 	}
                   3740: 	$metacache{$uri.':keys'}=join(',',keys %metathesekeys);
1.261     albertel 3741: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
1.339     albertel 3742: 	$metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
                   3743: 	$metacache{$uri.':cachedtimestamp'}=time;
1.177     www      3744: # this is the end of "was not already recently cached
1.71      www      3745:     }
                   3746:     return $metacache{$uri.':'.$what};
1.261     albertel 3747: }
                   3748: 
                   3749: sub metadata_generate_part0 {
                   3750:     my ($metadata,$metacache,$uri) = @_;
                   3751:     my %allnames;
                   3752:     foreach my $metakey (sort keys %$metadata) {
                   3753: 	if ($metakey=~/^parameter\_(.*)/) {
                   3754: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
                   3755: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
1.356     albertel 3756: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 3757: 	    $allnames{$name}=$part;
                   3758: 	  }
                   3759: 	}
                   3760:     }
                   3761:     foreach my $name (keys(%allnames)) {
                   3762:       $$metadata{"parameter_0_$name"}=1;
                   3763:       my $key="$uri:parameter_0_$name";
                   3764:       $$metacache{"$key.part"}='0';
                   3765:       $$metacache{"$key.name"}=$name;
                   3766:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
                   3767: 					   $allnames{$name}.'_'.$name.
                   3768: 					   '.type'};
                   3769:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
                   3770: 			     '.display'};
                   3771:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
                   3772:       $olddis=~s/$expr/\[Part: 0\]/;
                   3773:       $$metacache{"$key.display"}=$olddis;
                   3774:     }
1.71      www      3775: }
                   3776: 
1.301     www      3777: # ------------------------------------------------- Get the title of a resource
                   3778: 
                   3779: sub gettitle {
                   3780:     my $urlsymb=shift;
                   3781:     my $symb=&symbread($urlsymb);
                   3782:     unless ($symb) {
                   3783: 	unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
                   3784:         return &metadata($urlsymb,'title'); 
                   3785:     }
1.382     albertel 3786:     if ($titlecache{$symb}) {
                   3787: 	if (time < ($titlecache{$symb}[1] + 600)) {
                   3788: 	    return $titlecache{$symb}[0];
                   3789: 	} else {
                   3790: 	    delete($titlecache{$symb});
                   3791: 	}
                   3792:     }
1.409     www      3793:     my ($map,$resid,$url)=&decode_symb($symb);
1.301     www      3794:     my $title='';
                   3795:     my %bighash;
                   3796:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                   3797:                             &GDBM_READER(),0640)) {
                   3798:         my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   3799:         $title=$bighash{'title_'.$mapid.'.'.$resid};
                   3800:         untie %bighash;
                   3801:     }
1.363     www      3802:     $title=~s/\&colon\;/\:/gs;
1.301     www      3803:     if ($title) {
1.382     albertel 3804:         $titlecache{$symb}=[$title,time];
1.301     www      3805:         return $title;
                   3806:     } else {
                   3807: 	return &metadata($urlsymb,'title');
                   3808:     }
                   3809: }
                   3810:     
1.31      www      3811: # ------------------------------------------------- Update symbolic store links
                   3812: 
                   3813: sub symblist {
                   3814:     my ($mapname,%newhash)=@_;
                   3815:     $mapname=declutter($mapname);
                   3816:     my %hash;
                   3817:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   3818:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 3819:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 3820: 	    foreach (keys %newhash) {
1.211     www      3821:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
1.191     harris41 3822:             }
1.31      www      3823:             if (untie(%hash)) {
                   3824: 		return 'ok';
                   3825:             }
                   3826:         }
                   3827:     }
                   3828:     return 'error';
1.212     www      3829: }
                   3830: 
                   3831: # --------------------------------------------------------------- Verify a symb
                   3832: 
                   3833: sub symbverify {
                   3834:     my ($symb,$thisfn)=@_;
1.213     www      3835:     $thisfn=&declutter($thisfn);
1.215     www      3836: # direct jump to resource in page or to a sequence - will construct own symbs
                   3837:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   3838: # check URL part
1.409     www      3839:     my ($map,$resid,$url)=&decode_symb($symb);
1.213     www      3840:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
                   3841: 
1.216     www      3842:     $symb=&symbclean($symb);
1.213     www      3843: 
                   3844:     my %bighash;
                   3845:     my $okay=0;
                   3846:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 3847:                             &GDBM_READER(),0640)) {
1.280     www      3848:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.216     www      3849:         unless ($ids) { 
                   3850:            $ids=$bighash{'ids_/'.$thisfn};
                   3851:         }
                   3852:         if ($ids) {
                   3853: # ------------------------------------------------------------------- Has ID(s)
                   3854: 	    foreach (split(/\,/,$ids)) {
                   3855:                my ($mapid,$resid)=split(/\./,$_);
                   3856:                if (
                   3857:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   3858:    eq $symb) { 
                   3859:                   $okay=1; 
                   3860:                }
                   3861: 	   }
                   3862:         }
1.213     www      3863: 	untie(%bighash);
                   3864:     }
                   3865:     return $okay;
1.31      www      3866: }
                   3867: 
1.210     www      3868: # --------------------------------------------------------------- Clean-up symb
                   3869: 
                   3870: sub symbclean {
                   3871:     my $symb=shift;
1.213     www      3872: 
1.210     www      3873: # remove version from map
                   3874:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      3875: 
1.210     www      3876: # remove version from URL
                   3877:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      3878: 
1.210     www      3879:     return $symb;
1.409     www      3880: }
                   3881: 
                   3882: # ---------------------------------------------- Split symb to find map and url
                   3883: 
                   3884: sub decode_symb {
1.413   ! www      3885:     my ($map,$resid,$url)=split(/\_\_\_/,shift);
        !          3886:     return (&fixversion($map),$resid,&fixversion($url));
        !          3887: }
        !          3888: 
        !          3889: sub fixversion {
        !          3890:     my $fn=shift;
        !          3891:     if ($fn=~/^(adm|uploaded|public)/) { return $fn; }
        !          3892:     my ($match,$cond,$versioned)=&is_on_map($fn);
        !          3893:     unless ($match) {
        !          3894: 	$fn=$versioned;
        !          3895:     }
        !          3896:     return $fn;
1.210     www      3897: }
                   3898: 
1.31      www      3899: # ------------------------------------------------------ Return symb list entry
                   3900: 
                   3901: sub symbread {
1.249     www      3902:     my ($thisfn,$donotrecurse)=@_;
1.242     www      3903: # no filename provided? try from environment
1.44      www      3904:     unless ($thisfn) {
1.210     www      3905:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
1.44      www      3906: 	$thisfn=$ENV{'request.filename'};
                   3907:     }
1.242     www      3908: # is that filename actually a symb? Verify, clean, and return
                   3909:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
                   3910: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
                   3911:     }
1.44      www      3912:     $thisfn=declutter($thisfn);
1.31      www      3913:     my %hash;
1.37      www      3914:     my %bighash;
                   3915:     my $syval='';
1.45      www      3916:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31      www      3917:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 3918:                       &GDBM_READER(),0640)) {
1.31      www      3919: 	    $syval=$hash{$thisfn};
1.37      www      3920:             untie(%hash);
                   3921:         }
                   3922: # ---------------------------------------------------------- There was an entry
                   3923:         if ($syval) {
                   3924:            unless ($syval=~/\_\d+$/) {
                   3925: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44      www      3926:                   &appenv('request.ambiguous' => $thisfn);
1.37      www      3927:                   return '';
                   3928:                }    
                   3929:                $syval.=$1;
                   3930: 	   }
                   3931:         } else {
                   3932: # ------------------------------------------------------- Was not in symb table
                   3933:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 3934:                             &GDBM_READER(),0640)) {
1.37      www      3935: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      3936:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      3937:               unless ($ids) { 
                   3938:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      3939:               }
                   3940:               unless ($ids) {
                   3941: # alias?
                   3942: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      3943:               }
1.37      www      3944:               if ($ids) {
                   3945: # ------------------------------------------------------------------- Has ID(s)
                   3946:                  my @possibilities=split(/\,/,$ids);
1.39      www      3947:                  if ($#possibilities==0) {
                   3948: # ----------------------------------------------- There is only one possibility
1.37      www      3949: 		     my ($mapid,$resid)=split(/\./,$ids);
                   3950:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249     www      3951:                  } elsif (!$donotrecurse) {
1.39      www      3952: # ------------------------------------------ There is more than one possibility
                   3953:                      my $realpossible=0;
1.191     harris41 3954:                      foreach (@possibilities) {
1.39      www      3955: 			 my $file=$bighash{'src_'.$_};
                   3956:                          if (&allowed('bre',$file)) {
                   3957:          		    my ($mapid,$resid)=split(/\./,$_);
                   3958:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   3959: 				$realpossible++;
                   3960:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   3961:                                        '___'.$resid;
                   3962:                             }
                   3963: 			 }
1.191     harris41 3964:                      }
1.39      www      3965: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      3966:                  } else {
                   3967:                      $syval='';
1.37      www      3968:                  }
                   3969: 	      }
                   3970:               untie(%bighash)
                   3971:            } 
1.31      www      3972:         }
1.62      www      3973:         if ($syval) {
1.210     www      3974:            return &symbclean($syval.'___'.$thisfn); 
1.62      www      3975:         }
1.31      www      3976:     }
1.44      www      3977:     &appenv('request.ambiguous' => $thisfn);
1.31      www      3978:     return '';
                   3979: }
                   3980: 
                   3981: # ---------------------------------------------------------- Return random seed
                   3982: 
1.32      www      3983: sub numval {
                   3984:     my $txt=shift;
                   3985:     $txt=~tr/A-J/0-9/;
                   3986:     $txt=~tr/a-j/0-9/;
                   3987:     $txt=~tr/K-T/0-9/;
                   3988:     $txt=~tr/k-t/0-9/;
                   3989:     $txt=~tr/U-Z/0-5/;
                   3990:     $txt=~tr/u-z/0-5/;
                   3991:     $txt=~s/\D//g;
                   3992:     return int($txt);
1.368     albertel 3993: }
                   3994: 
                   3995: sub latest_rnd_algorithm_id {
                   3996:     return '64bit';
1.366     albertel 3997: }
1.32      www      3998: 
1.31      www      3999: sub rndseed {
1.155     albertel 4000:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 4001: 
                   4002:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 4003:     if (!$symb) {
1.366     albertel 4004: 	unless ($symb=$wsymb) { return time; }
                   4005:     }
                   4006:     if (!$courseid) { $courseid=$wcourseid; }
                   4007:     if (!$domain) { $domain=$wdomain; }
                   4008:     if (!$username) { $username=$wusername }
                   4009:     my $which=$ENV{"course.$courseid.rndseed"};
                   4010:     my $CODE=$ENV{'scantron.CODE'};
                   4011:     if (defined($CODE)) {
                   4012: 	&rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   4013:     } elsif ($which eq '64bit') {
                   4014: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   4015:     }
                   4016:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   4017: }
                   4018: 
                   4019: sub rndseed_32bit {
                   4020:     my ($symb,$courseid,$domain,$username)=@_;
                   4021:     {
                   4022: 	use integer;
                   4023: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   4024: 	my $symbseed=numval($symb) << 22;
                   4025: 	my $namechck=unpack("%32C*",$username) << 17;
                   4026: 	my $nameseed=numval($username) << 12;
                   4027: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   4028: 	my $courseseed=unpack("%32C*",$courseid);
                   4029: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   4030: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   4031: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   4032: 	return $num;
                   4033:     }
                   4034: }
                   4035: 
                   4036: sub rndseed_64bit {
                   4037:     my ($symb,$courseid,$domain,$username)=@_;
                   4038:     {
                   4039: 	use integer;
                   4040: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   4041: 	my $symbseed=numval($symb) << 10;
                   4042: 	my $namechck=unpack("%32S*",$username);
                   4043: 	
                   4044: 	my $nameseed=numval($username) << 21;
                   4045: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   4046: 	my $courseseed=unpack("%32S*",$courseid);
                   4047: 	
                   4048: 	my $num1=$symbchck+$symbseed+$namechck;
                   4049: 	my $num2=$nameseed+$domainseed+$courseseed;
                   4050: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   4051: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   4052: 	return "$num1,$num2";
1.155     albertel 4053:     }
1.366     albertel 4054: }
                   4055: 
                   4056: sub rndseed_CODE_64bit {
                   4057:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 4058:     {
1.366     albertel 4059: 	use integer;
                   4060: 	my $symbchck=unpack("%32S*",$symb) << 16;
                   4061: 	my $symbseed=numval($symb);
                   4062: 	my $CODEseed=numval($ENV{'scantron.CODE'}) << 16;
                   4063: 	my $courseseed=unpack("%32S*",$courseid);
                   4064: 	my $num1=$symbseed+$CODEseed;
                   4065: 	my $num2=$courseseed+$symbchck;
                   4066: 	#&Apache::lonxml::debug("$symbseed:$CODEseed|$courseseed:$symbchck");
                   4067: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   4068: 	return "$num1,$num2";
                   4069:     }
                   4070: }
                   4071: 
                   4072: sub setup_random_from_rndseed {
                   4073:     my ($rndseed)=@_;
                   4074:     if ($rndseed =~/,/) {
                   4075: 	my ($num1,$num2)=split(/,/,$rndseed);
                   4076: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   4077:     } else {
                   4078: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 4079:     }
1.36      albertel 4080: }
                   4081: 
1.76      www      4082: sub ireceipt {
                   4083:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
                   4084:     my $cuname=unpack("%32C*",$funame);
                   4085:     my $cudom=unpack("%32C*",$fudom);
                   4086:     my $cucourseid=unpack("%32C*",$fucourseid);
                   4087:     my $cusymb=unpack("%32C*",$fusymb);
1.77      www      4088:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76      www      4089:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
                   4090:            ($cunique%$cuname+
                   4091:             $cunique%$cudom+
                   4092:             $cusymb%$cuname+
                   4093:             $cusymb%$cudom+
                   4094:             $cucourseid%$cuname+
                   4095:             $cucourseid%$cudom);
                   4096: }
                   4097: 
                   4098: sub receipt {
1.260     ng       4099:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   4100:   return &ireceipt($name,$domain,$courseid,$symb);
1.76      www      4101: }
1.260     ng       4102: 
1.36      albertel 4103: # ------------------------------------------------------------ Serves up a file
                   4104: # returns either the contents of the file or a -1
                   4105: sub getfile {
1.269     www      4106:  my $file=shift;
                   4107:  if ($file=~/^\/*uploaded\//) { # user file
                   4108:     my $ua=new LWP::UserAgent;
                   4109:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
                   4110:     my $response=$ua->request($request);
                   4111:     if ($response->is_success()) {
                   4112:        return $response->content;
                   4113:     } else { 
                   4114:        return -1; 
                   4115:     }
                   4116:  } else { # normal file from res space
1.37      www      4117:   &repcopy($file);
1.36      albertel 4118:   if (! -e $file ) { return -1; };
                   4119:   my $fh=Apache::File->new($file);
                   4120:   my $a='';
                   4121:   while (<$fh>) { $a .=$_; }
1.269     www      4122:   return $a;
                   4123:  }
1.36      albertel 4124: }
                   4125: 
                   4126: sub filelocation {
                   4127:   my ($dir,$file) = @_;
                   4128:   my $location;
                   4129:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59      albertel 4130:   if ($file=~m:^/~:) { # is a contruction space reference
                   4131:     $location = $file;
                   4132:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.270     www      4133:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
                   4134:     $location=$file;
1.36      albertel 4135:   } else {
1.59      albertel 4136:     $file=~s/^$perlvar{'lonDocRoot'}//;
                   4137:     $file=~s:^/*res::;
                   4138:     if ( !( $file =~ m:^/:) ) {
                   4139:       $location = $dir. '/'.$file;
                   4140:     } else {
                   4141:       $location = '/home/httpd/html/res'.$file;
                   4142:     }
1.36      albertel 4143:   }
                   4144:   $location=~s://+:/:g; # remove duplicate /
1.46      www      4145:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   4146:   return $location;
                   4147: }
1.36      albertel 4148: 
1.46      www      4149: sub hreflocation {
                   4150:     my ($dir,$file)=@_;
1.191     harris41 4151:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46      www      4152:        my $finalpath=filelocation($dir,$file);
                   4153:        $finalpath=~s/^\/home\/httpd\/html//;
1.225     albertel 4154:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
1.46      www      4155:        return $finalpath;
                   4156:     } else {
                   4157:        return $file;
                   4158:     }
1.31      www      4159: }
                   4160: 
                   4161: # ------------------------------------------------------------- Declutters URLs
                   4162: 
                   4163: sub declutter {
                   4164:     my $thisfn=shift;
                   4165:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
                   4166:     $thisfn=~s/^\///;
                   4167:     $thisfn=~s/^res\///;
1.235     www      4168:     $thisfn=~s/\?.+$//;
1.268     www      4169:     return $thisfn;
                   4170: }
                   4171: 
                   4172: # ------------------------------------------------------------- Clutter up URLs
                   4173: 
                   4174: sub clutter {
                   4175:     my $thisfn='/'.&declutter(shift);
1.270     www      4176:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
                   4177:        $thisfn='/res'.$thisfn; 
                   4178:     }
1.31      www      4179:     return $thisfn;
1.12      www      4180: }
                   4181: 
                   4182: # -------------------------------------------------------- Escape Special Chars
                   4183: 
                   4184: sub escape {
                   4185:     my $str=shift;
                   4186:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   4187:     return $str;
                   4188: }
                   4189: 
                   4190: # ----------------------------------------------------- Un-Escape Special Chars
                   4191: 
                   4192: sub unescape {
                   4193:     my $str=shift;
                   4194:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   4195:     return $str;
                   4196: }
1.11      www      4197: 
1.1       albertel 4198: # ================================================================ Main Program
                   4199: 
1.184     www      4200: sub goodbye {
1.204     albertel 4201:    &logthis("Starting Shut down");
1.184     www      4202:    &flushcourselogs();
                   4203:    &logthis("Shutting down");
1.362     albertel 4204:    return DONE;
1.184     www      4205: }
                   4206: 
1.179     www      4207: BEGIN {
1.228     harris41 4208: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      4209:     unless ($readit) {
1.217     harris41 4210: {
                   4211:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
                   4212: 
                   4213:     while (my $configline=<$config>) {
                   4214:         if ($configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 4215: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      4216:            chomp($varvalue);
1.1       albertel 4217:            $perlvar{$varname}=$varvalue;
                   4218:         }
                   4219:     }
                   4220: }
1.227     harris41 4221: {
                   4222:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
                   4223: 
                   4224:     while (my $configline=<$config>) {
                   4225:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   4226: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   4227:            chomp($varvalue);
                   4228:            $perlvar{$varname}=$varvalue;
                   4229:         }
                   4230:     }
                   4231: }
1.1       albertel 4232: 
1.327     albertel 4233: # ------------------------------------------------------------ Read domain file
                   4234: {
                   4235:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
                   4236:                             '/domain.tab');
                   4237:     %domaindescription = ();
                   4238:     %domain_auth_def = ();
                   4239:     %domain_auth_arg_def = ();
                   4240:     if ($fh) {
                   4241:        while (<$fh>) {
1.390     matthew  4242:            next if (/^(\#|\s*$)/);
                   4243: #           next if /^\#/;
1.327     albertel 4244:            chomp;
1.403     www      4245:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
                   4246: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
                   4247: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 4248:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      4249: 	   $domaindescription{$domain}=$domain_description;
                   4250: 	   $domain_lang_def{$domain}=$def_lang;
                   4251: 	   $domain_city{$domain}=$city;
                   4252: 	   $domain_longi{$domain}=$longi;
                   4253: 	   $domain_lati{$domain}=$lati;
                   4254: 
1.327     albertel 4255: #          &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
                   4256: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
                   4257:        }
                   4258:     }
                   4259: }
                   4260: 
                   4261: 
1.1       albertel 4262: # ------------------------------------------------------------- Read hosts file
                   4263: {
                   4264:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
                   4265: 
                   4266:     while (my $configline=<$config>) {
1.303     matthew  4267:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      4268:        chomp($configline);
1.245     www      4269:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
1.252     albertel 4270:        if ($id && $domain && $role && $name && $ip) {
                   4271: 	 $hostname{$id}=$name;
                   4272: 	 $hostdom{$id}=$domain;
                   4273: 	 $hostip{$id}=$ip;
1.300     albertel 4274: 	 $iphost{$ip}=$id;
1.252     albertel 4275: 	 if ($role eq 'library') { $libserv{$id}=$name; }
                   4276:        } else {
                   4277: 	 if ($configline) {
                   4278: 	   &logthis("Skipping hosts.tab line -$configline-");
                   4279: 	 }
1.245     www      4280:        }
1.1       albertel 4281:     }
                   4282: }
                   4283: 
                   4284: # ------------------------------------------------------ Read spare server file
                   4285: {
                   4286:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
                   4287: 
                   4288:     while (my $configline=<$config>) {
                   4289:        chomp($configline);
1.284     matthew  4290:        if ($configline) {
1.1       albertel 4291:           $spareid{$configline}=1;
                   4292:        }
                   4293:     }
                   4294: }
1.11      www      4295: # ------------------------------------------------------------ Read permissions
                   4296: {
                   4297:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
                   4298: 
                   4299:     while (my $configline=<$config>) {
                   4300:        chomp($configline);
1.160     www      4301:       if ($configline) {
1.11      www      4302:        my ($role,$perm)=split(/ /,$configline);
                   4303:        if ($perm ne '') { $pr{$role}=$perm; }
1.160     www      4304:       }
1.11      www      4305:     }
                   4306: }
                   4307: 
                   4308: # -------------------------------------------- Read plain texts for permissions
                   4309: {
                   4310:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
                   4311: 
                   4312:     while (my $configline=<$config>) {
                   4313:        chomp($configline);
1.160     www      4314:       if ($configline) {
1.11      www      4315:        my ($short,$plain)=split(/:/,$configline);
                   4316:        if ($plain ne '') { $prp{$short}=$plain; }
1.160     www      4317:       }
1.135     www      4318:     }
                   4319: }
                   4320: 
                   4321: # ---------------------------------------------------------- Read package table
                   4322: {
                   4323:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
                   4324: 
                   4325:     while (my $configline=<$config>) {
                   4326:        chomp($configline);
                   4327:        my ($short,$plain)=split(/:/,$configline);
1.143     www      4328:        my ($pack,$name)=split(/\&/,$short);
                   4329:        if ($plain ne '') {
                   4330:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   4331:           $packagetab{$short}=$plain; 
1.25      www      4332:        }
1.11      www      4333:     }
1.329     matthew  4334: }
                   4335: 
                   4336: # ------------- set up temporary directory
                   4337: {
                   4338:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   4339: 
1.11      www      4340: }
                   4341: 
1.71      www      4342: %metacache=();
1.185     www      4343: 
1.281     www      4344: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      4345: $dumpcount=0;
1.22      www      4346: 
1.163     harris41 4347: &logtouch();
1.12      www      4348: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      4349: $readit=1;
                   4350: }
1.1       albertel 4351: }
1.179     www      4352: 
1.1       albertel 4353: 1;
1.191     harris41 4354: __END__
                   4355: 
1.243     albertel 4356: =pod
                   4357: 
1.191     harris41 4358: =head1 NAME
                   4359: 
1.243     albertel 4360: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 4361: 
                   4362: =head1 SYNOPSIS
                   4363: 
1.243     albertel 4364: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 4365: 
                   4366:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   4367: 
1.243     albertel 4368: Common parameters:
                   4369: 
                   4370: =over 4
                   4371: 
                   4372: =item *
                   4373: 
                   4374: $uname : an internal username (if $cname expecting a course Id specifically)
                   4375: 
                   4376: =item *
                   4377: 
                   4378: $udom : a domain (if $cdom expecting a course's domain specifically)
                   4379: 
                   4380: =item *
                   4381: 
                   4382: $symb : a resource instance identifier
                   4383: 
                   4384: =item *
                   4385: 
                   4386: $namespace : the name of a .db file that contains the data needed or
                   4387: being set.
                   4388: 
                   4389: =back
                   4390: 
1.394     bowersj2 4391: =head1 OVERVIEW
1.191     harris41 4392: 
1.394     bowersj2 4393: lonnet provides subroutines which interact with the
                   4394: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   4395: about classes, users, and resources.
1.243     albertel 4396: 
                   4397: For many of these objects you can also use this to store data about
                   4398: them or modify them in various ways.
1.191     harris41 4399: 
1.394     bowersj2 4400: =head2 Symbs
1.191     harris41 4401: 
1.394     bowersj2 4402: To identify a specific instance of a resource, LON-CAPA uses symbols
                   4403: or "symbs"X<symb>. These identifiers are built from the URL of the
                   4404: map, the resource number of the resource in the map, and the URL of
                   4405: the resource itself. The latter is somewhat redundant, but might help
                   4406: if maps change.
                   4407: 
                   4408: An example is
                   4409: 
                   4410:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   4411: 
                   4412: The respective map entry is
                   4413: 
                   4414:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   4415:   title="Problem 2">
                   4416:  </resource>
                   4417: 
                   4418: Symbs are used by the random number generator, as well as to store and
                   4419: restore data specific to a certain instance of for example a problem.
                   4420: 
                   4421: =head2 Storing And Retrieving Data
                   4422: 
                   4423: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   4424: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   4425: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   4426: is is the non-critical message twin of cstore. These functions are for
                   4427: handlers to store a perl hash to a user's permanent data space in an
                   4428: easy manner, and to retrieve it again on another call. It is expected
                   4429: that a handler would use this once at the beginning to retrieve data,
                   4430: and then again once at the end to send only the new data back.
                   4431: 
                   4432: The data is stored in the user's data directory on the user's
                   4433: homeserver under the ID of the course.
                   4434: 
                   4435: The hash that is returned by restore will have all of the previous
                   4436: value for all of the elements of the hash.
                   4437: 
                   4438: Example:
                   4439: 
                   4440:  #creating a hash
                   4441:  my %hash;
                   4442:  $hash{'foo'}='bar';
                   4443: 
                   4444:  #storing it
                   4445:  &Apache::lonnet::cstore(\%hash);
                   4446: 
                   4447:  #changing a value
                   4448:  $hash{'foo'}='notbar';
                   4449: 
                   4450:  #adding a new value
                   4451:  $hash{'bar'}='foo';
                   4452:  &Apache::lonnet::cstore(\%hash);
                   4453: 
                   4454:  #retrieving the hash
                   4455:  my %history=&Apache::lonnet::restore();
                   4456: 
                   4457:  #print the hash
                   4458:  foreach my $key (sort(keys(%history))) {
                   4459:    print("\%history{$key} = $history{$key}");
                   4460:  }
                   4461: 
                   4462: Will print out:
1.191     harris41 4463: 
1.394     bowersj2 4464:  %history{1:foo} = bar
                   4465:  %history{1:keys} = foo:timestamp
                   4466:  %history{1:timestamp} = 990455579
                   4467:  %history{2:bar} = foo
                   4468:  %history{2:foo} = notbar
                   4469:  %history{2:keys} = foo:bar:timestamp
                   4470:  %history{2:timestamp} = 990455580
                   4471:  %history{bar} = foo
                   4472:  %history{foo} = notbar
                   4473:  %history{timestamp} = 990455580
                   4474:  %history{version} = 2
                   4475: 
                   4476: Note that the special hash entries C<keys>, C<version> and
                   4477: C<timestamp> were added to the hash. C<version> will be equal to the
                   4478: total number of versions of the data that have been stored. The
                   4479: C<timestamp> attribute will be the UNIX time the hash was
                   4480: stored. C<keys> is available in every historical section to list which
                   4481: keys were added or changed at a specific historical revision of a
                   4482: hash.
                   4483: 
                   4484: B<Warning>: do not store the hash that restore returns directly. This
                   4485: will cause a mess since it will restore the historical keys as if the
                   4486: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 4487: 
1.394     bowersj2 4488: Calling convention:
1.191     harris41 4489: 
1.394     bowersj2 4490:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   4491:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 4492: 
1.394     bowersj2 4493: For more detailed information, see lonnet specific documentation.
1.191     harris41 4494: 
1.394     bowersj2 4495: =head1 RETURN MESSAGES
1.191     harris41 4496: 
1.394     bowersj2 4497: =over 4
1.191     harris41 4498: 
1.394     bowersj2 4499: =item * B<con_lost>: unable to contact remote host
1.191     harris41 4500: 
1.394     bowersj2 4501: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   4502: when the connection is brought back up
1.191     harris41 4503: 
1.394     bowersj2 4504: =item * B<con_failed>: unable to contact remote host and unable to save message
                   4505: for later delivery
1.191     harris41 4506: 
1.394     bowersj2 4507: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 4508: 
1.394     bowersj2 4509: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 4510: that was requested
1.191     harris41 4511: 
1.243     albertel 4512: =back
1.191     harris41 4513: 
1.243     albertel 4514: =head1 PUBLIC SUBROUTINES
1.191     harris41 4515: 
1.243     albertel 4516: =head2 Session Environment Functions
1.191     harris41 4517: 
1.243     albertel 4518: =over 4
1.191     harris41 4519: 
1.394     bowersj2 4520: =item * 
                   4521: X<appenv()>
                   4522: B<appenv(%hash)>: the value of %hash is written to
                   4523: the user envirnoment file, and will be restored for each access this
                   4524: user makes during this session, also modifies the %ENV for the current
                   4525: process
1.191     harris41 4526: 
                   4527: =item *
1.394     bowersj2 4528: X<delenv()>
                   4529: B<delenv($regexp)>: removes all items from the session
                   4530: environment file that matches the regular expression in $regexp. The
                   4531: values are also delted from the current processes %ENV.
1.191     harris41 4532: 
1.243     albertel 4533: =back
                   4534: 
                   4535: =head2 User Information
1.191     harris41 4536: 
1.243     albertel 4537: =over 4
1.191     harris41 4538: 
                   4539: =item *
1.394     bowersj2 4540: X<queryauthenticate()>
                   4541: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 4542: authentication scheme
                   4543: 
                   4544: =item *
1.394     bowersj2 4545: X<authenticate()>
                   4546: B<authenticate($uname,$upass,$udom)>: try to
                   4547: authenticate user from domain's lib servers (first use the current
                   4548: one). C<$upass> should be the users password.
1.191     harris41 4549: 
                   4550: =item *
1.394     bowersj2 4551: X<homeserver()>
                   4552: B<homeserver($uname,$udom)>: find the server which has
                   4553: the user's directory and files (there must be only one), this caches
                   4554: the answer, and also caches if there is a borken connection.
1.191     harris41 4555: 
                   4556: =item *
1.394     bowersj2 4557: X<idget()>
                   4558: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   4559: (IDs are a unique resource in a domain, there must be only 1 ID per
                   4560: username, and only 1 username per ID in a specific domain) (returns
                   4561: hash: id=>name,id=>name)
1.191     harris41 4562: 
                   4563: =item *
1.394     bowersj2 4564: X<idrget()>
                   4565: B<idrget($udom,@unames)>: find the IDs behind a list of
                   4566: usernames (returns hash: name=>id,name=>id)
1.191     harris41 4567: 
                   4568: =item *
1.394     bowersj2 4569: X<idput()>
                   4570: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 4571: 
                   4572: =item *
1.394     bowersj2 4573: X<rolesinit()>
                   4574: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 4575: 
                   4576: =item *
1.394     bowersj2 4577: X<usection()>
                   4578: B<usection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 4579: course $cname, return section name/number or '' for "not in course"
                   4580: and '-1' for "no section"
                   4581: 
                   4582: =item *
1.394     bowersj2 4583: X<userenvironment()>
                   4584: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 4585: passed in @what from the requested user's environment, returns a hash
                   4586: 
                   4587: =back
                   4588: 
                   4589: =head2 User Roles
                   4590: 
                   4591: =over 4
                   4592: 
                   4593: =item *
                   4594: 
                   4595: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   4596: actions
                   4597:  F: full access
                   4598:  U,I,K: authentication modes (cxx only)
                   4599:  '': forbidden
                   4600:  1: user needs to choose course
                   4601:  2: browse allowed
                   4602: 
                   4603: =item *
                   4604: 
                   4605: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   4606: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   4607: and course level
                   4608: 
                   4609: =item *
                   4610: 
                   4611: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   4612: explanation of a user role term
                   4613: 
                   4614: =back
                   4615: 
                   4616: =head2 User Modification
                   4617: 
                   4618: =over 4
                   4619: 
                   4620: =item *
                   4621: 
                   4622: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   4623: user for the level given by URL.  Optional start and end dates (leave empty
                   4624: string or zero for "no date")
1.191     harris41 4625: 
                   4626: =item *
                   4627: 
1.243     albertel 4628: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   4629: change a users, password, possible return values are: ok,
                   4630: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   4631: refused
1.191     harris41 4632: 
                   4633: =item *
                   4634: 
1.243     albertel 4635: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 4636: 
                   4637: =item *
                   4638: 
1.243     albertel 4639: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   4640: modify user
1.191     harris41 4641: 
                   4642: =item *
                   4643: 
1.286     matthew  4644: modifystudent
                   4645: 
                   4646: modify a students enrollment and identification information.
                   4647: The course id is resolved based on the current users environment.  
                   4648: This means the envoking user must be a course coordinator or otherwise
                   4649: associated with a course.
                   4650: 
1.297     matthew  4651: This call is essentially a wrapper for lonnet::modifyuser and
                   4652: lonnet::modify_student_enrollment
1.286     matthew  4653: 
                   4654: Inputs: 
                   4655: 
                   4656: =over 4
                   4657: 
                   4658: =item B<$udom> Students loncapa domain
                   4659: 
                   4660: =item B<$uname> Students loncapa login name
                   4661: 
                   4662: =item B<$uid> Students id/student number
                   4663: 
                   4664: =item B<$umode> Students authentication mode
                   4665: 
                   4666: =item B<$upass> Students password
                   4667: 
                   4668: =item B<$first> Students first name
                   4669: 
                   4670: =item B<$middle> Students middle name
                   4671: 
                   4672: =item B<$last> Students last name
                   4673: 
                   4674: =item B<$gene> Students generation
                   4675: 
                   4676: =item B<$usec> Students section in course
                   4677: 
                   4678: =item B<$end> Unix time of the roles expiration
                   4679: 
                   4680: =item B<$start> Unix time of the roles start date
                   4681: 
                   4682: =item B<$forceid> If defined, allow $uid to be changed
                   4683: 
                   4684: =item B<$desiredhome> server to use as home server for student
                   4685: 
                   4686: =back
1.297     matthew  4687: 
                   4688: =item *
                   4689: 
                   4690: modify_student_enrollment
                   4691: 
                   4692: Change a students enrollment status in a class.  The environment variable
                   4693: 'role.request.course' must be defined for this function to proceed.
                   4694: 
                   4695: Inputs:
                   4696: 
                   4697: =over 4
                   4698: 
                   4699: =item $udom, students domain
                   4700: 
                   4701: =item $uname, students name
                   4702: 
                   4703: =item $uid, students user id
                   4704: 
                   4705: =item $first, students first name
                   4706: 
                   4707: =item $middle
                   4708: 
                   4709: =item $last
                   4710: 
                   4711: =item $gene
                   4712: 
                   4713: =item $usec
                   4714: 
                   4715: =item $end
                   4716: 
                   4717: =item $start
                   4718: 
                   4719: =back
                   4720: 
1.191     harris41 4721: 
                   4722: =item *
                   4723: 
1.243     albertel 4724: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   4725: custom role; give a custom role to a user for the level given by URL.  Specify
                   4726: name and domain of role author, and role name
1.191     harris41 4727: 
                   4728: =item *
                   4729: 
1.243     albertel 4730: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 4731: 
                   4732: =item *
                   4733: 
1.243     albertel 4734: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   4735: 
                   4736: =back
                   4737: 
                   4738: =head2 Course Infomation
                   4739: 
                   4740: =over 4
1.191     harris41 4741: 
                   4742: =item *
                   4743: 
1.243     albertel 4744: coursedescription($courseid) : course description
1.191     harris41 4745: 
                   4746: =item *
                   4747: 
1.243     albertel 4748: courseresdata($coursenum,$coursedomain,@which) : request for current
                   4749: parameter setting for a specific course, @what should be a list of
                   4750: parameters to ask about. This routine caches answers for 5 minutes.
                   4751: 
                   4752: =back
                   4753: 
                   4754: =head2 Course Modification
                   4755: 
                   4756: =over 4
1.191     harris41 4757: 
                   4758: =item *
                   4759: 
1.243     albertel 4760: writecoursepref($courseid,%prefs) : write preferences (environment
                   4761: database) for a course
1.191     harris41 4762: 
                   4763: =item *
                   4764: 
1.243     albertel 4765: createcourse($udom,$description,$url) : make/modify course
                   4766: 
                   4767: =back
                   4768: 
                   4769: =head2 Resource Subroutines
                   4770: 
                   4771: =over 4
1.191     harris41 4772: 
                   4773: =item *
                   4774: 
1.243     albertel 4775: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 4776: 
                   4777: =item *
                   4778: 
1.243     albertel 4779: repcopy($filename) : subscribes to the requested file, and attempts to
                   4780: replicate from the owning library server, Might return
                   4781: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
                   4782: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
                   4783: resource. Expects the local filesystem pathname
                   4784: (/home/httpd/html/res/....)
                   4785: 
                   4786: =back
                   4787: 
                   4788: =head2 Resource Information
                   4789: 
                   4790: =over 4
1.191     harris41 4791: 
                   4792: =item *
                   4793: 
1.243     albertel 4794: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   4795: a vairety of different possible values, $varname should be a request
                   4796: string, and the other parameters can be used to specify who and what
                   4797: one is asking about.
                   4798: 
                   4799: Possible values for $varname are environment.lastname (or other item
                   4800: from the envirnment hash), user.name (or someother aspect about the
                   4801: user), resource.0.maxtries (or some other part and parameter of a
                   4802: resource)
1.204     albertel 4803: 
                   4804: =item *
                   4805: 
1.243     albertel 4806: directcondval($number) : get current value of a condition; reads from a state
                   4807: string
1.204     albertel 4808: 
                   4809: =item *
                   4810: 
1.243     albertel 4811: condval($condidx) : value of condition index based on state
1.204     albertel 4812: 
                   4813: =item *
                   4814: 
1.243     albertel 4815: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   4816: resource's metadata, $what should be either a specific key, or either
                   4817: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   4818: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   4819: 
                   4820: this function automatically caches all requests
1.191     harris41 4821: 
                   4822: =item *
                   4823: 
1.243     albertel 4824: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   4825: network of library servers; returns file handle of where SQL and regex results
                   4826: will be stored for query
1.191     harris41 4827: 
                   4828: =item *
                   4829: 
1.243     albertel 4830: symbread($filename) : return symbolic list entry (filename argument optional);
                   4831: returns the data handle
1.191     harris41 4832: 
                   4833: =item *
                   4834: 
1.243     albertel 4835: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
                   4836: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
                   4837: failure, user must be in a course, as it assumes the existance of the
                   4838: course initi hash, and uses $ENV('request.course.id'}
                   4839: 
1.191     harris41 4840: 
                   4841: =item *
                   4842: 
1.243     albertel 4843: symbclean($symb) : removes versions numbers from a symb, returns the
                   4844: cleaned symb
1.191     harris41 4845: 
                   4846: =item *
                   4847: 
1.243     albertel 4848: is_on_map($uri) : checks if the $uri is somewhere on the current
                   4849: course map, user must be in a course for it to work.
1.191     harris41 4850: 
                   4851: =item *
                   4852: 
1.243     albertel 4853: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 4854: 
                   4855: =item *
                   4856: 
1.243     albertel 4857: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   4858: a random seed, all arguments are optional, if they aren't sent it uses the
                   4859: environment to derive them. Note: if symb isn't sent and it can't get one
                   4860: from &symbread it will use the current time as its return value
1.191     harris41 4861: 
                   4862: =item *
                   4863: 
1.243     albertel 4864: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   4865: unfakeable, receipt
1.191     harris41 4866: 
                   4867: =item *
                   4868: 
1.243     albertel 4869: receipt() : API to ireceipt working off of ENV values; given out to users
1.191     harris41 4870: 
                   4871: =item *
                   4872: 
1.243     albertel 4873: countacc($url) : count the number of accesses to a given URL
1.191     harris41 4874: 
                   4875: =item *
                   4876: 
1.243     albertel 4877: checkout($symb,$tuname,$tudom,$tcrsid) :  creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
1.191     harris41 4878: 
                   4879: =item *
                   4880: 
1.243     albertel 4881: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
1.191     harris41 4882: 
                   4883: =item *
                   4884: 
1.243     albertel 4885: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 4886: 
                   4887: =item *
                   4888: 
1.243     albertel 4889: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   4890: forcing spreadsheet to reevaluate the resource scores next time.
                   4891: 
                   4892: =back
                   4893: 
                   4894: =head2 Storing/Retreiving Data
                   4895: 
                   4896: =over 4
1.191     harris41 4897: 
                   4898: =item *
                   4899: 
1.243     albertel 4900: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   4901: for this url; hashref needs to be given and should be a \%hashname; the
                   4902: remaining args aren't required and if they aren't passed or are '' they will
                   4903: be derived from the ENV
1.191     harris41 4904: 
                   4905: =item *
                   4906: 
1.243     albertel 4907: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   4908: uses critical subroutine
1.191     harris41 4909: 
                   4910: =item *
                   4911: 
1.243     albertel 4912: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   4913: all args are optional
1.191     harris41 4914: 
                   4915: =item *
                   4916: 
1.243     albertel 4917: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   4918: works very similar to store/cstore, but all data is stored in a
                   4919: temporary location and can be reset using tmpreset, $storehash should
                   4920: be a hash reference, returns nothing on success
1.191     harris41 4921: 
                   4922: =item *
                   4923: 
1.243     albertel 4924: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   4925: similar to restore, but all data is stored in a temporary location and
                   4926: can be reset using tmpreset. Returns a hash of values on success,
                   4927: error string otherwise.
1.191     harris41 4928: 
                   4929: =item *
                   4930: 
1.243     albertel 4931: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   4932: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 4933: 
                   4934: =item *
                   4935: 
1.243     albertel 4936: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   4937: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 4938: 
                   4939: =item *
                   4940: 
1.243     albertel 4941: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   4942: namesp ($udom and $uname are optional)
1.191     harris41 4943: 
                   4944: =item *
                   4945: 
1.243     albertel 4946: dump($namespace,$udom,$uname,$regexp) : 
                   4947: dumps the complete (or key matching regexp) namespace into a hash
                   4948: ($udom, $uname and $regexp are optional)
1.191     harris41 4949: 
                   4950: =item *
                   4951: 
1.243     albertel 4952: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   4953: ($udom and $uname are optional)
1.191     harris41 4954: 
                   4955: =item *
                   4956: 
1.243     albertel 4957: cput($namespace,$storehash,$udom,$uname) : critical put
                   4958: ($udom and $uname are optional)
1.191     harris41 4959: 
                   4960: =item *
                   4961: 
1.243     albertel 4962: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   4963: reference filled in from namesp (encrypts the return communication)
                   4964: ($udom and $uname are optional)
1.191     harris41 4965: 
                   4966: =item *
                   4967: 
1.243     albertel 4968: log($udom,$name,$home,$message) : write to permanent log for user; use
                   4969: critical subroutine
                   4970: 
                   4971: =back
                   4972: 
                   4973: =head2 Network Status Functions
                   4974: 
                   4975: =over 4
1.191     harris41 4976: 
                   4977: =item *
                   4978: 
                   4979: dirlist($uri) : return directory list based on URI
                   4980: 
                   4981: =item *
                   4982: 
1.243     albertel 4983: spareserver() : find server with least workload from spare.tab
                   4984: 
                   4985: =back
                   4986: 
                   4987: =head2 Apache Request
                   4988: 
                   4989: =over 4
1.191     harris41 4990: 
                   4991: =item *
                   4992: 
1.243     albertel 4993: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   4994: localhost, posts hash
                   4995: 
                   4996: =back
                   4997: 
                   4998: =head2 Data to String to Data
                   4999: 
                   5000: =over 4
1.191     harris41 5001: 
                   5002: =item *
                   5003: 
1.243     albertel 5004: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   5005: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 5006: 
                   5007: =item *
                   5008: 
1.243     albertel 5009: hashref2str($hashref) : convert a hashref into a string complete with
                   5010: escaping and '=' and '&' separators, supports elements that are
                   5011: arrayrefs and hashrefs
1.191     harris41 5012: 
                   5013: =item *
                   5014: 
1.243     albertel 5015: arrayref2str($arrayref) : convert an arrayref into a string complete
                   5016: with escaping and '&' separators, supports elements that are arrayrefs
                   5017: and hashrefs
1.191     harris41 5018: 
                   5019: =item *
                   5020: 
1.243     albertel 5021: str2hash($string) : convert string to hash using unescaping and
                   5022: splitting on '=' and '&', supports elements that are arrayrefs and
                   5023: hashrefs
1.191     harris41 5024: 
                   5025: =item *
                   5026: 
1.243     albertel 5027: str2array($string) : convert string to hash using unescaping and
                   5028: splitting on '&', supports elements that are arrayrefs and hashrefs
                   5029: 
                   5030: =back
                   5031: 
                   5032: =head2 Logging Routines
                   5033: 
                   5034: =over 4
                   5035: 
                   5036: These routines allow one to make log messages in the lonnet.log and
                   5037: lonnet.perm logfiles.
1.191     harris41 5038: 
                   5039: =item *
                   5040: 
1.243     albertel 5041: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 5042: 
                   5043: =item *
                   5044: 
1.243     albertel 5045: logthis() : append message to the normal lonnet.log file, it gets
                   5046: preiodically rolled over and deleted.
1.191     harris41 5047: 
                   5048: =item *
                   5049: 
1.243     albertel 5050: logperm() : append a permanent message to lonnet.perm.log, this log
                   5051: file never gets deleted by any automated portion of the system, only
                   5052: messages of critical importance should go in here.
                   5053: 
                   5054: =back
                   5055: 
                   5056: =head2 General File Helper Routines
                   5057: 
                   5058: =over 4
1.191     harris41 5059: 
                   5060: =item *
                   5061: 
1.243     albertel 5062: getfile($file) : returns the entire contents of a file or -1; it
                   5063: properly subscribes to and replicates the file if neccessary.
1.191     harris41 5064: 
                   5065: =item *
                   5066: 
1.243     albertel 5067: filelocation($dir,$file) : returns file system location of a file
                   5068: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   5069: directory that relative $file lookups are to looked in ($dir of /a/dir
                   5070: and a file of ../bob will become /a/bob)
1.191     harris41 5071: 
                   5072: =item *
                   5073: 
                   5074: hreflocation($dir,$file) : returns file system location or a URL; same as
                   5075: filelocation except for hrefs
                   5076: 
                   5077: =item *
                   5078: 
                   5079: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   5080: 
1.243     albertel 5081: =back
                   5082: 
                   5083: =head2 HTTP Helper Routines
                   5084: 
                   5085: =over 4
                   5086: 
1.191     harris41 5087: =item *
                   5088: 
                   5089: escape() : unpack non-word characters into CGI-compatible hex codes
                   5090: 
                   5091: =item *
                   5092: 
                   5093: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   5094: 
1.243     albertel 5095: =back
                   5096: 
                   5097: =head1 PRIVATE SUBROUTINES
                   5098: 
                   5099: =head2 Underlying communication routines (Shouldn't call)
                   5100: 
                   5101: =over 4
                   5102: 
                   5103: =item *
                   5104: 
                   5105: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   5106: 
                   5107: =item *
                   5108: 
                   5109: reply() : uses subreply to send a message to remote machine, logs all failures
                   5110: 
                   5111: =item *
                   5112: 
                   5113: critical() : passes a critical message to another server; if cannot
                   5114: get through then place message in connection buffer directory and
                   5115: returns con_delayed, if incapable of saving message, returns
                   5116: con_failed
                   5117: 
                   5118: =item *
                   5119: 
                   5120: reconlonc() : tries to reconnect lonc client processes.
                   5121: 
                   5122: =back
                   5123: 
                   5124: =head2 Resource Access Logging
                   5125: 
                   5126: =over 4
                   5127: 
                   5128: =item *
                   5129: 
                   5130: flushcourselogs() : flush (save) buffer logs and access logs
                   5131: 
                   5132: =item *
                   5133: 
                   5134: courselog($what) : save message for course in hash
                   5135: 
                   5136: =item *
                   5137: 
                   5138: courseacclog($what) : save message for course using &courselog().  Perform
                   5139: special processing for specific resource types (problems, exams, quizzes, etc).
                   5140: 
1.191     harris41 5141: =item *
                   5142: 
                   5143: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   5144: as a PerlChildExitHandler
1.243     albertel 5145: 
                   5146: =back
                   5147: 
                   5148: =head2 Other
                   5149: 
                   5150: =over 4
                   5151: 
                   5152: =item *
                   5153: 
                   5154: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 5155: 
                   5156: =back
                   5157: 
                   5158: =cut

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