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

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

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