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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.729   ! www         4: # $Id: lonnet.pm,v 1.728 2006/04/07 22:42:32 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.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.599     albertel   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
                     42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
                     55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729   ! www        88: {
        !            89:     my $logid;
        !            90:     sub instructor_log {
        !            91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
        !            92: 	$logid++;
        !            93: 	my $id=time().'00000'.$$.'00000'.$logid;
        !            94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
        !            95: 				    {
        !            96: 					$id.'_exe_uname' => $env{'user.name'},
        !            97: 					$id.'_exe_udom'  => $env{'user.domain'},
        !            98: 					$id.'_exe_time'  => time(),
        !            99: 					$id.'_exe_ip'    => $ENV{'REMOTE_ADDR'},
        !           100: 					$id.'_delflag'   => $delflag,
        !           101: 					$id.'_logentry'  => $storehash,
        !           102: 					$id.'_uname'     => $uname,
        !           103: 					$id.'_udom'      => $udom,
        !           104: 				    },
        !           105: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
        !           106: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
        !           107: 				    );
        !           108:     }
        !           109: }
1.1       albertel  110: 
1.163     harris41  111: sub logtouch {
                    112:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  113:     unless (-e "$execdir/logs/lonnet.log") {	
                    114: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  115: 	close $fh;
                    116:     }
                    117:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    118:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    119: }
                    120: 
1.1       albertel  121: sub logthis {
                    122:     my $message=shift;
                    123:     my $execdir=$perlvar{'lonDaemons'};
                    124:     my $now=time;
                    125:     my $local=localtime($now);
1.448     albertel  126:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    127: 	print $fh "$local ($$): $message\n";
                    128: 	close($fh);
                    129:     }
1.1       albertel  130:     return 1;
                    131: }
                    132: 
                    133: sub logperm {
                    134:     my $message=shift;
                    135:     my $execdir=$perlvar{'lonDaemons'};
                    136:     my $now=time;
                    137:     my $local=localtime($now);
1.448     albertel  138:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    139: 	print $fh "$now:$message:$local\n";
                    140: 	close($fh);
                    141:     }
1.1       albertel  142:     return 1;
                    143: }
                    144: 
                    145: # -------------------------------------------------- Non-critical communication
                    146: sub subreply {
                    147:     my ($cmd,$server)=@_;
1.704     albertel  148:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      149:     #
                    150:     #  With loncnew process trimming, there's a timing hole between lonc server
                    151:     #  process exit and the master server picking up the listen on the AF_UNIX
                    152:     #  socket.  In that time interval, a lock file will exist:
                    153: 
                    154:     my $lockfile=$peerfile.".lock";
                    155:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    156: 	sleep(1);
                    157:     }
                    158:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      159:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      160:     #
1.550     foxr      161:     #   We'll give the connection a few tries before abandoning it.  If
                    162:     #   connection is not possible, we'll con_lost back to the client.
                    163:     #   
                    164:     my $client;
                    165:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    166: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    167: 				      Type    => SOCK_STREAM,
                    168: 				      Timeout => 10);
                    169: 	if($client) {
                    170: 	    last;		# Connected!
                    171: 	}
                    172: 	sleep(1);		# Try again later if failed connection.
                    173:     }
                    174:     my $answer;
                    175:     if ($client) {
1.704     albertel  176: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      177: 	$answer=<$client>;
                    178: 	if (!$answer) { $answer="con_lost"; }
                    179: 	chomp($answer);
                    180:     } else {
                    181: 	$answer = 'con_lost';	# Failed connection.
                    182:     }
1.1       albertel  183:     return $answer;
                    184: }
                    185: 
                    186: sub reply {
                    187:     my ($cmd,$server)=@_;
1.205     www       188:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  189:     my $answer=subreply($cmd,$server);
1.65      www       190:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  191:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       192:                 " $cmd to $server returned $answer</font>");
                    193:     }
1.1       albertel  194:     return $answer;
                    195: }
                    196: 
                    197: # ----------------------------------------------------------- Send USR1 to lonc
                    198: 
                    199: sub reconlonc {
                    200:     my $peerfile=shift;
                    201:     &logthis("Trying to reconnect for $peerfile");
                    202:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  203:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  204: 	my $loncpid=<$fh>;
                    205:         chomp($loncpid);
                    206:         if (kill 0 => $loncpid) {
                    207: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    208:             kill USR1 => $loncpid;
                    209:             sleep 1;
                    210:             if (-e "$peerfile") { return; }
                    211:             &logthis("$peerfile still not there, give it another try");
                    212:             sleep 5;
                    213:             if (-e "$peerfile") { return; }
1.12      www       214:             &logthis(
1.672     albertel  215:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  216:         } else {
1.12      www       217: 	    &logthis(
1.672     albertel  218:                "<font color=\"blue\">WARNING:".
1.12      www       219:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  220:         }
                    221:     } else {
1.672     albertel  222:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  223:     }
                    224: }
                    225: 
                    226: # ------------------------------------------------------ Critical communication
1.12      www       227: 
1.1       albertel  228: sub critical {
                    229:     my ($cmd,$server)=@_;
1.89      www       230:     unless ($hostname{$server}) {
1.672     albertel  231:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       232:                " Critical message to unknown server ($server)</font>");
                    233:         return 'no_such_host';
                    234:     }
1.1       albertel  235:     my $answer=reply($cmd,$server);
                    236:     if ($answer eq 'con_lost') {
                    237: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  238: 	my $answer=reply($cmd,$server);
1.1       albertel  239:         if ($answer eq 'con_lost') {
                    240:             my $now=time;
                    241:             my $middlename=$cmd;
1.5       www       242:             $middlename=substr($middlename,0,16);
1.1       albertel  243:             $middlename=~s/\W//g;
                    244:             my $dfilename=
1.305     www       245:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    246:             $dumpcount++;
1.1       albertel  247:             {
1.448     albertel  248: 		my $dfh;
                    249: 		if (open($dfh,">$dfilename")) {
                    250: 		    print $dfh "$cmd\n"; 
                    251: 		    close($dfh);
                    252: 		}
1.1       albertel  253:             }
                    254:             sleep 2;
                    255:             my $wcmd='';
                    256:             {
1.448     albertel  257: 		my $dfh;
                    258: 		if (open($dfh,"<$dfilename")) {
                    259: 		    $wcmd=<$dfh>; 
                    260: 		    close($dfh);
                    261: 		}
1.1       albertel  262:             }
                    263:             chomp($wcmd);
1.7       www       264:             if ($wcmd eq $cmd) {
1.672     albertel  265: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       266:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  267:                 &logperm("D:$server:$cmd");
                    268: 	        return 'con_delayed';
                    269:             } else {
1.672     albertel  270:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       271:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  272:                 &logperm("F:$server:$cmd");
                    273:                 return 'con_failed';
                    274:             }
                    275:         }
                    276:     }
                    277:     return $answer;
1.405     albertel  278: }
                    279: 
1.374     www       280: # ------------------------------------------- Transfer profile into environment
                    281: 
                    282: sub transfer_profile_to_env {
                    283:     my ($lonidsdir,$handle)=@_;
1.720     albertel  284:     if (!defined($lonidsdir)) {
                    285: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    286:     }
                    287:     if (!defined($handle)) {
                    288:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    289:     }
                    290: 
1.374     www       291:     my @profile;
                    292:     {
1.448     albertel  293: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       294: 	flock($idf,LOCK_SH);
                    295: 	@profile=<$idf>;
1.448     albertel  296: 	close($idf);
1.374     www       297:     }
                    298:     my $envi;
1.433     matthew   299:     my %Remove;
1.374     www       300:     for ($envi=0;$envi<=$#profile;$envi++) {
                    301: 	chomp($profile[$envi]);
1.690     albertel  302: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  303: 	$envname=&unescape($envname);
                    304: 	$envvalue=&unescape($envvalue);
1.619     albertel  305: 	$env{$envname} = $envvalue;
1.433     matthew   306:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    307:             if ($time < time-300) {
                    308:                 $Remove{$key}++;
                    309:             }
                    310:         }
                    311:     }
1.619     albertel  312:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   313:     foreach my $expired_key (keys(%Remove)) {
                    314:         &delenv($expired_key);
1.374     www       315:     }
1.1       albertel  316: }
                    317: 
1.5       www       318: # ---------------------------------------------------------- Append Environment
                    319: 
                    320: sub appenv {
1.6       www       321:     my %newenv=@_;
1.692     albertel  322:     foreach my $key (keys(%newenv)) {
                    323: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  324:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  325:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       326:                 .'</font>');
1.692     albertel  327: 	    delete($newenv{$key});
1.35      www       328:         } else {
1.692     albertel  329:             $env{$key}=$newenv{$key};
1.35      www       330:         }
1.191     harris41  331:     }
1.95      www       332: 
                    333:     my $lockfh;
1.620     albertel  334:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  335: 	return 'error: '.$!;
1.95      www       336:     }
                    337:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  338:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       339:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  340:          close($lockfh);
1.95      www       341:          return 'error: '.$!;
                    342:     }
                    343: 
1.6       www       344:     my @oldenv;
                    345:     {
1.448     albertel  346: 	my $fh;
1.620     albertel  347: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  348: 	    return 'error: '.$!;
                    349: 	}
                    350: 	@oldenv=<$fh>;
                    351: 	close($fh);
1.6       www       352:     }
                    353:     for (my $i=0; $i<=$#oldenv; $i++) {
                    354:         chomp($oldenv[$i]);
1.9       www       355:         if ($oldenv[$i] ne '') {
1.690     albertel  356: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.726     albertel  357: 	    $name=&unescape($name);
                    358: 	    $value=&unescape($value);
1.448     albertel  359: 	    unless (defined($newenv{$name})) {
                    360: 		$newenv{$name}=$value;
                    361: 	    }
1.9       www       362:         }
1.6       www       363:     }
                    364:     {
1.448     albertel  365: 	my $fh;
1.620     albertel  366: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  367: 	    return 'error';
                    368: 	}
                    369: 	my $newname;
                    370: 	foreach $newname (keys %newenv) {
1.726     albertel  371: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
1.448     albertel  372: 	}
                    373: 	close($fh);
1.56      www       374:     }
1.448     albertel  375: 	
                    376:     close($lockfh);
1.56      www       377:     return 'ok';
                    378: }
                    379: # ----------------------------------------------------- Delete from Environment
                    380: 
                    381: sub delenv {
                    382:     my $delthis=shift;
                    383:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  384:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       385:                 "Attempt to delete from environment ".$delthis);
                    386:         return 'error';
                    387:     }
                    388:     my @oldenv;
                    389:     {
1.448     albertel  390: 	my $fh;
1.620     albertel  391: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  392: 	    return 'error';
                    393: 	}
                    394: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  395: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  396: 		     'Could not obtain shared lock in delenv: '.$!);
                    397: 	    close($fh);
                    398: 	    return 'error: '.$!;
                    399: 	}
                    400: 	@oldenv=<$fh>;
                    401: 	close($fh);
1.56      www       402:     }
                    403:     {
1.448     albertel  404: 	my $fh;
1.620     albertel  405: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  406: 	    return 'error';
                    407: 	}
                    408: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  409: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  410: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    411: 	    close($fh);
                    412: 	    return 'error: '.$!;
                    413: 	}
1.692     albertel  414: 	foreach my $cur_key (@oldenv) {
1.726     albertel  415: 	    my $unescaped_cur_key = &unescape($cur_key);
                    416: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    417:                 my ($key) = split('=',$cur_key,2);
                    418: 		$key = &unescape($key);
1.619     albertel  419:                 delete($env{$key});
1.473     matthew   420:             } else {
1.692     albertel  421:                 print $fh $cur_key; 
1.473     matthew   422:             }
1.448     albertel  423: 	}
                    424: 	close($fh);
1.5       www       425:     }
                    426:     return 'ok';
1.369     albertel  427: }
                    428: 
                    429: # ------------------------------------------ Find out current server userload
                    430: # there is a copy in lond
                    431: sub userload {
                    432:     my $numusers=0;
                    433:     {
                    434: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    435: 	my $filename;
                    436: 	my $curtime=time;
                    437: 	while ($filename=readdir(LONIDS)) {
                    438: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  439: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  440: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  441: 	}
                    442: 	closedir(LONIDS);
                    443:     }
                    444:     my $userloadpercent=0;
                    445:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    446:     if ($maxuserload) {
1.371     albertel  447: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  448:     }
1.372     albertel  449:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  450:     return $userloadpercent;
1.283     www       451: }
                    452: 
                    453: # ------------------------------------------ Fight off request when overloaded
                    454: 
                    455: sub overloaderror {
                    456:     my ($r,$checkserver)=@_;
                    457:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    458:     my $loadavg;
                    459:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  460:        open(my $loadfile,'/proc/loadavg');
1.283     www       461:        $loadavg=<$loadfile>;
                    462:        $loadavg =~ s/\s.*//g;
1.285     matthew   463:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  464:        close($loadfile);
1.283     www       465:     } else {
                    466:        $loadavg=&reply('load',$checkserver);
                    467:     }
1.285     matthew   468:     my $overload=$loadavg-100;
1.283     www       469:     if ($overload>0) {
1.285     matthew   470: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       471:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       472:         return 413;
1.283     www       473:     }    
                    474:     return '';
1.5       www       475: }
1.1       albertel  476: 
                    477: # ------------------------------ Find server with least workload from spare.tab
1.11      www       478: 
1.1       albertel  479: sub spareserver {
1.670     albertel  480:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  481:     my $tryserver;
                    482:     my $spareserver='';
1.370     albertel  483:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    484:     my $lowestserver=$loadpercent > $userloadpercent?
                    485: 	             $loadpercent :  $userloadpercent;
1.670     albertel  486:     foreach $tryserver (keys(%spareid)) {
                    487: 	my $loadans=&reply('load',$tryserver);
                    488: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  489: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    490: 	    next; #didn't get a number from the server
                    491: 	}
                    492: 	my $answer;
                    493: 	if ($loadans =~ /\d/) {
                    494: 	    if ($userloadans =~ /\d/) {
                    495: 		#both are numbers, pick the bigger one
                    496: 		$answer=$loadans > $userloadans?
                    497: 		    $loadans :  $userloadans;
                    498: 	    } else {
                    499: 		$answer = $loadans;
                    500: 	    }
                    501: 	} else {
                    502: 	    $answer = $userloadans;
                    503: 	}
                    504: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  505: 	    if ($want_server_name) {
                    506: 		$spareserver=$tryserver;
                    507: 	    } else {
                    508: 		$spareserver="http://$hostname{$tryserver}";
                    509: 	    }
1.411     albertel  510: 	    $lowestserver=$answer;
                    511: 	}
1.370     albertel  512:     }
1.1       albertel  513:     return $spareserver;
1.202     matthew   514: }
                    515: 
                    516: # --------------------------------------------- Try to change a user's password
                    517: 
                    518: sub changepass {
                    519:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    520:     $currentpass = &escape($currentpass);
                    521:     $newpass     = &escape($newpass);
                    522:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    523: 		       $server);
                    524:     if (! $answer) {
                    525: 	&logthis("No reply on password change request to $server ".
                    526: 		 "by $uname in domain $udom.");
                    527:     } elsif ($answer =~ "^ok") {
                    528:         &logthis("$uname in $udom successfully changed their password ".
                    529: 		 "on $server.");
                    530:     } elsif ($answer =~ "^pwchange_failure") {
                    531: 	&logthis("$uname in $udom was unable to change their password ".
                    532: 		 "on $server.  The action was blocked by either lcpasswd ".
                    533: 		 "or pwchange");
                    534:     } elsif ($answer =~ "^non_authorized") {
                    535:         &logthis("$uname in $udom did not get their password correct when ".
                    536: 		 "attempting to change it on $server.");
                    537:     } elsif ($answer =~ "^auth_mode_error") {
                    538:         &logthis("$uname in $udom attempted to change their password despite ".
                    539: 		 "not being locally or internally authenticated on $server.");
                    540:     } elsif ($answer =~ "^unknown_user") {
                    541:         &logthis("$uname in $udom attempted to change their password ".
                    542: 		 "on $server but were unable to because $server is not ".
                    543: 		 "their home server.");
                    544:     } elsif ($answer =~ "^refused") {
                    545: 	&logthis("$server refused to change $uname in $udom password because ".
                    546: 		 "it was sent an unencrypted request to change the password.");
                    547:     }
                    548:     return $answer;
1.1       albertel  549: }
                    550: 
1.169     harris41  551: # ----------------------- Try to determine user's current authentication scheme
                    552: 
                    553: sub queryauthenticate {
                    554:     my ($uname,$udom)=@_;
1.456     albertel  555:     my $uhome=&homeserver($uname,$udom);
                    556:     if (!$uhome) {
                    557: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    558: 	return 'no_host';
                    559:     }
                    560:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    561:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    562: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  563:     }
1.456     albertel  564:     return $answer;
1.169     harris41  565: }
                    566: 
1.1       albertel  567: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       568: 
1.1       albertel  569: sub authenticate {
                    570:     my ($uname,$upass,$udom)=@_;
1.12      www       571:     $upass=escape($upass);
1.199     www       572:     $uname=~s/\W//g;
1.471     albertel  573:     my $uhome=&homeserver($uname,$udom);
                    574:     if (!$uhome) {
                    575: 	&logthis("User $uname at $udom is unknown in authenticate");
                    576: 	return 'no_host';
1.1       albertel  577:     }
1.471     albertel  578:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    579:     if ($answer eq 'authorized') {
                    580: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    581: 	return $uhome; 
                    582:     }
                    583:     if ($answer eq 'non_authorized') {
                    584: 	&logthis("User $uname at $udom rejected by $uhome");
                    585: 	return 'no_host'; 
1.9       www       586:     }
1.471     albertel  587:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  588:     return 'no_host';
                    589: }
                    590: 
                    591: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       592: 
1.599     albertel  593: my %homecache;
1.1       albertel  594: sub homeserver {
1.230     stredwic  595:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  596:     my $index="$uname:$udom";
1.426     albertel  597: 
1.599     albertel  598:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  599:     my $tryserver;
                    600:     foreach $tryserver (keys %libserv) {
1.230     stredwic  601:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  602: 		 exists($badServerCache{$tryserver}));
1.1       albertel  603: 	if ($hostdom{$tryserver} eq $udom) {
                    604:            my $answer=reply("home:$udom:$uname",$tryserver);
                    605:            if ($answer eq 'found') { 
1.599     albertel  606: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  607:            } elsif ($answer eq 'no_host') {
                    608: 	       $badServerCache{$tryserver}=1;
1.221     matthew   609:            }
1.1       albertel  610:        }
                    611:     }    
                    612:     return 'no_host';
1.70      www       613: }
                    614: 
                    615: # ------------------------------------- Find the usernames behind a list of IDs
                    616: 
                    617: sub idget {
                    618:     my ($udom,@ids)=@_;
                    619:     my %returnhash=();
                    620:     
                    621:     my $tryserver;
                    622:     foreach $tryserver (keys %libserv) {
                    623:        if ($hostdom{$tryserver} eq $udom) {
                    624: 	  my $idlist=join('&',@ids);
                    625:           $idlist=~tr/A-Z/a-z/; 
                    626: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    627:           my @answer=();
1.76      www       628:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       629: 	      @answer=split(/\&/,$reply);
                    630:           }                    ;
                    631:           my $i;
                    632:           for ($i=0;$i<=$#ids;$i++) {
                    633:               if ($answer[$i]) {
                    634: 		  $returnhash{$ids[$i]}=$answer[$i];
                    635:               } 
                    636:           }
                    637:        }
                    638:     }    
                    639:     return %returnhash;
                    640: }
                    641: 
                    642: # ------------------------------------- Find the IDs behind a list of usernames
                    643: 
                    644: sub idrget {
                    645:     my ($udom,@unames)=@_;
                    646:     my %returnhash=();
1.191     harris41  647:     foreach (@unames) {
1.70      www       648:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  649:     }
1.70      www       650:     return %returnhash;
                    651: }
                    652: 
                    653: # ------------------------------- Store away a list of names and associated IDs
                    654: 
                    655: sub idput {
                    656:     my ($udom,%ids)=@_;
                    657:     my %servers=();
1.191     harris41  658:     foreach (keys %ids) {
1.487     albertel  659: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       660:         my $uhom=&homeserver($_,$udom);
                    661:         if ($uhom ne 'no_host') {
                    662:             my $id=&escape($ids{$_});
                    663:             $id=~tr/A-Z/a-z/;
                    664:             my $unam=&escape($_);
                    665: 	    if ($servers{$uhom}) {
                    666: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    667:             } else {
                    668:                 $servers{$uhom}=$id.'='.$unam;
                    669:             }
                    670:         }
1.191     harris41  671:     }
                    672:     foreach (keys %servers) {
1.70      www       673:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  674:     }
1.344     www       675: }
                    676: 
                    677: # --------------------------------------------------- Assign a key to a student
                    678: 
                    679: sub assign_access_key {
1.364     www       680: #
                    681: # a valid key looks like uname:udom#comments
                    682: # comments are being appended
                    683: #
1.498     www       684:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    685:     $kdom=
1.620     albertel  686:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       687:     $knum=
1.620     albertel  688:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       689:     $cdom=
1.620     albertel  690:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       691:     $cnum=
1.620     albertel  692:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    693:     $udom=$env{'user.name'} unless (defined($udom));
                    694:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       695:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       696:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  697:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       698:                                                   # assigned to this person
                    699:                                                   # - this should not happen,
1.345     www       700:                                                   # unless something went wrong
                    701:                                                   # the first time around
                    702: # ready to assign
1.364     www       703:         $logentry=$1.'; '.$logentry;
1.496     www       704:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       705:                                                  $kdom,$knum) eq 'ok') {
1.345     www       706: # key now belongs to user
1.346     www       707: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       708:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    709:                 &appenv('environment.'.$envkey => $ckey);
                    710:                 return 'ok';
                    711:             } else {
                    712:                 return 
                    713:   'error: Count not permanently assign key, will need to be re-entered later.';
                    714: 	    }
                    715:         } else {
                    716:             return 'error: Could not assign key, try again later.';
                    717:         }
1.364     www       718:     } elsif (!$existing{$ckey}) {
1.345     www       719: # the key does not exist
                    720: 	return 'error: The key does not exist';
                    721:     } else {
                    722: # the key is somebody else's
                    723: 	return 'error: The key is already in use';
                    724:     }
1.344     www       725: }
                    726: 
1.364     www       727: # ------------------------------------------ put an additional comment on a key
                    728: 
                    729: sub comment_access_key {
                    730: #
                    731: # a valid key looks like uname:udom#comments
                    732: # comments are being appended
                    733: #
                    734:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    735:     $cdom=
1.620     albertel  736:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       737:     $cnum=
1.620     albertel  738:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       739:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    740:     if ($existing{$ckey}) {
                    741:         $existing{$ckey}.='; '.$logentry;
                    742: # ready to assign
1.367     www       743:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       744:                                                  $cdom,$cnum) eq 'ok') {
                    745: 	    return 'ok';
                    746:         } else {
                    747: 	    return 'error: Count not store comment.';
                    748:         }
                    749:     } else {
                    750: # the key does not exist
                    751: 	return 'error: The key does not exist';
                    752:     }
                    753: }
                    754: 
1.344     www       755: # ------------------------------------------------------ Generate a set of keys
                    756: 
                    757: sub generate_access_keys {
1.364     www       758:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       759:     $cdom=
1.620     albertel  760:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       761:     $cnum=
1.620     albertel  762:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       763:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       764:     unless (($cdom) && ($cnum)) { return 0; }
                    765:     if ($number>10000) { return 0; }
                    766:     sleep(2); # make sure don't get same seed twice
                    767:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    768:     my $total=0;
                    769:     for (my $i=1;$i<=$number;$i++) {
                    770:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    771:                   sprintf("%lx",int(100000*rand)).'-'.
                    772:                   sprintf("%lx",int(100000*rand));
                    773:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    774:        $newkey=~s/0/h/g; # and also 0 and O
                    775:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    776:        if ($existing{$newkey}) {
                    777:            $i--;
                    778:        } else {
1.364     www       779: 	  if (&put('accesskeys',
                    780:               { $newkey => '# generated '.localtime().
1.620     albertel  781:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       782:                            '; '.$logentry },
                    783: 		   $cdom,$cnum) eq 'ok') {
1.344     www       784:               $total++;
                    785: 	  }
                    786:        }
                    787:     }
1.620     albertel  788:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       789:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    790:     return $total;
                    791: }
                    792: 
                    793: # ------------------------------------------------------- Validate an accesskey
                    794: 
                    795: sub validate_access_key {
                    796:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    797:     $cdom=
1.620     albertel  798:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       799:     $cnum=
1.620     albertel  800:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    801:     $udom=$env{'user.domain'} unless (defined($udom));
                    802:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       803:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  804:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       805: }
                    806: 
                    807: # ------------------------------------- Find the section of student in a course
1.652     albertel  808: sub devalidate_getsection_cache {
                    809:     my ($udom,$unam,$courseid)=@_;
                    810:     $courseid=~s/\_/\//g;
                    811:     $courseid=~s/^(\w)/\/$1/;
                    812:     my $hashid="$udom:$unam:$courseid";
                    813:     &devalidate_cache_new('getsection',$hashid);
                    814: }
1.298     matthew   815: 
                    816: sub getsection {
                    817:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  818:     my $cachetime=1800;
1.298     matthew   819:     $courseid=~s/\_/\//g;
                    820:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  821: 
                    822:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  823:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  824:     if (defined($cached)) { return $result; }
                    825: 
1.298     matthew   826:     my %Pending; 
                    827:     my %Expired;
                    828:     #
                    829:     # Each role can either have not started yet (pending), be active, 
                    830:     #    or have expired.
                    831:     #
                    832:     # If there is an active role, we are done.
                    833:     #
                    834:     # If there is more than one role which has not started yet, 
                    835:     #     choose the one which will start sooner
                    836:     # If there is one role which has not started yet, return it.
                    837:     #
                    838:     # If there is more than one expired role, choose the one which ended last.
                    839:     # If there is a role which has expired, return it.
                    840:     #
                    841:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    842:                         &homeserver($unam,$udom)))) {
                    843:         my ($key,$value)=split(/\=/,$_);
                    844:         $key=&unescape($key);
1.479     albertel  845:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   846:         my $section=$1;
                    847:         if ($key eq $courseid.'_st') { $section=''; }
                    848:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    849:         my $now=time;
1.548     albertel  850:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   851:             $Expired{$end}=$section;
                    852:             next;
                    853:         }
1.548     albertel  854:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   855:             $Pending{$start}=$section;
                    856:             next;
                    857:         }
1.599     albertel  858:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   859:     }
                    860:     #
                    861:     # Presumedly there will be few matching roles from the above
                    862:     # loop and the sorting time will be negligible.
                    863:     if (scalar(keys(%Pending))) {
                    864:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  865:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   866:     } 
                    867:     if (scalar(keys(%Expired))) {
                    868:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    869:         my $time = pop(@sorted);
1.599     albertel  870:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   871:     }
1.599     albertel  872:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   873: }
1.70      www       874: 
1.599     albertel  875: sub save_cache {
                    876:     &purge_remembered();
1.722     albertel  877:     #&Apache::loncommon::validate_page();
1.620     albertel  878:     undef(%env);
1.599     albertel  879: }
1.452     albertel  880: 
1.599     albertel  881: my $to_remember=-1;
                    882: my %remembered;
                    883: my %accessed;
                    884: my $kicks=0;
                    885: my $hits=0;
                    886: sub devalidate_cache_new {
                    887:     my ($name,$id,$debug) = @_;
                    888:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    889:     $id=&escape($name.':'.$id);
                    890:     $memcache->delete($id);
                    891:     delete($remembered{$id});
                    892:     delete($accessed{$id});
                    893: }
                    894: 
                    895: sub is_cached_new {
                    896:     my ($name,$id,$debug) = @_;
                    897:     $id=&escape($name.':'.$id);
                    898:     if (exists($remembered{$id})) {
                    899: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    900: 	$accessed{$id}=[&gettimeofday()];
                    901: 	$hits++;
                    902: 	return ($remembered{$id},1);
                    903:     }
                    904:     my $value = $memcache->get($id);
                    905:     if (!(defined($value))) {
                    906: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  907: 	return (undef,undef);
1.416     albertel  908:     }
1.599     albertel  909:     if ($value eq '__undef__') {
                    910: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    911: 	$value=undef;
                    912:     }
                    913:     &make_room($id,$value,$debug);
                    914:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    915:     return ($value,1);
                    916: }
                    917: 
                    918: sub do_cache_new {
                    919:     my ($name,$id,$value,$time,$debug) = @_;
                    920:     $id=&escape($name.':'.$id);
                    921:     my $setvalue=$value;
                    922:     if (!defined($setvalue)) {
                    923: 	$setvalue='__undef__';
                    924:     }
1.623     albertel  925:     if (!defined($time) ) {
                    926: 	$time=600;
                    927:     }
1.599     albertel  928:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  929:     $memcache->set($id,$setvalue,$time);
                    930:     # need to make a copy of $value
                    931:     #&make_room($id,$value,$debug);
1.599     albertel  932:     return $value;
                    933: }
                    934: 
                    935: sub make_room {
                    936:     my ($id,$value,$debug)=@_;
                    937:     $remembered{$id}=$value;
                    938:     if ($to_remember<0) { return; }
                    939:     $accessed{$id}=[&gettimeofday()];
                    940:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    941:     my $to_kick;
                    942:     my $max_time=0;
                    943:     foreach my $other (keys(%accessed)) {
                    944: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    945: 	    $to_kick=$other;
                    946: 	    $max_time=&tv_interval($accessed{$other});
                    947: 	}
                    948:     }
                    949:     delete($remembered{$to_kick});
                    950:     delete($accessed{$to_kick});
                    951:     $kicks++;
                    952:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  953:     return;
                    954: }
                    955: 
1.599     albertel  956: sub purge_remembered {
1.604     albertel  957:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    958:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  959:     undef(%remembered);
                    960:     undef(%accessed);
1.428     albertel  961: }
1.70      www       962: # ------------------------------------- Read an entry from a user's environment
                    963: 
                    964: sub userenvironment {
                    965:     my ($udom,$unam,@what)=@_;
                    966:     my %returnhash=();
                    967:     my @answer=split(/\&/,
                    968:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    969:                       &homeserver($unam,$udom)));
                    970:     my $i;
                    971:     for ($i=0;$i<=$#what;$i++) {
                    972: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    973:     }
                    974:     return %returnhash;
1.1       albertel  975: }
                    976: 
1.617     albertel  977: # ---------------------------------------------------------- Get a studentphoto
                    978: sub studentphoto {
                    979:     my ($udom,$unam,$ext) = @_;
                    980:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   981:     if (defined($env{'request.course.id'})) {
1.708     raeburn   982:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   983:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    984:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    985:             } else {
                    986:                 my ($result,$perm_reqd)=
1.707     albertel  987: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   988:                 if ($result eq 'ok') {
                    989:                     if (!($perm_reqd eq 'yes')) {
                    990:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    991:                     }
                    992:                 }
                    993:             }
                    994:         }
                    995:     } else {
                    996:         my ($result,$perm_reqd) = 
1.707     albertel  997: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   998:         if ($result eq 'ok') {
                    999:             if (!($perm_reqd eq 'yes')) {
                   1000:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1001:             }
                   1002:         }
                   1003:     }
                   1004:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1005: }
                   1006: 
                   1007: sub retrievestudentphoto {
                   1008:     my ($udom,$unam,$ext,$type) = @_;
                   1009:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1010:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1011:     if ($ret eq 'ok') {
                   1012:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1013:         if ($type eq 'thumbnail') {
                   1014:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1015:         }
                   1016:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1017:         return $tokenurl;
                   1018:     } else {
                   1019:         if ($type eq 'thumbnail') {
                   1020:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1021:         } else { 
                   1022:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1023:         }
1.617     albertel 1024:     }
                   1025: }
                   1026: 
1.263     www      1027: # -------------------------------------------------------------------- New chat
                   1028: 
                   1029: sub chatsend {
1.724     raeburn  1030:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1031:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1032:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1033:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1034:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1035: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1036: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1037: }
                   1038: 
                   1039: # ------------------------------------------ Find current version of a resource
                   1040: 
                   1041: sub getversion {
                   1042:     my $fname=&clutter(shift);
                   1043:     unless ($fname=~/^\/res\//) { return -1; }
                   1044:     return &currentversion(&filelocation('',$fname));
                   1045: }
                   1046: 
                   1047: sub currentversion {
                   1048:     my $fname=shift;
1.599     albertel 1049:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1050:     if (defined($cached)) { return $result; }
1.292     www      1051:     my $author=$fname;
                   1052:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1053:     my ($udom,$uname)=split(/\//,$author);
                   1054:     my $home=homeserver($uname,$udom);
                   1055:     if ($home eq 'no_host') { 
                   1056:         return -1; 
                   1057:     }
                   1058:     my $answer=reply("currentversion:$fname",$home);
                   1059:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1060: 	return -1;
                   1061:     }
1.599     albertel 1062:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1063: }
                   1064: 
1.1       albertel 1065: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1066: 
1.1       albertel 1067: sub subscribe {
                   1068:     my $fname=shift;
1.312     www      1069:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1070:     $fname=~s/[\n\r]//g;
1.1       albertel 1071:     my $author=$fname;
                   1072:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1073:     my ($udom,$uname)=split(/\//,$author);
                   1074:     my $home=homeserver($uname,$udom);
1.335     albertel 1075:     if ($home eq 'no_host') {
                   1076:         return 'not_found';
1.1       albertel 1077:     }
                   1078:     my $answer=reply("sub:$fname",$home);
1.64      www      1079:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1080: 	$answer.=' by '.$home;
                   1081:     }
1.1       albertel 1082:     return $answer;
                   1083: }
                   1084:     
1.8       www      1085: # -------------------------------------------------------------- Replicate file
                   1086: 
                   1087: sub repcopy {
                   1088:     my $filename=shift;
1.23      www      1089:     $filename=~s/\/+/\//g;
1.607     raeburn  1090:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1091:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1092:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1093: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1094: 	return &repcopy_userfile($filename);
                   1095:     }
1.532     albertel 1096:     $filename=~s/[\n\r]//g;
1.8       www      1097:     my $transname="$filename.in.transfer";
1.607     raeburn  1098:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1099:     my $remoteurl=subscribe($filename);
1.64      www      1100:     if ($remoteurl =~ /^con_lost by/) {
                   1101: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1102:            return 'unavailable';
1.8       www      1103:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1104: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1105: 	   return 'not_found';
1.64      www      1106:     } elsif ($remoteurl =~ /^rejected by/) {
                   1107: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1108:            return 'forbidden';
1.20      www      1109:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1110:            return 'ok';
1.8       www      1111:     } else {
1.290     www      1112:         my $author=$filename;
                   1113:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1114:         my ($udom,$uname)=split(/\//,$author);
                   1115:         my $home=homeserver($uname,$udom);
                   1116:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1117:            my @parts=split(/\//,$filename);
                   1118:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1119:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1120:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1121: 	       return 'bad_request';
1.8       www      1122:            }
                   1123:            my $count;
                   1124:            for ($count=5;$count<$#parts;$count++) {
                   1125:                $path.="/$parts[$count]";
                   1126:                if ((-e $path)!=1) {
                   1127: 		   mkdir($path,0777);
                   1128:                }
                   1129:            }
                   1130:            my $ua=new LWP::UserAgent;
                   1131:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1132:            my $response=$ua->request($request,$transname);
                   1133:            if ($response->is_error()) {
                   1134: 	       unlink($transname);
                   1135:                my $message=$response->status_line;
1.672     albertel 1136:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1137:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1138:                return 'unavailable';
1.8       www      1139:            } else {
1.16      www      1140: 	       if ($remoteurl!~/\.meta$/) {
                   1141:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1142:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1143:                   if ($mresponse->is_error()) {
                   1144: 		      unlink($filename.'.meta');
                   1145:                       &logthis(
1.672     albertel 1146:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1147:                   }
                   1148: 	       }
1.8       www      1149:                rename($transname,$filename);
1.607     raeburn  1150:                return 'ok';
1.8       www      1151:            }
1.290     www      1152:        }
1.8       www      1153:     }
1.330     www      1154: }
                   1155: 
                   1156: # ------------------------------------------------ Get server side include body
                   1157: sub ssi_body {
1.381     albertel 1158:     my ($filelink,%form)=@_;
1.606     matthew  1159:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1160:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1161:     }
1.330     www      1162:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1163:                                      &ssi($filelink,%form));
1.565     albertel 1164:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1165:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1166:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1167:     return $output;
1.8       www      1168: }
                   1169: 
1.15      www      1170: # --------------------------------------------------------- Server Side Include
                   1171: 
                   1172: sub ssi {
                   1173: 
1.23      www      1174:     my ($fn,%form)=@_;
1.15      www      1175: 
                   1176:     my $ua=new LWP::UserAgent;
1.23      www      1177:     
                   1178:     my $request;
1.711     albertel 1179: 
                   1180:     $form{'no_update_last_known'}=1;
                   1181: 
1.23      www      1182:     if (%form) {
                   1183:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1184:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1185:     } else {
                   1186:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1187:     }
                   1188: 
1.15      www      1189:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1190:     my $response=$ua->request($request);
                   1191: 
1.324     www      1192:     return $response->content;
                   1193: }
                   1194: 
                   1195: sub externalssi {
                   1196:     my ($url)=@_;
                   1197:     my $ua=new LWP::UserAgent;
                   1198:     my $request=new HTTP::Request('GET',$url);
                   1199:     my $response=$ua->request($request);
1.15      www      1200:     return $response->content;
                   1201: }
1.254     www      1202: 
1.492     albertel 1203: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1204: 
                   1205: sub allowuploaded {
                   1206:     my ($srcurl,$url)=@_;
                   1207:     $url=&clutter(&declutter($url));
                   1208:     my $dir=$url;
                   1209:     $dir=~s/\/[^\/]+$//;
                   1210:     my %httpref=();
                   1211:     my $httpurl=&hreflocation('',$url);
                   1212:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1213:     &Apache::lonnet::appenv(%httpref);
1.254     www      1214: }
1.477     raeburn  1215: 
1.478     albertel 1216: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1217: # input: action, courseID, current domain, intended
1.637     raeburn  1218: #        path to file, source of file, instruction to parse file for objects,
                   1219: #        ref to hash for embedded objects,
                   1220: #        ref to hash for codebase of java objects.
                   1221: #
1.485     raeburn  1222: # output: url to file (if action was uploaddoc), 
                   1223: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1224: #
1.478     albertel 1225: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1226: # course.
1.477     raeburn  1227: #
1.478     albertel 1228: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1229: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1230: #          course's home server.
1.477     raeburn  1231: #
1.478     albertel 1232: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1233: #          be copied from $source (current location) to 
                   1234: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1235: #         and will then be copied to
                   1236: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1237: #         course's home server.
1.485     raeburn  1238: #
1.481     raeburn  1239: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1240: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1241: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1242: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1243: #         in course's home server.
1.637     raeburn  1244: #
1.477     raeburn  1245: 
                   1246: sub process_coursefile {
1.638     albertel 1247:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1248:     my $fetchresult;
1.638     albertel 1249:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1250:     if ($action eq 'propagate') {
1.638     albertel 1251:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1252: 			     $home);
1.481     raeburn  1253:     } else {
1.477     raeburn  1254:         my $fpath = '';
                   1255:         my $fname = $file;
1.478     albertel 1256:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1257:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1258:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1259:         if ($action eq 'copy') {
                   1260:             if ($source eq '') {
                   1261:                 $fetchresult = 'no source file';
                   1262:                 return $fetchresult;
                   1263:             } else {
                   1264:                 my $destination = $filepath.'/'.$fname;
                   1265:                 rename($source,$destination);
                   1266:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1267:                                  $home);
1.481     raeburn  1268:             }
                   1269:         } elsif ($action eq 'uploaddoc') {
                   1270:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1271:             print $fh $env{'form.'.$source};
1.481     raeburn  1272:             close($fh);
1.637     raeburn  1273:             if ($parser eq 'parse') {
                   1274:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1275:                 unless ($parse_result eq 'ok') {
                   1276:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1277:                 }
                   1278:             }
1.477     raeburn  1279:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1280:                                  $home);
1.481     raeburn  1281:             if ($fetchresult eq 'ok') {
                   1282:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1283:             } else {
                   1284:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1285:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1286:                 return '/adm/notfound.html';
                   1287:             }
1.477     raeburn  1288:         }
                   1289:     }
1.485     raeburn  1290:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1291:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1292:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1293:     }
                   1294:     return $fetchresult;
                   1295: }
                   1296: 
1.637     raeburn  1297: sub build_filepath {
                   1298:     my ($fpath) = @_;
                   1299:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1300:     unless ($fpath eq '') {
                   1301:         my @parts=split('/',$fpath);
                   1302:         foreach my $part (@parts) {
                   1303:             $filepath.= '/'.$part;
                   1304:             if ((-e $filepath)!=1) {
                   1305:                 mkdir($filepath,0777);
                   1306:             }
                   1307:         }
                   1308:     }
                   1309:     return $filepath;
                   1310: }
                   1311: 
                   1312: sub store_edited_file {
1.638     albertel 1313:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1314:     my $file = $primary_url;
                   1315:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1316:     my $fpath = '';
                   1317:     my $fname = $file;
                   1318:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1319:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1320:     my $filepath = &build_filepath($fpath);
                   1321:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1322:     print $fh $content;
                   1323:     close($fh);
1.638     albertel 1324:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1325:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1326: 			  $home);
1.637     raeburn  1327:     if ($$fetchresult eq 'ok') {
                   1328:         return '/uploaded/'.$fpath.'/'.$fname;
                   1329:     } else {
1.638     albertel 1330:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1331: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1332:         return '/adm/notfound.html';
                   1333:     }
                   1334: }
                   1335: 
1.531     albertel 1336: sub clean_filename {
                   1337:     my ($fname)=@_;
1.315     www      1338: # Replace Windows backslashes by forward slashes
1.257     www      1339:     $fname=~s/\\/\//g;
1.315     www      1340: # Get rid of everything but the actual filename
1.257     www      1341:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1342: # Replace spaces by underscores
                   1343:     $fname=~s/\s+/\_/g;
                   1344: # Replace all other weird characters by nothing
1.317     www      1345:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1346: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1347: # numbers
                   1348:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1349:     return $fname;
                   1350: }
                   1351: 
1.608     albertel 1352: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1353: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1354: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1355: #        $coursedoc - if true up to the current course
                   1356: #                     if false
                   1357: #        $subdir - directory in userfile to store the file into
                   1358: #        $parser, $allfiles, $codebase - unknown
                   1359: #
                   1360: # output: url of file in userspace, or error: <message> 
                   1361: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1362: 
                   1363: 
1.531     albertel 1364: sub userfileupload {
1.719     banghart 1365:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1366:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1367:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1368:     $fname=&clean_filename($fname);
1.315     www      1369: # See if there is anything left
1.257     www      1370:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1371:     chop($env{'form.'.$formname});
1.523     raeburn  1372:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1373:         my $now = time;
                   1374:         my $filepath = 'tmp/helprequests/'.$now;
                   1375:         my @parts=split(/\//,$filepath);
                   1376:         my $fullpath = $perlvar{'lonDaemons'};
                   1377:         for (my $i=0;$i<@parts;$i++) {
                   1378:             $fullpath .= '/'.$parts[$i];
                   1379:             if ((-e $fullpath)!=1) {
                   1380:                 mkdir($fullpath,0777);
                   1381:             }
                   1382:         }
                   1383:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1384:         print $fh $env{'form.'.$formname};
1.523     raeburn  1385:         close($fh);
                   1386:         return $fullpath.'/'.$fname; 
                   1387:     }
1.719     banghart 1388:     
1.258     www      1389: # Create the directory if not present
1.493     albertel 1390:     $fname="$subdir/$fname";
1.259     www      1391:     if ($coursedoc) {
1.638     albertel 1392: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1393: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1394:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1395:             return &finishuserfileupload($docuname,$docudom,
                   1396: 					 $formname,$fname,$parser,$allfiles,
                   1397: 					 $codebase);
1.481     raeburn  1398:         } else {
1.620     albertel 1399:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1400:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1401: 				       $fname,$formname,$parser,
                   1402: 				       $allfiles,$codebase);
1.481     raeburn  1403:         }
1.719     banghart 1404:     } elsif (defined($destuname)) {
                   1405:         my $docuname=$destuname;
                   1406:         my $docudom=$destudom;
                   1407: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1408: 				     $fname,$parser,$allfiles,$codebase);
                   1409:         
1.259     www      1410:     } else {
1.638     albertel 1411:         my $docuname=$env{'user.name'};
                   1412:         my $docudom=$env{'user.domain'};
1.714     raeburn  1413:         if (exists($env{'form.group'})) {
                   1414:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1415:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1416:         }
1.638     albertel 1417: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1418: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1419:     }
1.271     www      1420: }
                   1421: 
                   1422: sub finishuserfileupload {
1.638     albertel 1423:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1424:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1425:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1426:     my ($fnamepath,$file);
                   1427:     $file=$fname;
                   1428:     if ($fname=~m|/|) {
                   1429:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1430: 	$path.=$fnamepath.'/';
                   1431:     }
1.259     www      1432:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1433:     my $count;
                   1434:     for ($count=4;$count<=$#parts;$count++) {
                   1435:         $filepath.="/$parts[$count]";
                   1436:         if ((-e $filepath)!=1) {
                   1437: 	    mkdir($filepath,0777);
                   1438:         }
                   1439:     }
                   1440: # Save the file
                   1441:     {
1.701     albertel 1442: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1443: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1444: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1445: 	    return '/adm/notfound.html';
                   1446: 	}
                   1447: 	if (!print FH ($env{'form.'.$formname})) {
                   1448: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1449: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1450: 	    return '/adm/notfound.html';
                   1451: 	}
1.570     albertel 1452: 	close(FH);
1.258     www      1453:     }
1.637     raeburn  1454:     if ($parser eq 'parse') {
1.638     albertel 1455:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1456: 						   $codebase);
1.637     raeburn  1457:         unless ($parse_result eq 'ok') {
1.638     albertel 1458:             &logthis('Failed to parse '.$filepath.$file.
                   1459: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1460:         }
                   1461:     }
1.259     www      1462: # Notify homeserver to grep it
                   1463: #
1.638     albertel 1464:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1465:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1466:     if ($fetchresult eq 'ok') {
1.259     www      1467: #
1.258     www      1468: # Return the URL to it
1.494     albertel 1469:         return '/uploaded/'.$path.$file;
1.263     www      1470:     } else {
1.494     albertel 1471:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1472: 		 ': '.$fetchresult);
1.263     www      1473:         return '/adm/notfound.html';
                   1474:     }    
1.493     albertel 1475: }
                   1476: 
1.637     raeburn  1477: sub extract_embedded_items {
1.648     raeburn  1478:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1479:     my @state = ();
                   1480:     my %javafiles = (
                   1481:                       codebase => '',
                   1482:                       code => '',
                   1483:                       archive => ''
                   1484:                     );
                   1485:     my %mediafiles = (
                   1486:                       src => '',
                   1487:                       movie => '',
                   1488:                      );
1.648     raeburn  1489:     my $p;
                   1490:     if ($content) {
                   1491:         $p = HTML::LCParser->new($content);
                   1492:     } else {
                   1493:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1494:     }
1.641     albertel 1495:     while (my $t=$p->get_token()) {
1.640     albertel 1496: 	if ($t->[0] eq 'S') {
                   1497: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1498: 	    push (@state, $tagname);
1.648     raeburn  1499:             if (lc($tagname) eq 'allow') {
                   1500:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1501:             }
1.640     albertel 1502: 	    if (lc($tagname) eq 'img') {
                   1503: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1504: 	    }
1.645     raeburn  1505:             if (lc($tagname) eq 'script') {
                   1506:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1507:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1508:                 } else {
                   1509:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1510:                 }
                   1511:             }
                   1512:             if (lc($tagname) eq 'link') {
                   1513:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1514:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1515:                 }
                   1516:             }
1.640     albertel 1517: 	    if (lc($tagname) eq 'object' ||
                   1518: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1519: 		foreach my $item (keys(%javafiles)) {
                   1520: 		    $javafiles{$item} = '';
                   1521: 		}
                   1522: 	    }
                   1523: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1524: 		my $name = lc($attr->{'name'});
                   1525: 		foreach my $item (keys(%javafiles)) {
                   1526: 		    if ($name eq $item) {
                   1527: 			$javafiles{$item} = $attr->{'value'};
                   1528: 			last;
                   1529: 		    }
                   1530: 		}
                   1531: 		foreach my $item (keys(%mediafiles)) {
                   1532: 		    if ($name eq $item) {
                   1533: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1534: 			last;
                   1535: 		    }
                   1536: 		}
                   1537: 	    }
                   1538: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1539: 		foreach my $item (keys(%javafiles)) {
                   1540: 		    if ($attr->{$item}) {
                   1541: 			$javafiles{$item} = $attr->{$item};
                   1542: 			last;
                   1543: 		    }
                   1544: 		}
                   1545: 		foreach my $item (keys(%mediafiles)) {
                   1546: 		    if ($attr->{$item}) {
                   1547: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1548: 			last;
                   1549: 		    }
                   1550: 		}
                   1551: 	    }
                   1552: 	} elsif ($t->[0] eq 'E') {
                   1553: 	    my ($tagname) = ($t->[1]);
                   1554: 	    if ($javafiles{'codebase'} ne '') {
                   1555: 		$javafiles{'codebase'} .= '/';
                   1556: 	    }  
                   1557: 	    if (lc($tagname) eq 'applet' ||
                   1558: 		lc($tagname) eq 'object' ||
                   1559: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1560: 		) {
                   1561: 		foreach my $item (keys(%javafiles)) {
                   1562: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1563: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1564: 			&add_filetype($allfiles,$file,$item);
                   1565: 		    }
                   1566: 		}
                   1567: 	    } 
                   1568: 	    pop @state;
                   1569: 	}
                   1570:     }
1.637     raeburn  1571:     return 'ok';
                   1572: }
                   1573: 
1.639     albertel 1574: sub add_filetype {
                   1575:     my ($allfiles,$file,$type)=@_;
                   1576:     if (exists($allfiles->{$file})) {
                   1577: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1578: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1579: 	}
                   1580:     } else {
                   1581: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1582:     }
                   1583: }
                   1584: 
1.493     albertel 1585: sub removeuploadedurl {
                   1586:     my ($url)=@_;
                   1587:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1588:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1589: }
                   1590: 
                   1591: sub removeuserfile {
                   1592:     my ($docuname,$docudom,$fname)=@_;
                   1593:     my $home=&homeserver($docuname,$docudom);
                   1594:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1595: }
1.15      www      1596: 
1.530     albertel 1597: sub mkdiruserfile {
                   1598:     my ($docuname,$docudom,$dir)=@_;
                   1599:     my $home=&homeserver($docuname,$docudom);
                   1600:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1601: }
                   1602: 
1.531     albertel 1603: sub renameuserfile {
                   1604:     my ($docuname,$docudom,$old,$new)=@_;
                   1605:     my $home=&homeserver($docuname,$docudom);
                   1606:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1607: 		  &escape("$new"),$home);
                   1608: }
                   1609: 
1.14      www      1610: # ------------------------------------------------------------------------- Log
                   1611: 
                   1612: sub log {
                   1613:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1614:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1615: }
                   1616: 
                   1617: # ------------------------------------------------------------------ Course Log
1.352     www      1618: #
                   1619: # This routine flushes several buffers of non-mission-critical nature
                   1620: #
1.157     www      1621: 
                   1622: sub flushcourselogs {
1.352     www      1623:     &logthis('Flushing log buffers');
                   1624: #
                   1625: # course logs
                   1626: # This is a log of all transactions in a course, which can be used
                   1627: # for data mining purposes
                   1628: #
                   1629: # It also collects the courseid database, which lists last transaction
                   1630: # times and course titles for all courseids
                   1631: #
                   1632:     my %courseidbuffer=();
1.191     harris41 1633:     foreach (keys %courselogs) {
1.157     www      1634:         my $crsid=$_;
1.352     www      1635:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1636: 		          &escape($courselogs{$crsid}),
                   1637: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1638: 	    delete $courselogs{$crsid};
                   1639:         } else {
                   1640:             &logthis('Failed to flush log buffer for '.$crsid);
                   1641:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1642:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1643:                         " exceeded maximum size, deleting.</font>");
                   1644:                delete $courselogs{$crsid};
                   1645:             }
1.352     www      1646:         }
                   1647:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1648:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1649: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1650:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352     www      1651:         } else {
                   1652:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1653: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1654:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
                   1655:         }
1.191     harris41 1656:     }
1.352     www      1657: #
                   1658: # Write course id database (reverse lookup) to homeserver of courses 
                   1659: # Is used in pickcourse
                   1660: #
                   1661:     foreach (keys %courseidbuffer) {
1.353     www      1662:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1663:     }
                   1664: #
                   1665: # File accesses
                   1666: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1667: #
1.449     matthew  1668:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1669:         if ($entry =~ /___count$/) {
                   1670:             my ($dom,$name);
                   1671:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1672:             if (! defined($dom) || $dom eq '' || 
                   1673:                 ! defined($name) || $name eq '') {
1.620     albertel 1674:                 my $cid = $env{'request.course.id'};
                   1675:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1676:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1677:             }
1.450     matthew  1678:             my $value = $accesshash{$entry};
                   1679:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1680:             my %temphash=($url => $value);
1.449     matthew  1681:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1682:             if ($result eq 'ok') {
                   1683:                 delete $accesshash{$entry};
                   1684:             } elsif ($result eq 'unknown_cmd') {
                   1685:                 # Target server has old code running on it.
1.450     matthew  1686:                 my %temphash=($entry => $value);
1.449     matthew  1687:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1688:                     delete $accesshash{$entry};
                   1689:                 }
                   1690:             }
                   1691:         } else {
1.458     matthew  1692:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1693:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1694:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1695:                 delete $accesshash{$entry};
                   1696:             }
1.185     www      1697:         }
1.191     harris41 1698:     }
1.352     www      1699: #
                   1700: # Roles
                   1701: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1702: #
1.349     www      1703:     foreach (keys %userrolehash) {
                   1704:         my $entry=$_;
1.351     www      1705:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1706: 	    split(/\:/,$entry);
                   1707:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1708:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1709:                 $rudom,$runame) eq 'ok') {
                   1710: 	    delete $userrolehash{$entry};
                   1711:         }
                   1712:     }
1.662     raeburn  1713: #
                   1714: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1715: #
                   1716:     my %domrolebuffer = ();
                   1717:     foreach my $entry (keys %domainrolehash) {
                   1718:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1719:         if ($domrolebuffer{$rudom}) {
                   1720:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1721:                       '='.&escape($domainrolehash{$entry});
                   1722:         } else {
                   1723:             $domrolebuffer{$rudom}.=&escape($entry).
                   1724:                       '='.&escape($domainrolehash{$entry});
                   1725:         }
                   1726:         delete $domainrolehash{$entry};
                   1727:     }
                   1728:     foreach my $dom (keys(%domrolebuffer)) {
                   1729:         foreach my $tryserver (keys %libserv) {
                   1730:             if ($hostdom{$tryserver} eq $dom) {
                   1731:                 unless (&reply('domroleput:'.$dom.':'.
                   1732:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1733:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1734:                 }
                   1735:             }
                   1736:         }
                   1737:     }
1.186     www      1738:     $dumpcount++;
1.157     www      1739: }
                   1740: 
                   1741: sub courselog {
                   1742:     my $what=shift;
1.158     www      1743:     $what=time.':'.$what;
1.620     albertel 1744:     unless ($env{'request.course.id'}) { return ''; }
                   1745:     $coursedombuf{$env{'request.course.id'}}=
                   1746:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1747:     $coursenumbuf{$env{'request.course.id'}}=
                   1748:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1749:     $coursehombuf{$env{'request.course.id'}}=
                   1750:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1751:     $coursedescrbuf{$env{'request.course.id'}}=
                   1752:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1753:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1754:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1755:     $courseownerbuf{$env{'request.course.id'}}=
                   1756:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   1757:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1758: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1759:     } else {
1.620     albertel 1760: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1761:     }
1.620     albertel 1762:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1763: 	&flushcourselogs();
                   1764:     }
1.158     www      1765: }
                   1766: 
                   1767: sub courseacclog {
                   1768:     my $fnsymb=shift;
1.620     albertel 1769:     unless ($env{'request.course.id'}) { return ''; }
                   1770:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1771:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1772:         $what.=':POST';
1.583     matthew  1773:         # FIXME: Probably ought to escape things....
1.620     albertel 1774: 	foreach (keys %env) {
1.158     www      1775:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1776: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1777:             }
1.191     harris41 1778:         }
1.583     matthew  1779:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1780:         # FIXME: We should not be depending on a form parameter that someone
                   1781:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1782:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1783:             $what.= ':POST';
                   1784:             # FIXME: Probably ought to escape things....
                   1785:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1786:                                  'crsdiscuss') {
1.620     albertel 1787:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1788:             }
                   1789:         }
1.158     www      1790:     }
                   1791:     &courselog($what);
1.149     www      1792: }
                   1793: 
1.185     www      1794: sub countacc {
                   1795:     my $url=&declutter(shift);
1.458     matthew  1796:     return if (! defined($url) || $url eq '');
1.620     albertel 1797:     unless ($env{'request.course.id'}) { return ''; }
                   1798:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1799:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1800:     $accesshash{$key}++;
1.185     www      1801: }
1.349     www      1802: 
1.361     www      1803: sub linklog {
                   1804:     my ($from,$to)=@_;
                   1805:     $from=&declutter($from);
                   1806:     $to=&declutter($to);
                   1807:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1808:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1809: }
                   1810:   
1.349     www      1811: sub userrolelog {
                   1812:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1813:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1814:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1815:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1816:         ($trole=~/^ta/)) {
1.350     www      1817:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1818:        $userrolehash
                   1819:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1820:                     =$tend.':'.$tstart;
1.662     raeburn  1821:     }
                   1822:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1823:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1824:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1825:         ($trole=~/^sc/)) {
                   1826:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1827:        $domainrolehash
                   1828:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1829:                     = $tend.':'.$tstart;
                   1830:     }
1.351     www      1831: }
                   1832: 
                   1833: sub get_course_adv_roles {
                   1834:     my $cid=shift;
1.620     albertel 1835:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1836:     my %coursehash=&coursedescription($cid);
1.470     www      1837:     my %nothide=();
                   1838:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1839: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1840:     }
1.351     www      1841:     my %returnhash=();
                   1842:     my %dumphash=
                   1843:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1844:     my $now=time;
                   1845:     foreach (keys %dumphash) {
                   1846: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1847:         if (($tstart) && ($tstart<0)) { next; }
                   1848:         if (($tend) && ($tend<$now)) { next; }
                   1849:         if (($tstart) && ($now<$tstart)) { next; }
                   1850:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1851: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1852: 	if ((&privileged($username,$domain)) && 
                   1853: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1854: 	if ($role eq 'cr') { next; }
1.351     www      1855:         my $key=&plaintext($role);
1.656     albertel 1856: 	if ($role =~ /^cr/) {
                   1857: 	    $key=(split('/',$role))[3];
                   1858: 	}
1.351     www      1859:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1860:         if ($returnhash{$key}) {
                   1861: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1862:         } else {
                   1863:             $returnhash{$key}=$username.':'.$domain;
                   1864:         }
1.400     www      1865:      }
                   1866:     return %returnhash;
                   1867: }
                   1868: 
                   1869: sub get_my_roles {
                   1870:     my ($uname,$udom)=@_;
1.620     albertel 1871:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1872:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1873:     my %dumphash=
                   1874:             &dump('nohist_userroles',$udom,$uname);
                   1875:     my %returnhash=();
                   1876:     my $now=time;
                   1877:     foreach (keys %dumphash) {
                   1878: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1879:         if (($tstart) && ($tstart<0)) { next; }
                   1880:         if (($tend) && ($tend<$now)) { next; }
                   1881:         if (($tstart) && ($now<$tstart)) { next; }
                   1882:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1883: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1884:      }
                   1885:     return %returnhash;
1.399     www      1886: }
                   1887: 
                   1888: # ----------------------------------------------------- Frontpage Announcements
                   1889: #
                   1890: #
                   1891: 
                   1892: sub postannounce {
                   1893:     my ($server,$text)=@_;
                   1894:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1895:     unless ($text=~/\w/) { $text=''; }
                   1896:     return &reply('setannounce:'.&escape($text),$server);
                   1897: }
                   1898: 
                   1899: sub getannounce {
1.448     albertel 1900: 
                   1901:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1902: 	my $announcement='';
                   1903: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1904: 	close($fh);
1.399     www      1905: 	if ($announcement=~/\w/) { 
                   1906: 	    return 
                   1907:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1908:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1909: 	} else {
                   1910: 	    return '';
                   1911: 	}
                   1912:     } else {
                   1913: 	return '';
                   1914:     }
1.351     www      1915: }
1.353     www      1916: 
                   1917: # ---------------------------------------------------------- Course ID routines
                   1918: # Deal with domain's nohist_courseid.db files
                   1919: #
                   1920: 
                   1921: sub courseidput {
                   1922:     my ($domain,$what,$coursehome)=@_;
                   1923:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1924: }
                   1925: 
                   1926: sub courseiddump {
1.622     raeburn  1927:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353     www      1928:     my %returnhash=();
1.355     www      1929:     unless ($domfilter) { $domfilter=''; }
1.353     www      1930:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1931:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1932: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1933: 	        foreach (
                   1934:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1935: 			       $sincefilter.':'.&escape($descfilter).':'.
1.622     raeburn  1936:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354     www      1937:                                $tryserver))) {
1.506     raeburn  1938: 		    my ($key,$value)=split(/\=/,$_);
                   1939:                     if (($key) && ($value)) {
1.516     raeburn  1940: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1941:                     }
1.353     www      1942:                 }
                   1943:             }
                   1944:         }
                   1945:     }
                   1946:     return %returnhash;
                   1947: }
                   1948: 
1.658     raeburn  1949: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1950: 
                   1951: sub dcmailput {
1.685     raeburn  1952:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1953:     my $status = &Apache::lonnet::critical(
                   1954:        'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='.
1.685     raeburn  1955:        &Apache::lonnet::escape($message),$server);
1.662     raeburn  1956:     return $status;
                   1957: }
                   1958: 
1.658     raeburn  1959: sub dcmaildump {
                   1960:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1961:     my %returnhash=();
                   1962:     if (exists($domain_primary{$dom})) {
                   1963:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1964:                                                          &escape($enddate).':';
                   1965: 	my @esc_senders=map { &escape($_)} @$senders;
                   1966: 	$cmd.=&escape(join('&',@esc_senders));
                   1967: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1968:             my ($key,$value) = split(/\=/,$_);
                   1969:             if (($key) && ($value)) {
                   1970:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  1971:             }
                   1972:         }
                   1973:     }
                   1974:     return %returnhash;
                   1975: }
1.662     raeburn  1976: # ---------------------------------------------------------- Domain roles
                   1977: 
                   1978: sub get_domain_roles {
                   1979:     my ($dom,$roles,$startdate,$enddate)=@_;
                   1980:     if (undef($startdate) || $startdate eq '') {
                   1981:         $startdate = '.';
                   1982:     }
                   1983:     if (undef($enddate) || $enddate eq '') {
                   1984:         $enddate = '.';
                   1985:     }
                   1986:     my $rolelist = join(':',@{$roles});
                   1987:     my %personnel = ();
                   1988:     foreach my $tryserver (keys(%libserv)) {
                   1989:         if ($hostdom{$tryserver} eq $dom) {
                   1990:             %{$personnel{$tryserver}}=();
                   1991:             foreach (
                   1992:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   1993:                    &escape($startdate).':'.&escape($enddate).':'.
                   1994:                    &escape($rolelist), $tryserver))) {
                   1995:                 my($key,$value) = split(/\=/,$_);
                   1996:                 if (($key) && ($value)) {
                   1997:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   1998:                 }
                   1999:             }
                   2000:         }
                   2001:     }
                   2002:     return %personnel;
                   2003: }
1.658     raeburn  2004: 
1.149     www      2005: # ----------------------------------------------------------- Check out an item
                   2006: 
1.504     albertel 2007: sub get_first_access {
                   2008:     my ($type,$argsymb)=@_;
                   2009:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2010:     if ($argsymb) { $symb=$argsymb; }
                   2011:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2012:     if ($type eq 'map') {
                   2013: 	$res=&symbread($map);
                   2014:     } else {
                   2015: 	$res=$symb;
                   2016:     }
                   2017:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2018:     return $times{"$courseid\0$res"};
1.504     albertel 2019: }
                   2020: 
                   2021: sub set_first_access {
                   2022:     my ($type)=@_;
                   2023:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2024:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2025:     if ($type eq 'map') {
                   2026: 	$res=&symbread($map);
                   2027:     } else {
                   2028: 	$res=$symb;
                   2029:     }
                   2030:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2031:     if (!$firstaccess) {
1.588     albertel 2032: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2033:     }
                   2034:     return 'already_set';
1.504     albertel 2035: }
                   2036: 
1.149     www      2037: sub checkout {
                   2038:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2039:     my $now=time;
                   2040:     my $lonhost=$perlvar{'lonHostID'};
                   2041:     my $infostr=&escape(
1.234     www      2042:                  'CHECKOUTTOKEN&'.
1.149     www      2043:                  $tuname.'&'.
                   2044:                  $tudom.'&'.
                   2045:                  $tcrsid.'&'.
                   2046:                  $symb.'&'.
                   2047: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2048:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2049:     if ($token=~/^error\:/) { 
1.672     albertel 2050:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2051:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2052:                  "</font>");
                   2053:         return ''; 
                   2054:     }
                   2055: 
1.149     www      2056:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2057:     $token=~tr/a-z/A-Z/;
                   2058: 
1.153     www      2059:     my %infohash=('resource.0.outtoken' => $token,
                   2060:                   'resource.0.checkouttime' => $now,
                   2061:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2062: 
                   2063:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2064:        return '';
1.151     www      2065:     } else {
1.672     albertel 2066:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2067:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2068:                  "</font>");
1.149     www      2069:     }    
                   2070: 
                   2071:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2072:                          &escape('Checkout '.$infostr.' - '.
                   2073:                                                  $token)) ne 'ok') {
                   2074: 	return '';
1.151     www      2075:     } else {
1.672     albertel 2076:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2077:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2078:                  "</font>");
1.149     www      2079:     }
1.151     www      2080:     return $token;
1.149     www      2081: }
                   2082: 
                   2083: # ------------------------------------------------------------ Check in an item
                   2084: 
                   2085: sub checkin {
                   2086:     my $token=shift;
1.150     www      2087:     my $now=time;
                   2088:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2089:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2090:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2091:     $dtoken=~s/\W/\_/g;
1.234     www      2092:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2093:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2094: 
1.154     www      2095:     unless (($tuname) && ($tudom)) {
                   2096:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2097:         return '';
                   2098:     }
                   2099:     
                   2100:     unless (&allowed('mgr',$tcrsid)) {
                   2101:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2102:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2103:         return '';
                   2104:     }
                   2105: 
1.153     www      2106:     my %infohash=('resource.0.intoken' => $token,
                   2107:                   'resource.0.checkintime' => $now,
                   2108:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2109: 
                   2110:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2111:        return '';
                   2112:     }    
                   2113: 
                   2114:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2115:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2116: 	return '';
                   2117:     }
                   2118: 
                   2119:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2120: }
                   2121: 
                   2122: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2123: 
                   2124: sub expirespread {
                   2125:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2126:     my $cid=$env{'request.course.id'}; 
1.110     www      2127:     if ($cid) {
                   2128:        my $now=time;
                   2129:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2130:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2131:                             $env{'course.'.$cid.'.num'}.
1.110     www      2132: 	        	    ':nohist_expirationdates:'.
                   2133:                             &escape($key).'='.$now,
1.620     albertel 2134:                             $env{'course.'.$cid.'.home'})
1.110     www      2135:     }
                   2136:     return 'ok';
1.14      www      2137: }
                   2138: 
1.109     www      2139: # ----------------------------------------------------- Devalidate Spreadsheets
                   2140: 
                   2141: sub devalidate {
1.325     www      2142:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2143:     my $cid=$env{'request.course.id'}; 
1.109     www      2144:     if ($cid) {
1.391     matthew  2145:         # delete the stored spreadsheets for
                   2146:         # - the student level sheet of this user in course's homespace
                   2147:         # - the assessment level sheet for this resource 
                   2148:         #   for this user in user's homespace
1.553     albertel 2149: 	# - current conditional state info
1.325     www      2150: 	my $key=$uname.':'.$udom.':';
1.109     www      2151:         my $status=
1.299     matthew  2152: 	    &del('nohist_calculatedsheets',
1.391     matthew  2153: 		 [$key.'studentcalc:'],
1.620     albertel 2154: 		 $env{'course.'.$cid.'.domain'},
                   2155: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2156: 		.' '.
                   2157: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2158: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2159:         unless ($status eq 'ok ok') {
                   2160:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2161:                     $uname.' at '.$udom.' for '.
1.109     www      2162: 		    $symb.': '.$status);
1.133     albertel 2163:         }
1.553     albertel 2164: 	&delenv('user.state.'.$cid);
1.109     www      2165:     }
                   2166: }
                   2167: 
1.265     albertel 2168: sub get_scalar {
                   2169:     my ($string,$end) = @_;
                   2170:     my $value;
                   2171:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2172: 	$value = $1;
                   2173:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2174: 	$value = $1;
                   2175:     }
                   2176:     return &unescape($value);
                   2177: }
                   2178: 
                   2179: sub array2str {
                   2180:   my (@array) = @_;
                   2181:   my $result=&arrayref2str(\@array);
                   2182:   $result=~s/^__ARRAY_REF__//;
                   2183:   $result=~s/__END_ARRAY_REF__$//;
                   2184:   return $result;
                   2185: }
                   2186: 
1.204     albertel 2187: sub arrayref2str {
                   2188:   my ($arrayref) = @_;
1.265     albertel 2189:   my $result='__ARRAY_REF__';
1.204     albertel 2190:   foreach my $elem (@$arrayref) {
1.265     albertel 2191:     if(ref($elem) eq 'ARRAY') {
                   2192:       $result.=&arrayref2str($elem).'&';
                   2193:     } elsif(ref($elem) eq 'HASH') {
                   2194:       $result.=&hashref2str($elem).'&';
                   2195:     } elsif(ref($elem)) {
                   2196:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2197:     } else {
                   2198:       $result.=&escape($elem).'&';
                   2199:     }
                   2200:   }
                   2201:   $result=~s/\&$//;
1.265     albertel 2202:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2203:   return $result;
                   2204: }
                   2205: 
1.168     albertel 2206: sub hash2str {
1.204     albertel 2207:   my (%hash) = @_;
                   2208:   my $result=&hashref2str(\%hash);
1.265     albertel 2209:   $result=~s/^__HASH_REF__//;
                   2210:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2211:   return $result;
                   2212: }
                   2213: 
                   2214: sub hashref2str {
                   2215:   my ($hashref)=@_;
1.265     albertel 2216:   my $result='__HASH_REF__';
1.495     albertel 2217:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2218:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2219:       $result.=&arrayref2str($_).'=';
1.204     albertel 2220:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2221:       $result.=&hashref2str($_).'=';
1.204     albertel 2222:     } elsif (ref($_)) {
1.265     albertel 2223:       $result.='=';
                   2224:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2225:     } else {
1.265     albertel 2226: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2227:     }
                   2228: 
1.265     albertel 2229:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2230:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2231:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2232:       $result.=&hashref2str($hashref->{$_}).'&';
                   2233:     } elsif(ref($hashref->{$_})) {
                   2234:        $result.='&';
                   2235:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2236:     } else {
1.265     albertel 2237:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2238:     }
                   2239:   }
1.168     albertel 2240:   $result=~s/\&$//;
1.265     albertel 2241:   $result .= '__END_HASH_REF__';
1.168     albertel 2242:   return $result;
                   2243: }
                   2244: 
                   2245: sub str2hash {
1.265     albertel 2246:     my ($string)=@_;
                   2247:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2248:     return %$hash;
                   2249: }
                   2250: 
                   2251: sub str2hashref {
1.168     albertel 2252:   my ($string) = @_;
1.265     albertel 2253: 
                   2254:   my %hash;
                   2255: 
                   2256:   if($string !~ /^__HASH_REF__/) {
                   2257:       if (! ($string eq '' || !defined($string))) {
                   2258: 	  $hash{'error'}='Not hash reference';
                   2259:       }
                   2260:       return (\%hash, $string);
                   2261:   }
                   2262: 
                   2263:   $string =~ s/^__HASH_REF__//;
                   2264: 
                   2265:   while($string !~ /^__END_HASH_REF__/) {
                   2266:       #key
                   2267:       my $key='';
                   2268:       if($string =~ /^__HASH_REF__/) {
                   2269:           ($key, $string)=&str2hashref($string);
                   2270:           if(defined($key->{'error'})) {
                   2271:               $hash{'error'}='Bad data';
                   2272:               return (\%hash, $string);
                   2273:           }
                   2274:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2275:           ($key, $string)=&str2arrayref($string);
                   2276:           if($key->[0] eq 'Array reference error') {
                   2277:               $hash{'error'}='Bad data';
                   2278:               return (\%hash, $string);
                   2279:           }
                   2280:       } else {
                   2281:           $string =~ s/^(.*?)=//;
1.267     albertel 2282: 	  $key=&unescape($1);
1.265     albertel 2283:       }
                   2284:       $string =~ s/^=//;
                   2285: 
                   2286:       #value
                   2287:       my $value='';
                   2288:       if($string =~ /^__HASH_REF__/) {
                   2289:           ($value, $string)=&str2hashref($string);
                   2290:           if(defined($value->{'error'})) {
                   2291:               $hash{'error'}='Bad data';
                   2292:               return (\%hash, $string);
                   2293:           }
                   2294:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2295:           ($value, $string)=&str2arrayref($string);
                   2296:           if($value->[0] eq 'Array reference error') {
                   2297:               $hash{'error'}='Bad data';
                   2298:               return (\%hash, $string);
                   2299:           }
                   2300:       } else {
                   2301: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2302:       }
                   2303:       $string =~ s/^&//;
                   2304: 
                   2305:       $hash{$key}=$value;
1.204     albertel 2306:   }
1.265     albertel 2307: 
                   2308:   $string =~ s/^__END_HASH_REF__//;
                   2309: 
                   2310:   return (\%hash, $string);
1.204     albertel 2311: }
                   2312: 
                   2313: sub str2array {
1.265     albertel 2314:     my ($string)=@_;
                   2315:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2316:     return @$array;
                   2317: }
                   2318: 
                   2319: sub str2arrayref {
1.204     albertel 2320:   my ($string) = @_;
1.265     albertel 2321:   my @array;
                   2322: 
                   2323:   if($string !~ /^__ARRAY_REF__/) {
                   2324:       if (! ($string eq '' || !defined($string))) {
                   2325: 	  $array[0]='Array reference error';
                   2326:       }
                   2327:       return (\@array, $string);
                   2328:   }
                   2329: 
                   2330:   $string =~ s/^__ARRAY_REF__//;
                   2331: 
                   2332:   while($string !~ /^__END_ARRAY_REF__/) {
                   2333:       my $value='';
                   2334:       if($string =~ /^__HASH_REF__/) {
                   2335:           ($value, $string)=&str2hashref($string);
                   2336:           if(defined($value->{'error'})) {
                   2337:               $array[0] ='Array reference error';
                   2338:               return (\@array, $string);
                   2339:           }
                   2340:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2341:           ($value, $string)=&str2arrayref($string);
                   2342:           if($value->[0] eq 'Array reference error') {
                   2343:               $array[0] ='Array reference error';
                   2344:               return (\@array, $string);
                   2345:           }
                   2346:       } else {
                   2347: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2348:       }
                   2349:       $string =~ s/^&//;
                   2350: 
                   2351:       push(@array, $value);
1.191     harris41 2352:   }
1.265     albertel 2353: 
                   2354:   $string =~ s/^__END_ARRAY_REF__//;
                   2355: 
                   2356:   return (\@array, $string);
1.168     albertel 2357: }
                   2358: 
1.167     albertel 2359: # -------------------------------------------------------------------Temp Store
                   2360: 
1.168     albertel 2361: sub tmpreset {
                   2362:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2363:   if (!$symb) {
                   2364:     $symb=&symbread();
1.620     albertel 2365:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2366:   }
                   2367:   $symb=escape($symb);
                   2368: 
1.620     albertel 2369:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2370:   $namespace=~s/\//\_/g;
                   2371:   $namespace=~s/\W//g;
                   2372: 
1.620     albertel 2373:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2374:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2375:   if ($domain eq 'public' && $stuname eq 'public') {
                   2376:       $stuname=$ENV{'REMOTE_ADDR'};
                   2377:   }
1.168     albertel 2378:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2379:   my %hash;
                   2380:   if (tie(%hash,'GDBM_File',
                   2381: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2382: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2383:     foreach my $key (keys %hash) {
1.180     albertel 2384:       if ($key=~ /:$symb/) {
1.168     albertel 2385: 	delete($hash{$key});
                   2386:       }
                   2387:     }
                   2388:   }
                   2389: }
                   2390: 
1.167     albertel 2391: sub tmpstore {
1.168     albertel 2392:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2393: 
                   2394:   if (!$symb) {
                   2395:     $symb=&symbread();
1.620     albertel 2396:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2397:   }
                   2398:   $symb=escape($symb);
                   2399: 
                   2400:   if (!$namespace) {
                   2401:     # I don't think we would ever want to store this for a course.
                   2402:     # it seems this will only be used if we don't have a course.
1.620     albertel 2403:     #$namespace=$env{'request.course.id'};
1.168     albertel 2404:     #if (!$namespace) {
1.620     albertel 2405:       $namespace=$env{'request.state'};
1.168     albertel 2406:     #}
                   2407:   }
                   2408:   $namespace=~s/\//\_/g;
                   2409:   $namespace=~s/\W//g;
1.620     albertel 2410:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2411:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2412:   if ($domain eq 'public' && $stuname eq 'public') {
                   2413:       $stuname=$ENV{'REMOTE_ADDR'};
                   2414:   }
1.168     albertel 2415:   my $now=time;
                   2416:   my %hash;
                   2417:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2418:   if (tie(%hash,'GDBM_File',
                   2419: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2420: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2421:     $hash{"version:$symb"}++;
                   2422:     my $version=$hash{"version:$symb"};
                   2423:     my $allkeys=''; 
                   2424:     foreach my $key (keys(%$storehash)) {
                   2425:       $allkeys.=$key.':';
1.591     albertel 2426:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2427:     }
                   2428:     $hash{"$version:$symb:timestamp"}=$now;
                   2429:     $allkeys.='timestamp';
                   2430:     $hash{"$version:keys:$symb"}=$allkeys;
                   2431:     if (untie(%hash)) {
                   2432:       return 'ok';
                   2433:     } else {
                   2434:       return "error:$!";
                   2435:     }
                   2436:   } else {
                   2437:     return "error:$!";
                   2438:   }
                   2439: }
1.167     albertel 2440: 
1.168     albertel 2441: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2442: 
1.168     albertel 2443: sub tmprestore {
                   2444:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2445: 
1.168     albertel 2446:   if (!$symb) {
                   2447:     $symb=&symbread();
1.620     albertel 2448:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2449:   }
                   2450:   $symb=escape($symb);
                   2451: 
1.620     albertel 2452:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2453: 
1.620     albertel 2454:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2455:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2456:   if ($domain eq 'public' && $stuname eq 'public') {
                   2457:       $stuname=$ENV{'REMOTE_ADDR'};
                   2458:   }
1.168     albertel 2459:   my %returnhash;
                   2460:   $namespace=~s/\//\_/g;
                   2461:   $namespace=~s/\W//g;
                   2462:   my %hash;
                   2463:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2464:   if (tie(%hash,'GDBM_File',
                   2465: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2466: 	  &GDBM_READER(),0640)) {
1.168     albertel 2467:     my $version=$hash{"version:$symb"};
                   2468:     $returnhash{'version'}=$version;
                   2469:     my $scope;
                   2470:     for ($scope=1;$scope<=$version;$scope++) {
                   2471:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2472:       my @keys=split(/:/,$vkeys);
                   2473:       my $key;
                   2474:       $returnhash{"$scope:keys"}=$vkeys;
                   2475:       foreach $key (@keys) {
1.591     albertel 2476: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2477: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2478:       }
                   2479:     }
1.168     albertel 2480:     if (!(untie(%hash))) {
                   2481:       return "error:$!";
                   2482:     }
                   2483:   } else {
                   2484:     return "error:$!";
                   2485:   }
                   2486:   return %returnhash;
1.167     albertel 2487: }
                   2488: 
1.9       www      2489: # ----------------------------------------------------------------------- Store
                   2490: 
                   2491: sub store {
1.124     www      2492:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2493:     my $home='';
                   2494: 
1.168     albertel 2495:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2496: 
1.213     www      2497:     $symb=&symbclean($symb);
1.122     albertel 2498:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2499: 
1.620     albertel 2500:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2501:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2502: 
                   2503:     &devalidate($symb,$stuname,$domain);
1.109     www      2504: 
                   2505:     $symb=escape($symb);
1.187     www      2506:     if (!$namespace) { 
1.620     albertel 2507:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2508:           return ''; 
                   2509:        } 
                   2510:     }
1.620     albertel 2511:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2512: 
                   2513:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2514:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2515: 
1.12      www      2516:     my $namevalue='';
1.191     harris41 2517:     foreach (keys %$storehash) {
1.591     albertel 2518:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2519:     }
1.12      www      2520:     $namevalue=~s/\&$//;
1.187     www      2521:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2522:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2523: }
                   2524: 
1.47      www      2525: # -------------------------------------------------------------- Critical Store
                   2526: 
                   2527: sub cstore {
1.124     www      2528:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2529:     my $home='';
                   2530: 
1.168     albertel 2531:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2532: 
1.213     www      2533:     $symb=&symbclean($symb);
1.122     albertel 2534:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2535: 
1.620     albertel 2536:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2537:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2538: 
                   2539:     &devalidate($symb,$stuname,$domain);
1.109     www      2540: 
                   2541:     $symb=escape($symb);
1.187     www      2542:     if (!$namespace) { 
1.620     albertel 2543:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2544:           return ''; 
                   2545:        } 
                   2546:     }
1.620     albertel 2547:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2548: 
                   2549:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2550:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2551: 
1.47      www      2552:     my $namevalue='';
1.191     harris41 2553:     foreach (keys %$storehash) {
1.591     albertel 2554:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2555:     }
1.47      www      2556:     $namevalue=~s/\&$//;
1.187     www      2557:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2558:     return critical
                   2559:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2560: }
                   2561: 
1.9       www      2562: # --------------------------------------------------------------------- Restore
                   2563: 
                   2564: sub restore {
1.124     www      2565:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2566:     my $home='';
                   2567: 
1.168     albertel 2568:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2569: 
1.122     albertel 2570:     if (!$symb) {
                   2571:       unless ($symb=escape(&symbread())) { return ''; }
                   2572:     } else {
1.213     www      2573:       $symb=&escape(&symbclean($symb));
1.122     albertel 2574:     }
1.188     www      2575:     if (!$namespace) { 
1.620     albertel 2576:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2577:           return ''; 
                   2578:        } 
                   2579:     }
1.620     albertel 2580:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2581:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2582:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2583:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2584: 
1.12      www      2585:     my %returnhash=();
1.191     harris41 2586:     foreach (split(/\&/,$answer)) {
1.12      www      2587: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2588:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2589:     }
1.75      www      2590:     my $version;
                   2591:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2592:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2593:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2594:        }
1.75      www      2595:     }
1.13      www      2596:     return %returnhash;
1.34      www      2597: }
                   2598: 
                   2599: # ---------------------------------------------------------- Course Description
                   2600: 
                   2601: sub coursedescription {
                   2602:     my $courseid=shift;
                   2603:     $courseid=~s/^\///;
1.49      www      2604:     $courseid=~s/\_/\//g;
1.34      www      2605:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2606:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2607:     my $normalid=$cdomain.'_'.$cnum;
                   2608:     # need to always cache even if we get errors otherwise we keep 
                   2609:     # trying and trying and trying to get the course description.
                   2610:     my %envhash=();
                   2611:     my %returnhash=();
                   2612:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      2613:     if ($chome ne 'no_host') {
1.302     albertel 2614:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2615:        if (!exists($returnhash{'con_lost'})) {
                   2616:            $returnhash{'home'}= $chome;
                   2617: 	   $returnhash{'domain'} = $cdomain;
                   2618: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2619:            while (my ($name,$value) = each %returnhash) {
1.53      www      2620:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2621:            }
1.270     www      2622:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2623:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2624: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2625:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2626:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2627:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2628:        }
                   2629:     }
1.302     albertel 2630:     &appenv(%envhash);
                   2631:     return %returnhash;
1.461     www      2632: }
                   2633: 
                   2634: # -------------------------------------------------See if a user is privileged
                   2635: 
                   2636: sub privileged {
                   2637:     my ($username,$domain)=@_;
                   2638:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2639: 			&homeserver($username,$domain));
                   2640:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2641:     my $now=time;
                   2642:     if ($rolesdump ne '') {
                   2643:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2644: 	    if ($_!~/^rolesdef_/) {
1.461     www      2645: 		my ($area,$role)=split(/=/,$_);
                   2646: 		$area=~s/\_\w\w$//;
                   2647: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2648: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2649: 		    my $active=1;
                   2650: 		    if ($tend) {
                   2651: 			if ($tend<$now) { $active=0; }
                   2652: 		    }
                   2653: 		    if ($tstart) {
                   2654: 			if ($tstart>$now) { $active=0; }
                   2655: 		    }
                   2656: 		    if ($active) { return 1; }
                   2657: 		}
                   2658: 	    }
                   2659: 	}
                   2660:     }
                   2661:     return 0;
1.9       www      2662: }
1.1       albertel 2663: 
1.103     harris41 2664: # -------------------------------------------------------- Get user privileges
1.11      www      2665: 
                   2666: sub rolesinit {
                   2667:     my ($domain,$username,$authhost)=@_;
                   2668:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2669:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2670:     my %allroles=();
1.678     raeburn  2671:     my %allgroups=();   
1.11      www      2672:     my $now=time;
1.21      www      2673:     my $userroles="user.login.time=$now\n";
1.678     raeburn  2674:     my $group_privs;
1.11      www      2675: 
                   2676:     if ($rolesdump ne '') {
1.191     harris41 2677:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2678: 	  if ($_!~/^rolesdef_/) {
1.11      www      2679:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2680: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2681:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2682: 	    if ($role=~/^cr/) { 
1.655     albertel 2683: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2684: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2685: 		    ($tend,$tstart)=split('_',$trest);
                   2686: 		} else {
                   2687: 		    $trole=$role;
                   2688: 		}
1.678     raeburn  2689:             } elsif ($role =~ m|^gr/|) {
                   2690:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2691:                 ($trole,$group_privs) = split(/\//,$trole);
                   2692:                 $group_privs = &unescape($group_privs);
1.587     albertel 2693: 	    } else {
                   2694: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2695: 	    }
1.576     albertel 2696:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567     raeburn  2697:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2698:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2699:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2700: 		my $spec=$trole.'.'.$area;
                   2701: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2702: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2703:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2704:                 } elsif ($trole eq 'gr') {
                   2705:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2706: 		} else {
1.567     raeburn  2707:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2708: 		}
1.12      www      2709:             }
1.662     raeburn  2710:           }
1.191     harris41 2711:         }
1.678     raeburn  2712:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
1.128     www      2713:         $userroles.='user.adv='.$adv."\n".
                   2714: 	            'user.author='.$author."\n";
1.620     albertel 2715:         $env{'user.adv'}=$adv;
1.11      www      2716:     }
                   2717:     return $userroles;  
                   2718: }
                   2719: 
1.567     raeburn  2720: sub set_arearole {
                   2721:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2722: # log the associated role with the area
                   2723:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   2724:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
                   2725: }
                   2726: 
                   2727: sub custom_roleprivs {
                   2728:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2729:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2730:     my $homsvr=homeserver($rauthor,$rdomain);
                   2731:     if ($hostname{$homsvr} ne '') {
                   2732:         my ($rdummy,$roledef)=
                   2733:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2734:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2735:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2736:             if (defined($syspriv)) {
                   2737:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2738:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2739:             }
                   2740:             if ($tdomain ne '') {
                   2741:                 if (defined($dompriv)) {
                   2742:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2743:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2744:                 }
                   2745:                 if (($trest ne '') && (defined($coursepriv))) {
                   2746:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2747:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2748:                 }
                   2749:             }
                   2750:         }
                   2751:     }
                   2752: }
                   2753: 
1.678     raeburn  2754: sub group_roleprivs {
                   2755:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2756:     my $access = 1;
                   2757:     my $now = time;
                   2758:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2759:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2760:     if ($access) {
                   2761:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2762:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2763:     }
                   2764: }
1.567     raeburn  2765: 
                   2766: sub standard_roleprivs {
                   2767:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2768:     if (defined($pr{$trole.':s'})) {
                   2769:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2770:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2771:     }
                   2772:     if ($tdomain ne '') {
                   2773:         if (defined($pr{$trole.':d'})) {
                   2774:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2775:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2776:         }
                   2777:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2778:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2779:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2780:         }
                   2781:     }
                   2782: }
                   2783: 
                   2784: sub set_userprivs {
1.678     raeburn  2785:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2786:     my $author=0;
                   2787:     my $adv=0;
1.678     raeburn  2788:     my %grouproles = ();
                   2789:     if (keys(%{$allgroups}) > 0) {
                   2790:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2791:             my ($trole,$area,$sec,$extendedarea);
                   2792:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2793:                 $trole = $1;
                   2794:                 $area = $2;
1.681     raeburn  2795:                 $sec = $3;
                   2796:                 $extendedarea = $area.$sec;
                   2797:                 if (exists($$allgroups{$area})) {
                   2798:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2799:                         my $spec = $trole.'.'.$extendedarea;
                   2800:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2801:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2802:                     }
                   2803:                 }
                   2804:             }
                   2805:         }
                   2806:     }
                   2807:     foreach (keys(%grouproles)) {
                   2808:         $$allroles{$_} = $grouproles{$_};
                   2809:     }
1.567     raeburn  2810:     foreach (keys %{$allroles}) {
                   2811:         my %thesepriv=();
                   2812:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2813:         foreach (split(/:/,$$allroles{$_})) {
                   2814:             if ($_ ne '') {
                   2815:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2816:                 if ($restrictions eq '') {
                   2817:                     $thesepriv{$privilege}='F';
                   2818:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2819:                     $thesepriv{$privilege}.=$restrictions;
                   2820:                 }
                   2821:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2822:             }
                   2823:         }
                   2824:         my $thesestr='';
                   2825:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
                   2826:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
                   2827:     }
                   2828:     return ($author,$adv);
                   2829: }
                   2830: 
1.12      www      2831: # --------------------------------------------------------------- get interface
                   2832: 
                   2833: sub get {
1.131     albertel 2834:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2835:    my $items='';
1.191     harris41 2836:    foreach (@$storearr) {
1.12      www      2837:        $items.=escape($_).'&';
1.191     harris41 2838:    }
1.12      www      2839:    $items=~s/\&$//;
1.620     albertel 2840:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2841:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2842:    my $uhome=&homeserver($uname,$udomain);
                   2843: 
1.133     albertel 2844:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2845:    my @pairs=split(/\&/,$rep);
1.273     albertel 2846:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2847:      return @pairs;
                   2848:    }
1.15      www      2849:    my %returnhash=();
1.42      www      2850:    my $i=0;
1.191     harris41 2851:    foreach (@$storearr) {
1.557     albertel 2852:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2853:       $i++;
1.191     harris41 2854:    }
1.15      www      2855:    return %returnhash;
1.27      www      2856: }
                   2857: 
                   2858: # --------------------------------------------------------------- del interface
                   2859: 
                   2860: sub del {
1.133     albertel 2861:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2862:    my $items='';
1.191     harris41 2863:    foreach (@$storearr) {
1.27      www      2864:        $items.=escape($_).'&';
1.191     harris41 2865:    }
1.27      www      2866:    $items=~s/\&$//;
1.620     albertel 2867:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2868:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2869:    my $uhome=&homeserver($uname,$udomain);
                   2870: 
                   2871:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2872: }
                   2873: 
                   2874: # -------------------------------------------------------------- dump interface
                   2875: 
                   2876: sub dump {
1.702     albertel 2877:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.620     albertel 2878:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2879:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2880:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2881:    if ($regexp) {
                   2882:        $regexp=&escape($regexp);
                   2883:    } else {
                   2884:        $regexp='.';
                   2885:    }
1.702     albertel 2886:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.12      www      2887:    my @pairs=split(/\&/,$rep);
                   2888:    my %returnhash=();
1.191     harris41 2889:    foreach (@pairs) {
1.702     albertel 2890:       my ($key,$value)=split(/=/,$_,2);
1.557     albertel 2891:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2892:    }
                   2893:    return %returnhash;
1.407     www      2894: }
                   2895: 
1.717     albertel 2896: # --------------------------------------------------------- dumpstore interface
                   2897: 
                   2898: sub dumpstore {
                   2899:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2900:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2901: }
                   2902: 
1.407     www      2903: # -------------------------------------------------------------- keys interface
                   2904: 
                   2905: sub getkeys {
                   2906:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2907:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2908:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2909:    my $uhome=&homeserver($uname,$udomain);
                   2910:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2911:    my @keyarray=();
                   2912:    foreach (split(/\&/,$rep)) {
                   2913:       push (@keyarray,&unescape($_));
                   2914:    }
                   2915:    return @keyarray;
1.318     matthew  2916: }
                   2917: 
1.319     matthew  2918: # --------------------------------------------------------------- currentdump
                   2919: sub currentdump {
1.328     matthew  2920:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2921:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2922:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2923:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2924:    my $uhome = &homeserver($sname,$sdom);
                   2925:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2926:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2927:    #
1.318     matthew  2928:    my %returnhash=();
1.319     matthew  2929:    #
                   2930:    if ($rep eq "unknown_cmd") { 
                   2931:        # an old lond will not know currentdump
                   2932:        # Do a dump and make it look like a currentdump
1.326     matthew  2933:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2934:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2935:        my %hash = @tmp;
                   2936:        @tmp=();
1.424     matthew  2937:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2938:    } else {
                   2939:        my @pairs=split(/\&/,$rep);
                   2940:        foreach (@pairs) {
                   2941:            my ($key,$value)=split(/=/,$_);
                   2942:            my ($symb,$param) = split(/:/,$key);
                   2943:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2944:                                                         &thaw_unescape($value);
1.319     matthew  2945:        }
1.191     harris41 2946:    }
1.12      www      2947:    return %returnhash;
1.424     matthew  2948: }
                   2949: 
                   2950: sub convert_dump_to_currentdump{
                   2951:     my %hash = %{shift()};
                   2952:     my %returnhash;
                   2953:     # Code ripped from lond, essentially.  The only difference
                   2954:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2955:     # we might run in to problems with parameter names =~ /^v\./
                   2956:     while (my ($key,$value) = each(%hash)) {
                   2957:         my ($v,$symb,$param) = split(/:/,$key);
                   2958:         next if ($v eq 'version' || $symb eq 'keys');
                   2959:         next if (exists($returnhash{$symb}) &&
                   2960:                  exists($returnhash{$symb}->{$param}) &&
                   2961:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2962:         $returnhash{$symb}->{$param}=$value;
                   2963:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2964:     }
                   2965:     #
                   2966:     # Remove all of the keys in the hashes which keep track of
                   2967:     # the version of the parameter.
                   2968:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2969:         # use a foreach because we are going to delete from the hash.
                   2970:         foreach my $key (keys(%$param_hash)) {
                   2971:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2972:         }
                   2973:     }
                   2974:     return \%returnhash;
1.12      www      2975: }
                   2976: 
1.627     albertel 2977: # ------------------------------------------------------ critical inc interface
                   2978: 
                   2979: sub cinc {
                   2980:     return &inc(@_,'critical');
                   2981: }
                   2982: 
1.449     matthew  2983: # --------------------------------------------------------------- inc interface
                   2984: 
                   2985: sub inc {
1.627     albertel 2986:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 2987:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2988:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  2989:     my $uhome=&homeserver($uname,$udomain);
                   2990:     my $items='';
                   2991:     if (! ref($store)) {
                   2992:         # got a single value, so use that instead
                   2993:         $items = &escape($store).'=&';
                   2994:     } elsif (ref($store) eq 'SCALAR') {
                   2995:         $items = &escape($$store).'=&';        
                   2996:     } elsif (ref($store) eq 'ARRAY') {
                   2997:         $items = join('=&',map {&escape($_);} @{$store});
                   2998:     } elsif (ref($store) eq 'HASH') {
                   2999:         while (my($key,$value) = each(%{$store})) {
                   3000:             $items.= &escape($key).'='.&escape($value).'&';
                   3001:         }
                   3002:     }
                   3003:     $items=~s/\&$//;
1.627     albertel 3004:     if ($critical) {
                   3005: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3006:     } else {
                   3007: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3008:     }
1.449     matthew  3009: }
                   3010: 
1.12      www      3011: # --------------------------------------------------------------- put interface
                   3012: 
                   3013: sub put {
1.134     albertel 3014:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3015:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3016:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3017:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3018:    my $items='';
1.191     harris41 3019:    foreach (keys %$storehash) {
1.557     albertel 3020:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3021:    }
1.12      www      3022:    $items=~s/\&$//;
1.134     albertel 3023:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3024: }
                   3025: 
1.631     albertel 3026: # ------------------------------------------------------------ newput interface
                   3027: 
                   3028: sub newput {
                   3029:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3030:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3031:    if (!$uname) { $uname=$env{'user.name'}; }
                   3032:    my $uhome=&homeserver($uname,$udomain);
                   3033:    my $items='';
                   3034:    foreach my $key (keys(%$storehash)) {
                   3035:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3036:    }
                   3037:    $items=~s/\&$//;
                   3038:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3039: }
                   3040: 
                   3041: # ---------------------------------------------------------  putstore interface
                   3042: 
1.524     raeburn  3043: sub putstore {
1.715     albertel 3044:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3045:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3046:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3047:    my $uhome=&homeserver($uname,$udomain);
                   3048:    my $items='';
1.715     albertel 3049:    foreach my $key (keys(%$storehash)) {
                   3050:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3051:    }
1.715     albertel 3052:    $items=~s/\&$//;
1.716     albertel 3053:    my $esc_symb=&escape($symb);
                   3054:    my $esc_v=&escape($version);
1.715     albertel 3055:    my $reply =
1.716     albertel 3056:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3057: 	      $uhome);
                   3058:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3059:        # gfall back to way things use to be done
1.715     albertel 3060:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3061: 			    $uname);
1.524     raeburn  3062:    }
1.715     albertel 3063:    return $reply;
                   3064: }
                   3065: 
                   3066: sub old_putstore {
1.716     albertel 3067:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3068:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3069:     if (!$uname) { $uname=$env{'user.name'}; }
                   3070:     my $uhome=&homeserver($uname,$udomain);
                   3071:     my %newstorehash;
                   3072:     foreach (keys %$storehash) {
                   3073: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3074: 	$newstorehash{$key} = $storehash->{$_};
                   3075:     }
                   3076:     my $items='';
                   3077:     my %allitems = ();
                   3078:     foreach (keys %newstorehash) {
                   3079: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3080: 	    my $key = $1.':keys:'.$2;
                   3081: 	    $allitems{$key} .= $3.':';
                   3082: 	}
                   3083: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3084:     }
                   3085:     foreach (keys %allitems) {
                   3086: 	$allitems{$_} =~ s/\:$//;
                   3087: 	$items.= $_.'='.$allitems{$_}.'&';
                   3088:     }
                   3089:     $items=~s/\&$//;
                   3090:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3091: }
                   3092: 
1.47      www      3093: # ------------------------------------------------------ critical put interface
                   3094: 
                   3095: sub cput {
1.134     albertel 3096:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3097:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3098:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3099:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3100:    my $items='';
1.191     harris41 3101:    foreach (keys %$storehash) {
1.715     albertel 3102:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3103:    }
1.47      www      3104:    $items=~s/\&$//;
1.134     albertel 3105:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3106: }
                   3107: 
                   3108: # -------------------------------------------------------------- eget interface
                   3109: 
                   3110: sub eget {
1.133     albertel 3111:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3112:    my $items='';
1.191     harris41 3113:    foreach (@$storearr) {
1.12      www      3114:        $items.=escape($_).'&';
1.191     harris41 3115:    }
1.12      www      3116:    $items=~s/\&$//;
1.620     albertel 3117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3118:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3119:    my $uhome=&homeserver($uname,$udomain);
                   3120:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3121:    my @pairs=split(/\&/,$rep);
                   3122:    my %returnhash=();
1.42      www      3123:    my $i=0;
1.191     harris41 3124:    foreach (@$storearr) {
1.557     albertel 3125:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3126:       $i++;
1.191     harris41 3127:    }
1.12      www      3128:    return %returnhash;
                   3129: }
                   3130: 
1.667     albertel 3131: # ------------------------------------------------------------ tmpput interface
                   3132: sub tmpput {
                   3133:     my ($storehash,$server)=@_;
                   3134:     my $items='';
                   3135:     foreach (keys(%$storehash)) {
                   3136: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3137:     }
                   3138:     $items=~s/\&$//;
                   3139:     return &reply("tmpput:$items",$server);
                   3140: }
                   3141: 
                   3142: # ------------------------------------------------------------ tmpget interface
                   3143: sub tmpget {
1.688     albertel 3144:     my ($token,$server)=@_;
                   3145:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3146:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3147:     my %returnhash;
                   3148:     foreach my $item (split(/\&/,$rep)) {
                   3149: 	my ($key,$value)=split(/=/,$item);
                   3150: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3151:     }
                   3152:     return %returnhash;
                   3153: }
                   3154: 
1.688     albertel 3155: # ------------------------------------------------------------ tmpget interface
                   3156: sub tmpdel {
                   3157:     my ($token,$server)=@_;
                   3158:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3159:     return &reply("tmpdel:$token",$server);
                   3160: }
                   3161: 
1.341     www      3162: # ---------------------------------------------- Custom access rule evaluation
                   3163: 
                   3164: sub customaccess {
                   3165:     my ($priv,$uri)=@_;
1.620     albertel 3166:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3167:     $urealm=~s/^\W//;
                   3168:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3169:     my $access=0;
                   3170:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3171: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3172:         if ($role) {
                   3173: 	   if ($role ne $urole) { next; }
                   3174:         }
                   3175:         foreach (split(/\s*\,\s*/,$realm)) {
                   3176:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3177:             if ($tdom) {
                   3178: 		if ($tdom ne $udom) { next; }
                   3179:             }
                   3180:             if ($tcrs) {
                   3181: 		if ($tcrs ne $ucrs) { next; }
                   3182:             }
                   3183:             if ($tsec) {
                   3184: 		if ($tsec ne $usec) { next; }
                   3185:             }
                   3186:             $access=($effect eq 'allow');
                   3187:             last;
1.342     www      3188:         }
1.402     bowersj2 3189: 	if ($realm eq '' && $role eq '') {
                   3190:             $access=($effect eq 'allow');
                   3191: 	}
1.341     www      3192:     }
                   3193:     return $access;
                   3194: }
                   3195: 
1.103     harris41 3196: # ------------------------------------------------- Check for a user privilege
1.12      www      3197: 
                   3198: sub allowed {
1.579     albertel 3199:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3200:     my $ver_orguri=$uri;
1.439     www      3201:     $uri=&deversion($uri);
1.152     www      3202:     my $orguri=$uri;
1.52      www      3203:     $uri=&declutter($uri);
1.545     banghart 3204:     
1.620     albertel 3205:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3206: # Free bre access to adm and meta resources
1.529     albertel 3207:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3208: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3209: 	return 'F';
1.159     www      3210:     }
                   3211: 
1.545     banghart 3212: # Free bre access to user's own portfolio contents
1.714     raeburn  3213:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3214:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3215: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3216:         return 'F';
                   3217:     }
                   3218: 
1.714     raeburn  3219: # bre access to group if user has rgf priv for this group and course.
                   3220:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3221:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3222:         if (exists($env{'request.course.id'})) {
                   3223:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3224:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3225:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3226:                 my $courseprivid=$env{'request.course.id'};
                   3227:                 $courseprivid=~s/\_/\//;
                   3228:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3229:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3230:                     return $1; 
                   3231:                 }
                   3232:             }
                   3233:         }
                   3234:     }
                   3235: 
1.159     www      3236: # Free bre to public access
                   3237: 
                   3238:     if ($priv eq 'bre') {
1.238     www      3239:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3240: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3241:            return 'F'; 
                   3242:         }
1.238     www      3243:         if ($copyright eq 'priv') {
                   3244:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3245: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3246: 		return '';
                   3247:             }
                   3248:         }
                   3249:         if ($copyright eq 'domain') {
                   3250:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3251: 	    unless (($env{'user.domain'} eq $1) ||
                   3252:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3253: 		return '';
                   3254:             }
1.262     matthew  3255:         }
1.620     albertel 3256:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3257:             # Library role, so allow browsing of resources in this domain.
                   3258:             return 'F';
1.238     www      3259:         }
1.341     www      3260:         if ($copyright eq 'custom') {
                   3261: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3262:         }
1.14      www      3263:     }
1.264     matthew  3264:     # Domain coordinator is trying to create a course
1.620     albertel 3265:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3266:         # uri is the requested domain in this case.
                   3267:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3268:         # a role of dc for the domain in question.
1.620     albertel 3269:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3270:     }
1.29      www      3271: 
1.52      www      3272:     my $thisallowed='';
                   3273:     my $statecond=0;
                   3274:     my $courseprivid='';
                   3275: 
                   3276: # Course
                   3277: 
1.620     albertel 3278:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3279:        $thisallowed.=$1;
                   3280:     }
1.29      www      3281: 
1.52      www      3282: # Domain
                   3283: 
1.620     albertel 3284:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3285:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3286:        $thisallowed.=$1;
                   3287:     }
1.52      www      3288: 
                   3289: # Course: uri itself is a course
1.66      www      3290:     my $courseuri=$uri;
                   3291:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3292:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3293: 
1.620     albertel 3294:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3295:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3296:        $thisallowed.=$1;
                   3297:     }
1.29      www      3298: 
1.678     raeburn  3299: # Group: uri itself is a group
                   3300:     my $groupuri=$uri;
                   3301:     $groupuri=~s/^([^\/])/\/$1/;
                   3302:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3303:        =~/\Q$priv\E\&([^\:]*)/) {
                   3304:        $thisallowed.=$1;
                   3305:     }
                   3306: 
1.665     albertel 3307: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3308: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3309:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3310: 	$thisallowed='';
1.671     raeburn  3311:         my ($match)=&is_on_map($uri);
                   3312:         if ($match) {
                   3313:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3314:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3315:                 $thisallowed.=$1;
                   3316:             }
                   3317:         } else {
1.705     albertel 3318:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3319:             if ($refuri) {
                   3320:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3321:                     $thisallowed='F';
1.671     raeburn  3322:                 } else {
                   3323:                     $refuri=&declutter($refuri);
                   3324:                     my ($match) = &is_on_map($refuri);
                   3325:                     if ($match) {
                   3326:                         $thisallowed='F';
                   3327:                     }
1.669     raeburn  3328:                 }
1.671     raeburn  3329:             }
                   3330:         }
1.314     www      3331:     }
1.492     albertel 3332: 
1.52      www      3333: # Full access at system, domain or course-wide level? Exit.
1.29      www      3334: 
                   3335:     if ($thisallowed=~/F/) {
                   3336: 	return 'F';
                   3337:     }
                   3338: 
1.52      www      3339: # If this is generating or modifying users, exit with special codes
1.29      www      3340: 
1.643     www      3341:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3342: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3343: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3344: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3345: 	    unless ($auname) { return $thisallowed; }
                   3346: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3347: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3348: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3349: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3350: 	}
1.52      www      3351: 	return $thisallowed;
                   3352:     }
                   3353: #
1.103     harris41 3354: # Gathered so far: system, domain and course wide privileges
1.52      www      3355: #
                   3356: # Course: See if uri or referer is an individual resource that is part of 
                   3357: # the course
                   3358: 
1.620     albertel 3359:     if ($env{'request.course.id'}) {
1.232     www      3360: 
1.620     albertel 3361:        $courseprivid=$env{'request.course.id'};
                   3362:        if ($env{'request.course.sec'}) {
                   3363:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3364:        }
                   3365:        $courseprivid=~s/\_/\//;
                   3366:        my $checkreferer=1;
1.232     www      3367:        my ($match,$cond)=&is_on_map($uri);
                   3368:        if ($match) {
                   3369:            $statecond=$cond;
1.620     albertel 3370:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3371:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3372:                $thisallowed.=$1;
                   3373:                $checkreferer=0;
                   3374:            }
1.29      www      3375:        }
1.83      www      3376:        
1.148     www      3377:        if ($checkreferer) {
1.620     albertel 3378: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3379:             unless ($refuri) {
1.620     albertel 3380:                 foreach (keys %env) {
1.148     www      3381: 		    if ($_=~/^httpref\..*\*/) {
                   3382: 			my $pattern=$_;
1.156     www      3383:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3384:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3385:                         $pattern=~s/\//\\\//g;
1.152     www      3386:                         if ($orguri=~/$pattern/) {
1.620     albertel 3387: 			    $refuri=$env{$_};
1.148     www      3388:                         }
                   3389:                     }
1.191     harris41 3390:                 }
1.148     www      3391:             }
1.232     www      3392: 
1.148     www      3393:          if ($refuri) { 
1.152     www      3394: 	  $refuri=&declutter($refuri);
1.232     www      3395:           my ($match,$cond)=&is_on_map($refuri);
                   3396:             if ($match) {
                   3397:               my $refstatecond=$cond;
1.620     albertel 3398:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3399:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3400:                   $thisallowed.=$1;
1.53      www      3401:                   $uri=$refuri;
                   3402:                   $statecond=$refstatecond;
1.52      www      3403:               }
                   3404:           }
1.148     www      3405:         }
1.29      www      3406:        }
1.52      www      3407:    }
1.29      www      3408: 
1.52      www      3409: #
1.103     harris41 3410: # Gathered now: all privileges that could apply, and condition number
1.52      www      3411: # 
                   3412: #
                   3413: # Full or no access?
                   3414: #
1.29      www      3415: 
1.52      www      3416:     if ($thisallowed=~/F/) {
                   3417: 	return 'F';
                   3418:     }
1.29      www      3419: 
1.52      www      3420:     unless ($thisallowed) {
                   3421:         return '';
                   3422:     }
1.29      www      3423: 
1.52      www      3424: # Restrictions exist, deal with them
                   3425: #
                   3426: #   C:according to course preferences
                   3427: #   R:according to resource settings
                   3428: #   L:unless locked
                   3429: #   X:according to user session state
                   3430: #
                   3431: 
                   3432: # Possibly locked functionality, check all courses
1.54      www      3433: # Locks might take effect only after 10 minutes cache expiration for other
                   3434: # courses, and 2 minutes for current course
1.52      www      3435: 
                   3436:     my $envkey;
                   3437:     if ($thisallowed=~/L/) {
1.620     albertel 3438:         foreach $envkey (keys %env) {
1.54      www      3439:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3440:                my $courseid=$2;
                   3441:                my $roleid=$1.'.'.$2;
1.92      www      3442:                $courseid=~s/^\///;
1.54      www      3443:                my $expiretime=600;
1.620     albertel 3444:                if ($env{'request.role'} eq $roleid) {
1.54      www      3445: 		  $expiretime=120;
                   3446:                }
                   3447: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3448:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3449:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.54      www      3450: 		   &coursedescription($courseid);
                   3451:                }
1.620     albertel 3452:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3453:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3454: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3455:                        &log($env{'user.domain'},$env{'user.name'},
                   3456:                             $env{'user.home'},
1.57      www      3457:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3458:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3459:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3460: 		       return '';
                   3461:                    }
                   3462:                }
1.620     albertel 3463:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3464:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3465: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3466:                        &log($env{'user.domain'},$env{'user.name'},
                   3467:                             $env{'user.home'},
1.57      www      3468:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3469:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3470:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3471: 		       return '';
                   3472:                    }
                   3473:                }
                   3474: 	   }
1.29      www      3475:        }
1.52      www      3476:     }
                   3477:    
                   3478: #
                   3479: # Rest of the restrictions depend on selected course
                   3480: #
                   3481: 
1.620     albertel 3482:     unless ($env{'request.course.id'}) {
1.52      www      3483:        return '1';
                   3484:     }
1.29      www      3485: 
1.52      www      3486: #
                   3487: # Now user is definitely in a course
                   3488: #
1.53      www      3489: 
                   3490: 
                   3491: # Course preferences
                   3492: 
                   3493:    if ($thisallowed=~/C/) {
1.620     albertel 3494:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3495:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3496:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3497: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3498: 	   if ($priv ne 'pch') { 
                   3499: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3500: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3501: 			$env{'request.course.id'});
                   3502: 	   }
1.237     www      3503:            return '';
                   3504:        }
                   3505: 
1.620     albertel 3506:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3507: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3508: 	   if ($priv ne 'pch') { 
                   3509: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3510: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3511: 			$env{'request.course.id'});
                   3512: 	   }
1.54      www      3513:            return '';
                   3514:        }
1.53      www      3515:    }
                   3516: 
                   3517: # Resource preferences
                   3518: 
                   3519:    if ($thisallowed=~/R/) {
1.620     albertel 3520:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3521:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3522: 	   if ($priv ne 'pch') { 
                   3523: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3524: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3525: 	   }
                   3526: 	   return '';
1.54      www      3527:        }
1.53      www      3528:    }
1.30      www      3529: 
1.246     www      3530: # Restricted by state or randomout?
1.30      www      3531: 
1.52      www      3532:    if ($thisallowed=~/X/) {
1.620     albertel 3533:       if ($env{'acc.randomout'}) {
1.579     albertel 3534: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3535:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3536:             return ''; 
                   3537:          }
1.247     www      3538:       }
                   3539:       if (&condval($statecond)) {
1.52      www      3540: 	 return '2';
                   3541:       } else {
                   3542:          return '';
                   3543:       }
                   3544:    }
1.30      www      3545: 
1.52      www      3546:    return 'F';
1.232     www      3547: }
                   3548: 
1.710     albertel 3549: sub split_uri_for_cond {
                   3550:     my $uri=&deversion(&declutter(shift));
                   3551:     my @uriparts=split(/\//,$uri);
                   3552:     my $filename=pop(@uriparts);
                   3553:     my $pathname=join('/',@uriparts);
                   3554:     return ($pathname,$filename);
                   3555: }
1.232     www      3556: # --------------------------------------------------- Is a resource on the map?
                   3557: 
                   3558: sub is_on_map {
1.710     albertel 3559:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3560:     #Trying to find the conditional for the file
1.620     albertel 3561:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3562: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3563:     if ($match) {
1.289     bowersj2 3564: 	return (1,$1);
                   3565:     } else {
1.434     www      3566: 	return (0,0);
1.289     bowersj2 3567:     }
1.12      www      3568: }
                   3569: 
1.427     www      3570: # --------------------------------------------------------- Get symb from alias
                   3571: 
                   3572: sub get_symb_from_alias {
                   3573:     my $symb=shift;
                   3574:     my ($map,$resid,$url)=&decode_symb($symb);
                   3575: # Already is a symb
                   3576:     if ($url) { return $symb; }
                   3577: # Must be an alias
                   3578:     my $aliassymb='';
                   3579:     my %bighash;
1.620     albertel 3580:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3581:                             &GDBM_READER(),0640)) {
                   3582:         my $rid=$bighash{'mapalias_'.$symb};
                   3583: 	if ($rid) {
                   3584: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3585: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3586: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3587: 	}
                   3588:         untie %bighash;
                   3589:     }
                   3590:     return $aliassymb;
                   3591: }
                   3592: 
1.12      www      3593: # ----------------------------------------------------------------- Define Role
                   3594: 
                   3595: sub definerole {
                   3596:   if (allowed('mcr','/')) {
                   3597:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3598:     foreach (split(':',$sysrole)) {
1.21      www      3599: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3600:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3601:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3602: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3603:                return "refused:s:$crole&$cqual"; 
                   3604:             }
                   3605:         }
1.191     harris41 3606:     }
1.392     www      3607:     foreach (split(':',$domrole)) {
1.21      www      3608: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3609:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3610:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3611: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3612:                return "refused:d:$crole&$cqual"; 
                   3613:             }
                   3614:         }
1.191     harris41 3615:     }
1.392     www      3616:     foreach (split(':',$courole)) {
1.21      www      3617: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3618:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3619:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3620: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3621:                return "refused:c:$crole&$cqual"; 
                   3622:             }
                   3623:         }
1.191     harris41 3624:     }
1.620     albertel 3625:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3626:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3627: 	        "rolesdef_$rolename=".
                   3628:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3629:     return reply($command,$env{'user.home'});
1.12      www      3630:   } else {
                   3631:     return 'refused';
                   3632:   }
1.105     harris41 3633: }
                   3634: 
                   3635: # ---------------- Make a metadata query against the network of library servers
                   3636: 
                   3637: sub metadata_query {
1.244     matthew  3638:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3639:     my %rhash;
1.244     matthew  3640:     my @server_list = (defined($server_array) ? @$server_array
                   3641:                                               : keys(%libserv) );
                   3642:     for my $server (@server_list) {
1.118     harris41 3643: 	unless ($custom or $customshow) {
                   3644: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3645: 	    $rhash{$server}=$reply;
                   3646: 	}
                   3647: 	else {
                   3648: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3649: 			     &escape($custom).':'.&escape($customshow),
                   3650: 			     $server);
                   3651: 	    $rhash{$server}=$reply;
                   3652: 	}
1.112     harris41 3653:     }
1.118     harris41 3654:     return \%rhash;
1.240     www      3655: }
                   3656: 
                   3657: # ----------------------------------------- Send log queries and wait for reply
                   3658: 
                   3659: sub log_query {
                   3660:     my ($uname,$udom,$query,%filters)=@_;
                   3661:     my $uhome=&homeserver($uname,$udom);
                   3662:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3663:     my $uhost=$hostname{$uhome};
1.241     www      3664:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3665:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3666:                        $uhome);
1.479     albertel 3667:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3668:     return get_query_reply($queryid);
                   3669: }
                   3670: 
1.508     raeburn  3671: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3672: 
                   3673: sub fetch_enrollment_query {
1.511     raeburn  3674:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3675:     my $homeserver;
1.547     raeburn  3676:     my $maxtries = 1;
1.508     raeburn  3677:     if ($context eq 'automated') {
                   3678:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3679:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3680:     } else {
                   3681:         $homeserver = &homeserver($cnum,$dom);
                   3682:     }
1.506     raeburn  3683:     my $host=$hostname{$homeserver};
                   3684:     my $cmd = '';
                   3685:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3686:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3687:     }
                   3688:     $cmd =~ s/%%$//;
                   3689:     $cmd = &escape($cmd);
                   3690:     my $query = 'fetchenrollment';
1.620     albertel 3691:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3692:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3693:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3694:         return 'error: '.$queryid;
                   3695:     }
1.506     raeburn  3696:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3697:     my $tries = 1;
                   3698:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3699:         $reply = &get_query_reply($queryid);
                   3700:         $tries ++;
                   3701:     }
1.526     raeburn  3702:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3703:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3704:     } else {
1.515     raeburn  3705:         my @responses = split/:/,$reply;
                   3706:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3707:             foreach (@responses) {
                   3708:                 my ($key,$value) = split/=/,$_;
                   3709:                 $$replyref{$key} = $value;
                   3710:             }
                   3711:         } else {
1.506     raeburn  3712:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3713:             foreach (@responses) {
                   3714:                 my ($key,$value) = split/=/,$_;
                   3715:                 $$replyref{$key} = $value;
                   3716:                 if ($value > 0) {
                   3717:                     foreach (@{$$affiliatesref{$key}}) {
                   3718:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3719:                         my $destname = $pathname.'/'.$filename;
                   3720:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3721:                         if ($xml_classlist =~ /^error/) {
                   3722:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3723:                         } else {
1.506     raeburn  3724:                             if ( open(FILE,">$destname") ) {
                   3725:                                 print FILE &unescape($xml_classlist);
                   3726:                                 close(FILE);
1.526     raeburn  3727:                             } else {
                   3728:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3729:                             }
                   3730:                         }
                   3731:                     }
                   3732:                 }
                   3733:             }
                   3734:         }
                   3735:         return 'ok';
                   3736:     }
                   3737:     return 'error';
                   3738: }
                   3739: 
1.242     www      3740: sub get_query_reply {
                   3741:     my $queryid=shift;
1.240     www      3742:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3743:     my $reply='';
                   3744:     for (1..100) {
                   3745: 	sleep 2;
                   3746:         if (-e $replyfile.'.end') {
1.448     albertel 3747: 	    if (open(my $fh,$replyfile)) {
1.240     www      3748:                $reply.=<$fh>;
1.448     albertel 3749:                close($fh);
1.240     www      3750: 	   } else { return 'error: reply_file_error'; }
1.242     www      3751:            return &unescape($reply);
                   3752: 	}
1.240     www      3753:     }
1.242     www      3754:     return 'timeout:'.$queryid;
1.240     www      3755: }
                   3756: 
                   3757: sub courselog_query {
1.241     www      3758: #
                   3759: # possible filters:
                   3760: # url: url or symb
                   3761: # username
                   3762: # domain
                   3763: # action: view, submit, grade
                   3764: # start: timestamp
                   3765: # end: timestamp
                   3766: #
1.240     www      3767:     my (%filters)=@_;
1.620     albertel 3768:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3769:     if ($filters{'url'}) {
                   3770: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3771:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3772:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3773:     }
1.620     albertel 3774:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3775:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3776:     return &log_query($cname,$cdom,'courselog',%filters);
                   3777: }
                   3778: 
                   3779: sub userlog_query {
                   3780:     my ($uname,$udom,%filters)=@_;
                   3781:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3782: }
                   3783: 
1.506     raeburn  3784: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3785: 
                   3786: sub auto_run {
1.508     raeburn  3787:     my ($cnum,$cdom) = @_;
                   3788:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3789:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3790:     return $response;
                   3791: }
                   3792:                                                                                    
                   3793: sub auto_get_sections {
1.508     raeburn  3794:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3795:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3796:     my @secs = ();
1.511     raeburn  3797:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3798:     unless ($response eq 'refused') {
                   3799:         @secs = split/:/,$response;
                   3800:     }
                   3801:     return @secs;
                   3802: }
                   3803:                                                                                    
                   3804: sub auto_new_course {
1.508     raeburn  3805:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3806:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3807:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3808:     return $response;
                   3809: }
                   3810:                                                                                    
                   3811: sub auto_validate_courseID {
1.508     raeburn  3812:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3813:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3814:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3815:     return $response;
                   3816: }
                   3817:                                                                                    
                   3818: sub auto_create_password {
1.508     raeburn  3819:     my ($cnum,$cdom,$authparam) = @_;
                   3820:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3821:     my $create_passwd = 0;
                   3822:     my $authchk = '';
1.511     raeburn  3823:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3824:     if ($response eq 'refused') {
                   3825:         $authchk = 'refused';
                   3826:     } else {
                   3827:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3828:     }
                   3829:     return ($authparam,$create_passwd,$authchk);
                   3830: }
                   3831: 
1.706     raeburn  3832: sub auto_photo_permission {
                   3833:     my ($cnum,$cdom,$students) = @_;
                   3834:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 3835:     my ($outcome,$perm_reqd,$conditions) = 
                   3836: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 3837:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3838: 	return (undef,undef);
                   3839:     }
1.706     raeburn  3840:     return ($outcome,$perm_reqd,$conditions);
                   3841: }
                   3842: 
                   3843: sub auto_checkphotos {
                   3844:     my ($uname,$udom,$pid) = @_;
                   3845:     my $homeserver = &homeserver($uname,$udom);
                   3846:     my ($result,$resulttype);
                   3847:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 3848: 				   &escape($uname).':'.&escape($pid),
                   3849: 				   $homeserver));
1.709     albertel 3850:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3851: 	return (undef,undef);
                   3852:     }
1.706     raeburn  3853:     if ($outcome) {
                   3854:         ($result,$resulttype) = split(/:/,$outcome);
                   3855:     } 
                   3856:     return ($result,$resulttype);
                   3857: }
                   3858: 
                   3859: sub auto_photochoice {
                   3860:     my ($cnum,$cdom) = @_;
                   3861:     my $homeserver = &homeserver($cnum,$cdom);
                   3862:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 3863: 						       &escape($cdom),
                   3864: 						       $homeserver)));
1.709     albertel 3865:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3866: 	return (undef,undef);
                   3867:     }
1.706     raeburn  3868:     return ($update,$comment);
                   3869: }
                   3870: 
                   3871: sub auto_photoupdate {
                   3872:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   3873:     my $homeserver = &homeserver($cnum,$dom);
                   3874:     my $host=$hostname{$homeserver};
                   3875:     my $cmd = '';
                   3876:     my $maxtries = 1;
                   3877:     foreach (keys %{$affiliatesref}) {
                   3878:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   3879:     }
                   3880:     $cmd =~ s/%%$//;
                   3881:     $cmd = &escape($cmd);
                   3882:     my $query = 'institutionalphotos';
                   3883:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   3884:     unless ($queryid=~/^\Q$host\E\_/) {
                   3885:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   3886:         return 'error: '.$queryid;
                   3887:     }
                   3888:     my $reply = &get_query_reply($queryid);
                   3889:     my $tries = 1;
                   3890:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3891:         $reply = &get_query_reply($queryid);
                   3892:         $tries ++;
                   3893:     }
                   3894:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   3895:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   3896:     } else {
                   3897:         my @responses = split(/:/,$reply);
                   3898:         my $outcome = shift(@responses); 
                   3899:         foreach my $item (@responses) {
                   3900:             my ($key,$value) = split(/=/,$item);
                   3901:             $$photo{$key} = $value;
                   3902:         }
                   3903:         return $outcome;
                   3904:     }
                   3905:     return 'error';
                   3906: }
                   3907: 
1.521     raeburn  3908: sub auto_instcode_format {
                   3909:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3910:     my $courses = '';
                   3911:     my $homeserver;
                   3912:     if ($caller eq 'global') {
1.584     raeburn  3913:         foreach my $tryserver (keys %libserv) {
                   3914:             if ($hostdom{$tryserver} eq $codedom) {
                   3915:                 $homeserver = $tryserver;
                   3916:                 last;
                   3917:             }
                   3918:         }
1.620     albertel 3919:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3920:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3921:         }
1.521     raeburn  3922:     } else {
                   3923:         $homeserver = &homeserver($caller,$codedom);
                   3924:     }
                   3925:     foreach (keys %{$instcodes}) {
                   3926:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3927:     }
                   3928:     chop($courses);
                   3929:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3930:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3931:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3932:         %{$codes} = &str2hash($codes_str);
                   3933:         @{$codetitles} = &str2array($codetitles_str);
                   3934:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3935:         %{$cat_order} = &str2hash($cat_order_str);
                   3936:         return 'ok';
                   3937:     }
                   3938:     return $response;
                   3939: }
                   3940: 
1.679     raeburn  3941: # ------------------------------------------------------- Course Group routines
                   3942: 
                   3943: sub get_coursegroups {
1.683     raeburn  3944:     my ($cdom,$cnum,$group) = @_;
                   3945:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  3946: }
                   3947: 
                   3948: sub modify_coursegroup {
                   3949:     my ($cdom,$cnum,$groupsettings) = @_;
                   3950:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   3951: }
                   3952: 
                   3953: sub modify_group_roles {
                   3954:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   3955:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   3956:     my $role = 'gr/'.&escape($userprivs);
                   3957:     my ($uname,$udom) = split(/:/,$user);
                   3958:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  3959:     if ($result eq 'ok') {
                   3960:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   3961:     }
                   3962: 
1.679     raeburn  3963:     return $result;
                   3964: }
                   3965: 
                   3966: sub modify_coursegroup_membership {
                   3967:     my ($cdom,$cnum,$membership) = @_;
                   3968:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   3969:     return $result;
                   3970: }
                   3971: 
1.682     raeburn  3972: sub get_active_groups {
                   3973:     my ($udom,$uname,$cdom,$cnum) = @_;
                   3974:     my $now = time;
                   3975:     my %groups = ();
                   3976:     foreach my $key (keys(%env)) {
                   3977:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   3978:             my ($start,$end) = split(/\./,$env{$key});
                   3979:             if (($end!=0) && ($end<$now)) { next; }
                   3980:             if (($start!=0) && ($start>$now)) { next; }
                   3981:             if ($1 eq $cdom && $2 eq $cnum) {
                   3982:                 $groups{$3} = $env{$key} ;
                   3983:             }
                   3984:         }
                   3985:     }
                   3986:     return %groups;
                   3987: }
                   3988: 
1.683     raeburn  3989: sub get_group_membership {
                   3990:     my ($cdom,$cnum,$group) = @_;
                   3991:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   3992: }
                   3993: 
                   3994: sub get_users_groups {
                   3995:     my ($udom,$uname,$courseid) = @_;
                   3996:     my $cachetime=1800;
                   3997:     $courseid=~s/\_/\//g;
                   3998:     $courseid=~s/^(\w)/\/$1/;
                   3999: 
                   4000:     my $hashid="$udom:$uname:$courseid";
                   4001:     my ($result,$cached)=&is_cached_new('getgroups',$hashid);
                   4002:     if (defined($cached)) { return $result; }
                   4003: 
                   4004:     my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4005:     my ($tmp) = keys(%roleshash);
                   4006:     if ($tmp=~/^error:/) {
                   4007:         &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4008:         return '';
                   4009:     } else {
                   4010:         my $grouplist;
                   4011:         foreach my $key (keys %roleshash) {
                   4012:             if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
1.727     raeburn  4013:                 unless ($roleshash{$key} =~ /_\d+_\-1$/) {   # deleted membership
1.683     raeburn  4014:                     $grouplist .= $1.':';
                   4015:                 }
                   4016:             }
                   4017:         }
                   4018:         $grouplist =~ s/:$//;
                   4019:         return &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
                   4020:     }
                   4021: }
                   4022: 
                   4023: sub devalidate_getgroups_cache {
                   4024:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4025:     my $courseid = $cdom.'_'.$cnum;
                   4026:     $courseid=~s/\_/\//g;
                   4027:     $courseid=~s/^(\w)/\/$1/;
                   4028:     my $hashid="$udom:$uname:$courseid";
                   4029:     &devalidate_cache_new('getgroups',$hashid);
                   4030: }
                   4031: 
1.12      www      4032: # ------------------------------------------------------------------ Plain Text
                   4033: 
                   4034: sub plaintext {
1.22      www      4035:     my $short=shift;
1.676     albertel 4036:     return &Apache::lonlocal::mt($prp{$short});
1.12      www      4037: }
                   4038: 
                   4039: # ----------------------------------------------------------------- Assign Role
                   4040: 
                   4041: sub assignrole {
1.357     www      4042:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4043:     my $mrole;
                   4044:     if ($role =~ /^cr\//) {
1.393     www      4045:         my $cwosec=$url;
                   4046:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4047: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4048:            &logthis('Refused custom assignrole: '.
                   4049:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4050: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4051:            return 'refused'; 
                   4052:         }
1.21      www      4053:         $mrole='cr';
1.678     raeburn  4054:     } elsif ($role =~ /^gr\//) {
                   4055:         my $cwogrp=$url;
                   4056:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4057:         unless (&allowed('mdg',$cwogrp)) {
                   4058:             &logthis('Refused group assignrole: '.
                   4059:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4060:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4061:             return 'refused';
                   4062:         }
                   4063:         $mrole='gr';
1.21      www      4064:     } else {
1.82      www      4065:         my $cwosec=$url;
1.83      www      4066:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4067:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4068:            &logthis('Refused assignrole: '.
                   4069:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4070: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4071:            return 'refused'; 
                   4072:         }
1.21      www      4073:         $mrole=$role;
                   4074:     }
1.620     albertel 4075:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4076:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4077:     if ($end) { $command.='_'.$end; }
1.21      www      4078:     if ($start) {
                   4079: 	if ($end) { 
1.81      www      4080:            $command.='_'.$start; 
1.21      www      4081:         } else {
1.81      www      4082:            $command.='_0_'.$start;
1.21      www      4083:         }
                   4084:     }
1.357     www      4085: # actually delete
                   4086:     if ($deleteflag) {
1.373     www      4087: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4088: # modify command to delete the role
1.620     albertel 4089:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4090:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4091: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4092: # set start and finish to negative values for userrolelog
                   4093:            $start=-1;
                   4094:            $end=-1;
                   4095:         }
                   4096:     }
                   4097: # send command
1.349     www      4098:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4099: # log new user role if status is ok
1.349     www      4100:     if ($answer eq 'ok') {
1.663     raeburn  4101: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.349     www      4102:     }
                   4103:     return $answer;
1.169     harris41 4104: }
                   4105: 
                   4106: # -------------------------------------------------- Modify user authentication
1.197     www      4107: # Overrides without validation
                   4108: 
1.169     harris41 4109: sub modifyuserauth {
                   4110:     my ($udom,$uname,$umode,$upass)=@_;
                   4111:     my $uhome=&homeserver($uname,$udom);
1.197     www      4112:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4113:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4114:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4115:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4116:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4117: 		     &escape($upass),$uhome);
1.620     albertel 4118:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4119:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4120:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4121:     &log($udom,,$uname,$uhome,
1.620     albertel 4122:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4123:                                      $env{'user.name'}.', '.$umode.
1.197     www      4124:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4125:     unless ($reply eq 'ok') {
1.197     www      4126:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4127: 	return 'error: '.$reply;
                   4128:     }   
1.170     harris41 4129:     return 'ok';
1.80      www      4130: }
                   4131: 
1.81      www      4132: # --------------------------------------------------------------- Modify a user
1.80      www      4133: 
1.81      www      4134: sub modifyuser {
1.206     matthew  4135:     my ($udom,    $uname, $uid,
                   4136:         $umode,   $upass, $first,
                   4137:         $middle,  $last,  $gene,
1.387     www      4138:         $forceid, $desiredhome, $email)=@_;
1.198     www      4139:     $udom=~s/\W//g;
                   4140:     $uname=~s/\W//g;
1.81      www      4141:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4142:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4143: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4144:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4145:                                      ' desiredhome not specified'). 
1.620     albertel 4146:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4147:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4148:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4149: # ----------------------------------------------------------------- Create User
1.406     albertel 4150:     if (($uhome eq 'no_host') && 
                   4151: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4152:         my $unhome='';
1.209     matthew  4153:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4154:             $unhome = $desiredhome;
1.620     albertel 4155: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4156: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4157:         } else { # load balancing routine for determining $unhome
1.80      www      4158:             my $tryserver;
1.81      www      4159:             my $loadm=10000000;
1.80      www      4160:             foreach $tryserver (keys %libserv) {
                   4161: 	       if ($hostdom{$tryserver} eq $udom) {
                   4162:                   my $answer=reply('load',$tryserver);
                   4163:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4164: 		      $loadm=$answer;
                   4165:                       $unhome=$tryserver;
                   4166:                   }
                   4167: 	       }
                   4168: 	    }
                   4169:         }
                   4170:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4171: 	    return 'error: unable to find a home server for '.$uname.
                   4172:                    ' in domain '.$udom;
1.80      www      4173:         }
                   4174:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4175:                          &escape($upass),$unhome);
                   4176: 	unless ($reply eq 'ok') {
                   4177:             return 'error: '.$reply;
                   4178:         }   
1.230     stredwic 4179:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4180:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4181: 	    return 'error: unable verify users home machine.';
1.80      www      4182:         }
1.209     matthew  4183:     }   # End of creation of new user
1.80      www      4184: # ---------------------------------------------------------------------- Add ID
                   4185:     if ($uid) {
                   4186:        $uid=~tr/A-Z/a-z/;
                   4187:        my %uidhash=&idrget($udom,$uname);
1.196     www      4188:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4189:          && (!$forceid)) {
1.80      www      4190: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4191: 	      return 'error: user id "'.$uid.'" does not match '.
                   4192:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4193:           }
                   4194:        } else {
                   4195: 	  &idput($udom,($uname => $uid));
                   4196:        }
                   4197:     }
                   4198: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4199:     my @tmp=&get('environment',
1.134     albertel 4200: 		   ['firstname','middlename','lastname','generation'],
                   4201: 		   $udom,$uname);
1.313     matthew  4202:     my %names;
                   4203:     if ($tmp[0] =~ m/^error:.*/) { 
                   4204:         %names=(); 
                   4205:     } else {
                   4206:         %names = @tmp;
                   4207:     }
1.388     www      4208: #
                   4209: # Make sure to not trash student environment if instructor does not bother
                   4210: # to supply name and email information
                   4211: #
                   4212:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4213:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4214:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4215:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4216:     if ($email) {
                   4217:        $email=~s/[^\w\@\.\-\,]//gs;
                   4218:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4219: 			   $names{'critnotification'} = $email;
                   4220: 			   $names{'permanentemail'} = $email; }
                   4221:     }
1.134     albertel 4222:     my $reply = &put('environment', \%names, $udom,$uname);
                   4223:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4224:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4225:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4226:              $umode.', '.$first.', '.$middle.', '.
                   4227: 	     $last.', '.$gene.' by '.
1.620     albertel 4228:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4229:     return 'ok';
1.80      www      4230: }
                   4231: 
1.81      www      4232: # -------------------------------------------------------------- Modify student
1.80      www      4233: 
1.81      www      4234: sub modifystudent {
                   4235:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4236:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4237:     if (!$cid) {
1.620     albertel 4238: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4239: 	    return 'not_in_class';
                   4240: 	}
1.80      www      4241:     }
                   4242: # --------------------------------------------------------------- Make the user
1.81      www      4243:     my $reply=&modifyuser
1.209     matthew  4244: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4245:          $desiredhome,$email);
1.80      www      4246:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4247:     # This will cause &modify_student_enrollment to get the uid from the
                   4248:     # students environment
                   4249:     $uid = undef if (!$forceid);
1.455     albertel 4250:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4251: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4252:     return $reply;
                   4253: }
                   4254: 
                   4255: sub modify_student_enrollment {
1.515     raeburn  4256:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4257:     my ($cdom,$cnum,$chome);
                   4258:     if (!$cid) {
1.620     albertel 4259: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4260: 	    return 'not_in_class';
                   4261: 	}
1.620     albertel 4262: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4263: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4264:     } else {
                   4265: 	($cdom,$cnum)=split(/_/,$cid);
                   4266:     }
1.620     albertel 4267:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4268:     if (!$chome) {
1.457     raeburn  4269: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4270:     }
1.455     albertel 4271:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4272:     # Make sure the user exists
1.81      www      4273:     my $uhome=&homeserver($uname,$udom);
                   4274:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4275: 	return 'error: no such user';
                   4276:     }
1.297     matthew  4277:     # Get student data if we were not given enough information
                   4278:     if (!defined($first)  || $first  eq '' || 
                   4279:         !defined($last)   || $last   eq '' || 
                   4280:         !defined($uid)    || $uid    eq '' || 
                   4281:         !defined($middle) || $middle eq '' || 
                   4282:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4283:         # They did not supply us with enough data to enroll the student, so
                   4284:         # we need to pick up more information.
1.297     matthew  4285:         my %tmp = &get('environment',
1.294     matthew  4286:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4287:                        ,$udom,$uname);
                   4288: 
1.455     albertel 4289:         #foreach (keys(%tmp)) {
                   4290:         #    &logthis("key $_ = ".$tmp{$_});
                   4291:         #}
1.294     matthew  4292:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4293:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4294:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4295:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4296:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4297:     }
1.556     albertel 4298:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4299:     my $reply=cput('classlist',
                   4300: 		   {"$uname:$udom" => 
1.515     raeburn  4301: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4302: 		   $cdom,$cnum);
1.81      www      4303:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4304: 	return 'error: '.$reply;
1.652     albertel 4305:     } else {
                   4306: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4307:     }
1.297     matthew  4308:     # Add student role to user
1.83      www      4309:     my $uurl='/'.$cid;
1.81      www      4310:     $uurl=~s/\_/\//g;
                   4311:     if ($usec) {
                   4312: 	$uurl.='/'.$usec;
                   4313:     }
                   4314:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4315: }
                   4316: 
1.556     albertel 4317: sub format_name {
                   4318:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4319:     my $name;
                   4320:     if ($first ne 'lastname') {
                   4321: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4322:     } else {
                   4323: 	if ($lastname=~/\S/) {
                   4324: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4325: 	    $name=~s/\s+,/,/;
                   4326: 	} else {
                   4327: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4328: 	}
                   4329:     }
                   4330:     $name=~s/^\s+//;
                   4331:     $name=~s/\s+$//;
                   4332:     $name=~s/\s+/ /g;
                   4333:     return $name;
                   4334: }
                   4335: 
1.84      www      4336: # ------------------------------------------------- Write to course preferences
                   4337: 
                   4338: sub writecoursepref {
                   4339:     my ($courseid,%prefs)=@_;
                   4340:     $courseid=~s/^\///;
                   4341:     $courseid=~s/\_/\//g;
                   4342:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4343:     my $chome=homeserver($cnum,$cdomain);
                   4344:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4345: 	return 'error: no such course';
                   4346:     }
                   4347:     my $cstring='';
1.191     harris41 4348:     foreach (keys %prefs) {
1.84      www      4349: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4350:     }
1.84      www      4351:     $cstring=~s/\&$//;
                   4352:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4353: }
                   4354: 
                   4355: # ---------------------------------------------------------- Make/modify course
                   4356: 
                   4357: sub createcourse {
1.571     raeburn  4358:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      4359:     $url=&declutter($url);
                   4360:     my $cid='';
1.264     matthew  4361:     unless (&allowed('ccc',$udom)) {
1.84      www      4362:         return 'refused';
                   4363:     }
                   4364: # ------------------------------------------------------------------- Create ID
1.674     www      4365:    my $uname=int(1+rand(9)).
                   4366:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4367:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4368:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4369: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4370:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4371:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4372:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4373:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4374:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4375:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4376:            return 'error: unable to generate unique course-ID';
                   4377:        } 
                   4378:    }
1.264     matthew  4379: # ------------------------------------------------ Check supplied server name
1.620     albertel 4380:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4381:     if (! exists($libserv{$course_server})) {
                   4382:         return 'error:bad server name '.$course_server;
                   4383:     }
1.84      www      4384: # ------------------------------------------------------------- Make the course
                   4385:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4386:                       $course_server);
1.84      www      4387:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4388:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4389:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4390: 	return 'error: no such course';
                   4391:     }
1.271     www      4392: # ----------------------------------------------------------------- Course made
1.516     raeburn  4393: # log existence
                   4394:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  4395:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      4396:     &flushcourselogs();
                   4397: # set toplevel url
1.271     www      4398:     my $topurl=$url;
                   4399:     unless ($nonstandard) {
                   4400: # ------------------------------------------ For standard courses, make top url
                   4401:         my $mapurl=&clutter($url);
1.278     www      4402:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4403:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4404: <map>
                   4405: <resource id="1" type="start"></resource>
                   4406: <resource id="2" src="$mapurl"></resource>
                   4407: <resource id="3" type="finish"></resource>
                   4408: <link index="1" from="1" to="2"></link>
                   4409: <link index="2" from="2" to="3"></link>
                   4410: </map>
                   4411: ENDINITMAP
                   4412:         $topurl=&declutter(
1.638     albertel 4413:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4414:                           );
                   4415:     }
                   4416: # ----------------------------------------------------------- Write preferences
1.84      www      4417:     &writecoursepref($udom.'_'.$uname,
                   4418:                      ('description' => $description,
1.271     www      4419:                       'url'         => $topurl));
1.84      www      4420:     return '/'.$udom.'/'.$uname;
                   4421: }
                   4422: 
1.21      www      4423: # ---------------------------------------------------------- Assign Custom Role
                   4424: 
                   4425: sub assigncustomrole {
1.357     www      4426:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4427:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4428:                        $end,$start,$deleteflag);
1.21      www      4429: }
                   4430: 
                   4431: # ----------------------------------------------------------------- Revoke Role
                   4432: 
                   4433: sub revokerole {
1.357     www      4434:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4435:     my $now=time;
1.357     www      4436:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4437: }
                   4438: 
                   4439: # ---------------------------------------------------------- Revoke Custom Role
                   4440: 
                   4441: sub revokecustomrole {
1.357     www      4442:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4443:     my $now=time;
1.357     www      4444:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4445:            $deleteflag);
1.17      www      4446: }
                   4447: 
1.533     banghart 4448: # ------------------------------------------------------------ Disk usage
1.535     albertel 4449: sub diskusage {
1.533     banghart 4450:     my ($udom,$uname,$directoryRoot)=@_;
                   4451:     $directoryRoot =~ s/\/$//;
1.535     albertel 4452:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4453:     return $listing;
1.512     banghart 4454: }
                   4455: 
1.566     banghart 4456: sub is_locked {
                   4457:     my ($file_name, $domain, $user) = @_;
                   4458:     my @check;
                   4459:     my $is_locked;
                   4460:     push @check, $file_name;
1.613     albertel 4461:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4462: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4463:     my ($tmp)=keys(%locked);
                   4464:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 4465: 
1.566     banghart 4466:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   4467:         $is_locked = 'true';
                   4468:     } else {
                   4469:         $is_locked = 'false';
                   4470:     }
                   4471: }
                   4472: 
1.559     banghart 4473: # ------------------------------------------------------------- Mark as Read Only
                   4474: 
                   4475: sub mark_as_readonly {
                   4476:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4477:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4478:     my ($tmp)=keys(%current_permissions);
                   4479:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4480:     foreach my $file (@{$files}) {
1.561     banghart 4481:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4482:     }
1.613     albertel 4483:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4484:     return;
                   4485: }
                   4486: 
1.572     banghart 4487: # ------------------------------------------------------------Save Selected Files
                   4488: 
                   4489: sub save_selected_files {
                   4490:     my ($user, $path, @files) = @_;
                   4491:     my $filename = $user."savedfiles";
1.573     banghart 4492:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4493:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4494:     foreach my $file (@files) {
1.620     albertel 4495:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4496:     }
                   4497:     foreach my $file (@other_files) {
1.574     banghart 4498:         print (OUT $file."\n");
1.572     banghart 4499:     }
1.574     banghart 4500:     close (OUT);
1.572     banghart 4501:     return 'ok';
                   4502: }
                   4503: 
1.574     banghart 4504: sub clear_selected_files {
                   4505:     my ($user) = @_;
                   4506:     my $filename = $user."savedfiles";
                   4507:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4508:     print (OUT undef);
                   4509:     close (OUT);
                   4510:     return ("ok");    
                   4511: }
                   4512: 
1.572     banghart 4513: sub files_in_path {
                   4514:     my ($user, $path) = @_;
                   4515:     my $filename = $user."savedfiles";
                   4516:     my %return_files;
1.574     banghart 4517:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4518:     while (my $line_in = <IN>) {
1.574     banghart 4519:         chomp ($line_in);
                   4520:         my @paths_and_file = split (m!/!, $line_in);
                   4521:         my $file_part = pop (@paths_and_file);
                   4522:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4523:         $path_part.='/';
                   4524:         my $path_and_file = $path_part.$file_part;
                   4525:         if ($path_part eq $path) {
                   4526:             $return_files{$file_part}= 'selected';
                   4527:         }
                   4528:     }
1.574     banghart 4529:     close (IN);
                   4530:     return (\%return_files);
1.572     banghart 4531: }
                   4532: 
                   4533: # called in portfolio select mode, to show files selected NOT in current directory
                   4534: sub files_not_in_path {
                   4535:     my ($user, $path) = @_;
                   4536:     my $filename = $user."savedfiles";
                   4537:     my @return_files;
                   4538:     my $path_part;
1.574     banghart 4539:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4540:     while (<IN>) {
                   4541:         #ok, I know it's clunky, but I want it to work
                   4542:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4543:         my $file_part = pop (@paths_and_file);
                   4544:         chomp ($file_part);
                   4545:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4546:         $path_part .= '/';
                   4547:         my $path_and_file = $path_part.$file_part;
                   4548:         if ($path_part ne $path) {
1.574     banghart 4549:             push (@return_files, ($path_and_file));
1.572     banghart 4550:         }
                   4551:     }
1.574     banghart 4552:     close (OUT);
                   4553:     return (@return_files);
1.572     banghart 4554: }
                   4555: 
1.561     banghart 4556: #--------------------------------------------------------------Get Marked as Read Only
                   4557: 
1.629     banghart 4558: 
1.561     banghart 4559: sub get_marked_as_readonly {
                   4560:     my ($domain,$user,$what) = @_;
1.613     albertel 4561:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4562:     my ($tmp)=keys(%current_permissions);
                   4563:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563     banghart 4564:     my @readonly_files;
1.629     banghart 4565:     my $cmp1=$what;
                   4566:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.563     banghart 4567:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 4568:         if (ref($value) eq "ARRAY"){
                   4569:             foreach my $stored_what (@{$value}) {
1.629     banghart 4570:                 my $cmp2=$stored_what;
                   4571:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
                   4572:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4573:                     push(@readonly_files, $file_name);
1.563     banghart 4574:                 } elsif (!defined($what)) {
                   4575:                     push(@readonly_files, $file_name);
1.561     banghart 4576:                 }
                   4577:             }
                   4578:         } 
                   4579:     }
                   4580:     return @readonly_files;
                   4581: }
1.577     banghart 4582: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4583: 
1.577     banghart 4584: sub get_marked_as_readonly_hash {
                   4585:     my ($domain,$user,$what) = @_;
1.613     albertel 4586:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4587:     my ($tmp)=keys(%current_permissions);
                   4588:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4589: 
1.577     banghart 4590:     my %readonly_files;
                   4591:     while (my ($file_name,$value) = each(%current_permissions)) {
                   4592:         if (ref($value) eq "ARRAY"){
                   4593:             foreach my $stored_what (@{$value}) {
                   4594:                 if ($stored_what eq $what) {
                   4595:                     $readonly_files{$file_name} = 'locked';
                   4596:                 } elsif (!defined($what)) {
                   4597:                     $readonly_files{$file_name} = 'locked';
                   4598:                 }
                   4599:             }
                   4600:         } 
                   4601:     }
                   4602:     return %readonly_files;
                   4603: }
1.559     banghart 4604: # ------------------------------------------------------------ Unmark as Read Only
                   4605: 
                   4606: sub unmark_as_readonly {
1.629     banghart 4607:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4608:     # for portfolio submissions, $what contains [$symb,$crsid] 
                   4609:     my ($domain,$user,$what,$file_name) = @_;
1.634     albertel 4610:     my $symb_crs = $what;
                   4611:     if (ref($what)) { $symb_crs=join('',@$what); }
1.613     albertel 4612:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4613:     my ($tmp)=keys(%current_permissions);
                   4614:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4615:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.650     albertel 4616:     foreach my $file (@readonly_files) {
                   4617: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4618: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4619:         my @new_locks;
                   4620:         my @del_keys;
                   4621:         if (ref($current_locks) eq "ARRAY"){
                   4622:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4623:                 my $compare=$locker;
                   4624:                 if (ref($locker)) { $compare=join('',@{$locker}) };
1.650     albertel 4625:                 if ($compare ne $symb_crs) {
                   4626:                     push(@new_locks, $locker);
1.563     banghart 4627:                 }
                   4628:             }
1.650     albertel 4629:             if (scalar(@new_locks) > 0) {
1.563     banghart 4630:                 $current_permissions{$file} = \@new_locks;
                   4631:             } else {
                   4632:                 push(@del_keys, $file);
1.613     albertel 4633:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4634:                 delete($current_permissions{$file});
1.563     banghart 4635:             }
                   4636:         }
1.561     banghart 4637:     }
1.613     albertel 4638:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4639:     return;
                   4640: }
1.512     banghart 4641: 
1.17      www      4642: # ------------------------------------------------------------ Directory lister
                   4643: 
                   4644: sub dirlist {
1.253     stredwic 4645:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4646: 
1.18      www      4647:     $uri=~s/^\///;
                   4648:     $uri=~s/\/$//;
1.253     stredwic 4649:     my ($udom, $uname);
                   4650:     (undef,$udom,$uname)=split(/\//,$uri);
                   4651:     if(defined($userdomain)) {
                   4652:         $udom = $userdomain;
                   4653:     }
                   4654:     if(defined($username)) {
                   4655:         $uname = $username;
                   4656:     }
                   4657: 
                   4658:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4659:     if(defined($alternateDirectoryRoot)) {
                   4660:         $dirRoot = $alternateDirectoryRoot;
                   4661:         $dirRoot =~ s/\/$//;
                   4662:     }
                   4663: 
                   4664:     if($udom) {
                   4665:         if($uname) {
1.605     matthew  4666:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4667:                               homeserver($uname,$udom));
1.605     matthew  4668:             my @listing_results;
                   4669:             if ($listing eq 'unknown_cmd') {
                   4670:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4671:                                homeserver($uname,$udom));
                   4672:                 @listing_results = split(/:/,$listing);
                   4673:             } else {
                   4674:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4675:             }
                   4676:             return @listing_results;
1.253     stredwic 4677:         } elsif(!defined($alternateDirectoryRoot)) {
                   4678:             my $tryserver;
                   4679:             my %allusers=();
                   4680:             foreach $tryserver (keys %libserv) {
                   4681:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4682:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4683:                                       $udom, $tryserver);
1.605     matthew  4684:                     my @listing_results;
                   4685:                     if ($listing eq 'unknown_cmd') {
                   4686:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4687:                                        $udom, $tryserver);
                   4688:                         @listing_results = split(/:/,$listing);
                   4689:                     } else {
                   4690:                         @listing_results =
                   4691:                             map { &unescape($_); } split(/:/,$listing);
                   4692:                     }
                   4693:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4694:                         $listing_results[0] ne 'empty'       &&
                   4695:                         $listing_results[0] ne 'con_lost') {
                   4696:                         foreach (@listing_results) {
1.253     stredwic 4697:                             my ($entry,@stat)=split(/&/,$_);
                   4698:                             $allusers{$entry}=1;
                   4699:                         }
                   4700:                     }
1.191     harris41 4701:                 }
1.253     stredwic 4702:             }
                   4703:             my $alluserstr='';
                   4704:             foreach (sort keys %allusers) {
                   4705:                 $alluserstr.=$_.'&user:';
                   4706:             }
                   4707:             $alluserstr=~s/:$//;
                   4708:             return split(/:/,$alluserstr);
                   4709:         } else {
                   4710:             my @emptyResults = ();
                   4711:             push(@emptyResults, 'missing user name');
                   4712:             return split(':',@emptyResults);
                   4713:         }
                   4714:     } elsif(!defined($alternateDirectoryRoot)) {
                   4715:         my $tryserver;
                   4716:         my %alldom=();
                   4717:         foreach $tryserver (keys %libserv) {
                   4718:             $alldom{$hostdom{$tryserver}}=1;
                   4719:         }
                   4720:         my $alldomstr='';
                   4721:         foreach (sort keys %alldom) {
1.397     albertel 4722:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4723:         }
                   4724:         $alldomstr=~s/:$//;
                   4725:         return split(/:/,$alldomstr);       
                   4726:     } else {
                   4727:         my @emptyResults = ();
                   4728:         push(@emptyResults, 'missing domain');
                   4729:         return split(':',@emptyResults);
1.275     stredwic 4730:     }
                   4731: }
                   4732: 
                   4733: # --------------------------------------------- GetFileTimestamp
                   4734: # This function utilizes dirlist and returns the date stamp for
                   4735: # when it was last modified.  It will also return an error of -1
                   4736: # if an error occurs
                   4737: 
1.410     matthew  4738: ##
                   4739: ## FIXME: This subroutine assumes its caller knows something about the
                   4740: ## directory structure of the home server for the student ($root).
                   4741: ## Not a good assumption to make.  Since this is for looking up files
                   4742: ## in user directories, the full path should be constructed by lond, not
                   4743: ## whatever machine we request data from.
                   4744: ##
1.275     stredwic 4745: sub GetFileTimestamp {
                   4746:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4747:     $studentDomain=~s/\W//g;
                   4748:     $studentName=~s/\W//g;
                   4749:     my $subdir=$studentName.'__';
                   4750:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4751:     my $proname="$studentDomain/$subdir/$studentName";
                   4752:     $proname .= '/'.$filename;
1.375     matthew  4753:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4754:                                               $studentName, $root);
1.275     stredwic 4755:     my @stats = split('&', $fileStat);
                   4756:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4757:         # @stats contains first the filename, then the stat output
                   4758:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4759:     } else {
                   4760:         return -1;
1.253     stredwic 4761:     }
1.26      www      4762: }
                   4763: 
1.712     albertel 4764: sub stat_file {
                   4765:     my ($uri) = @_;
1.722     albertel 4766:     $uri = &clutter($uri);
                   4767: 
                   4768:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 4769:     if ($uri =~ m-^/adm/-) {
                   4770: 	$uri=~s-^/adm/wrapper/-/-;
                   4771: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 4772:     }
1.712     albertel 4773:     my ($udom,$uname,$file,$dir);
                   4774:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   4775: 	($udom,$uname,$file) =
                   4776: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   4777: 	$file = 'userfiles/'.$file;
                   4778: 	$dir = &Apache::loncommon::propath($udom,$uname);
                   4779:     }
                   4780:     if ($uri =~ m-^/res/-) {
                   4781: 	($udom,$uname) = 
                   4782: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   4783: 	$file = $uri;
                   4784:     }
                   4785: 
                   4786:     if (!$udom || !$uname || !$file) {
                   4787: 	# unable to handle the uri
                   4788: 	return ();
                   4789:     }
                   4790: 
                   4791:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   4792:     my @stats = split('&', $result);
1.721     banghart 4793:     
1.712     albertel 4794:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   4795: 	shift(@stats); #filename is first
                   4796: 	return @stats;
                   4797:     }
                   4798:     return ();
                   4799: }
                   4800: 
1.26      www      4801: # -------------------------------------------------------- Value of a Condition
                   4802: 
1.713     albertel 4803: # gets the value of a specific preevaluated condition
                   4804: #    stored in the string  $env{user.state.<cid>}
                   4805: # or looks up a condition reference in the bighash and if if hasn't
                   4806: # already been evaluated recurses into docondval to get the value of
                   4807: # the condition, then memoizing it to 
                   4808: #   $env{user.state.<cid>.<condition>}
1.40      www      4809: sub directcondval {
                   4810:     my $number=shift;
1.620     albertel 4811:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4812: 	&Apache::lonuserstate::evalstate();
                   4813:     }
1.713     albertel 4814:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   4815: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   4816:     } elsif ($number =~ /^_/) {
                   4817: 	my $sub_condition;
                   4818: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   4819: 		&GDBM_READER(),0640)) {
                   4820: 	    $sub_condition=$bighash{'conditions'.$number};
                   4821: 	    untie(%bighash);
                   4822: 	}
                   4823: 	my $value = &docondval($sub_condition);
                   4824: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   4825: 	return $value;
                   4826:     }
1.620     albertel 4827:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4828:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4829:     } else {
                   4830:        return 2;
                   4831:     }
                   4832: }
                   4833: 
1.713     albertel 4834: # get the collection of conditions for this resource
1.26      www      4835: sub condval {
                   4836:     my $condidx=shift;
1.54      www      4837:     my $allpathcond='';
1.713     albertel 4838:     foreach my $cond (split(/\|/,$condidx)) {
                   4839: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   4840: 	    $allpathcond.=
                   4841: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   4842: 	}
1.191     harris41 4843:     }
1.54      www      4844:     $allpathcond=~s/\|$//;
1.713     albertel 4845:     return &docondval($allpathcond);
                   4846: }
                   4847: 
                   4848: #evaluates an expression of conditions
                   4849: sub docondval {
                   4850:     my ($allpathcond) = @_;
                   4851:     my $result=0;
                   4852:     if ($env{'request.course.id'}
                   4853: 	&& defined($allpathcond)) {
                   4854: 	my $operand='|';
                   4855: 	my @stack;
                   4856: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   4857: 	    if ($chunk eq '(') {
                   4858: 		push @stack,($operand,$result);
                   4859: 	    } elsif ($chunk eq ')') {
                   4860: 		my $before=pop @stack;
                   4861: 		if (pop @stack eq '&') {
                   4862: 		    $result=$result>$before?$before:$result;
                   4863: 		} else {
                   4864: 		    $result=$result>$before?$result:$before;
                   4865: 		}
                   4866: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   4867: 		$operand=$chunk;
                   4868: 	    } else {
                   4869: 		my $new=directcondval($chunk);
                   4870: 		if ($operand eq '&') {
                   4871: 		    $result=$result>$new?$new:$result;
                   4872: 		} else {
                   4873: 		    $result=$result>$new?$result:$new;
                   4874: 		}
                   4875: 	    }
                   4876: 	}
1.26      www      4877:     }
                   4878:     return $result;
1.421     albertel 4879: }
                   4880: 
                   4881: # ---------------------------------------------------- Devalidate courseresdata
                   4882: 
                   4883: sub devalidatecourseresdata {
                   4884:     my ($coursenum,$coursedomain)=@_;
                   4885:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4886:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4887: }
                   4888: 
1.200     www      4889: # --------------------------------------------------- Course Resourcedata Query
                   4890: 
1.624     albertel 4891: sub get_courseresdata {
                   4892:     my ($coursenum,$coursedomain)=@_;
1.200     www      4893:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4894:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4895:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4896:     my %dumpreply;
1.417     albertel 4897:     unless (defined($cached)) {
1.624     albertel 4898: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4899: 	$result=\%dumpreply;
1.251     albertel 4900: 	my ($tmp) = keys(%dumpreply);
                   4901: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4902: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4903: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4904: 	    return $tmp;
1.416     albertel 4905: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4906: 	    $result=undef;
1.599     albertel 4907: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4908: 	}
                   4909:     }
1.624     albertel 4910:     return $result;
                   4911: }
                   4912: 
1.633     albertel 4913: sub devalidateuserresdata {
                   4914:     my ($uname,$udom)=@_;
                   4915:     my $hashid="$udom:$uname";
                   4916:     &devalidate_cache_new('userres',$hashid);
                   4917: }
                   4918: 
1.624     albertel 4919: sub get_userresdata {
                   4920:     my ($uname,$udom)=@_;
                   4921:     #most student don\'t have any data set, check if there is some data
                   4922:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4923: 
                   4924:     my $hashid="$udom:$uname";
                   4925:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4926:     if (!defined($cached)) {
                   4927: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4928: 	$result=\%resourcedata;
                   4929: 	&do_cache_new('userres',$hashid,$result,600);
                   4930:     }
                   4931:     my ($tmp)=keys(%$result);
                   4932:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4933: 	return $result;
                   4934:     }
                   4935:     #error 2 occurs when the .db doesn't exist
                   4936:     if ($tmp!~/error: 2 /) {
1.672     albertel 4937: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 4938: 		 " Trying to get resource data for ".
                   4939: 		 $uname." at ".$udom.": ".
                   4940: 		 $tmp."</font>");
                   4941:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 4942: 	#&EXT_cache_set($udom,$uname);
                   4943: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 4944: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 4945:     }
                   4946:     return $tmp;
                   4947: }
                   4948: 
                   4949: sub resdata {
                   4950:     my ($name,$domain,$type,@which)=@_;
                   4951:     my $result;
                   4952:     if ($type eq 'course') {
                   4953: 	$result=&get_courseresdata($name,$domain);
                   4954:     } elsif ($type eq 'user') {
                   4955: 	$result=&get_userresdata($name,$domain);
                   4956:     }
                   4957:     if (!ref($result)) { return $result; }    
1.251     albertel 4958:     foreach my $item (@which) {
1.417     albertel 4959: 	if (defined($result->{$item})) {
                   4960: 	    return $result->{$item};
1.251     albertel 4961: 	}
1.250     albertel 4962:     }
1.291     albertel 4963:     return undef;
1.200     www      4964: }
                   4965: 
1.379     matthew  4966: #
                   4967: # EXT resource caching routines
                   4968: #
                   4969: 
                   4970: sub clear_EXT_cache_status {
1.383     albertel 4971:     &delenv('cache.EXT.');
1.379     matthew  4972: }
                   4973: 
                   4974: sub EXT_cache_status {
                   4975:     my ($target_domain,$target_user) = @_;
1.383     albertel 4976:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 4977:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  4978:         # We know already the user has no data
                   4979:         return 1;
                   4980:     } else {
                   4981:         return 0;
                   4982:     }
                   4983: }
                   4984: 
                   4985: sub EXT_cache_set {
                   4986:     my ($target_domain,$target_user) = @_;
1.383     albertel 4987:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 4988:     #&appenv($cachename => time);
1.379     matthew  4989: }
                   4990: 
1.28      www      4991: # --------------------------------------------------------- Value of a Variable
1.58      www      4992: sub EXT {
1.715     albertel 4993: 
1.395     albertel 4994:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      4995:     unless ($varname) { return ''; }
1.218     albertel 4996:     #get real user name/domain, courseid and symb
                   4997:     my $courseid;
1.359     albertel 4998:     my $publicuser;
1.427     www      4999:     if ($symbparm) {
                   5000: 	$symbparm=&get_symb_from_alias($symbparm);
                   5001:     }
1.218     albertel 5002:     if (!($uname && $udom)) {
1.360     albertel 5003:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5004: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5005:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5006:     } else {
1.620     albertel 5007: 	$courseid=$env{'request.course.id'};
1.218     albertel 5008:     }
1.48      www      5009:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5010:     my $rest;
1.320     albertel 5011:     if (defined($therest[0])) {
1.48      www      5012:        $rest=join('.',@therest);
                   5013:     } else {
                   5014:        $rest='';
                   5015:     }
1.320     albertel 5016: 
1.57      www      5017:     my $qualifierrest=$qualifier;
                   5018:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5019:     my $spacequalifierrest=$space;
                   5020:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5021:     if ($realm eq 'user') {
1.48      www      5022: # --------------------------------------------------------------- user.resource
                   5023: 	if ($space eq 'resource') {
1.651     albertel 5024: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5025: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5026: 		 &&
                   5027: 		 ($symbparm eq &symbread()) ) {
1.335     albertel 5028: 		return $Apache::lonhomework::history{$qualifierrest};
                   5029: 	    } else {
1.359     albertel 5030: 		my %restored;
1.620     albertel 5031: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5032: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5033: 		} else {
                   5034: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5035: 		}
1.335     albertel 5036: 		return $restored{$qualifierrest};
                   5037: 	    }
1.48      www      5038: # ----------------------------------------------------------------- user.access
                   5039:         } elsif ($space eq 'access') {
1.218     albertel 5040: 	    # FIXME - not supporting calls for a specific user
1.48      www      5041:             return &allowed($qualifier,$rest);
                   5042: # ------------------------------------------ user.preferences, user.environment
                   5043:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5044: 	    if (($uname eq $env{'user.name'}) &&
                   5045: 		($udom eq $env{'user.domain'})) {
                   5046: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5047: 	    } else {
1.359     albertel 5048: 		my %returnhash;
                   5049: 		if (!$publicuser) {
                   5050: 		    %returnhash=&userenvironment($udom,$uname,
                   5051: 						 $qualifierrest);
                   5052: 		}
1.218     albertel 5053: 		return $returnhash{$qualifierrest};
                   5054: 	    }
1.48      www      5055: # ----------------------------------------------------------------- user.course
                   5056:         } elsif ($space eq 'course') {
1.218     albertel 5057: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5058:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5059: # ------------------------------------------------------------------- user.role
                   5060:         } elsif ($space eq 'role') {
1.218     albertel 5061: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5062:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5063:             if ($qualifier eq 'value') {
                   5064: 		return $role;
                   5065:             } elsif ($qualifier eq 'extent') {
                   5066:                 return $where;
                   5067:             }
                   5068: # ----------------------------------------------------------------- user.domain
                   5069:         } elsif ($space eq 'domain') {
1.218     albertel 5070:             return $udom;
1.48      www      5071: # ------------------------------------------------------------------- user.name
                   5072:         } elsif ($space eq 'name') {
1.218     albertel 5073:             return $uname;
1.48      www      5074: # ---------------------------------------------------- Any other user namespace
1.29      www      5075:         } else {
1.359     albertel 5076: 	    my %reply;
                   5077: 	    if (!$publicuser) {
                   5078: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5079: 	    }
                   5080: 	    return $reply{$qualifierrest};
1.48      www      5081:         }
1.236     www      5082:     } elsif ($realm eq 'query') {
                   5083: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5084:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5085: 						[$spacequalifierrest]);
1.620     albertel 5086: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5087:    } elsif ($realm eq 'request') {
1.48      www      5088: # ------------------------------------------------------------- request.browser
                   5089:         if ($space eq 'browser') {
1.430     www      5090: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5091: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5092: 		    return 1;
                   5093: 		} else {
                   5094: 		    return 0;
                   5095: 		}
                   5096: 	    } else {
1.620     albertel 5097: 		return $env{'browser.'.$qualifier};
1.430     www      5098: 	    }
1.57      www      5099: # ------------------------------------------------------------ request.filename
                   5100:         } else {
1.620     albertel 5101:             return $env{'request.'.$spacequalifierrest};
1.29      www      5102:         }
1.28      www      5103:     } elsif ($realm eq 'course') {
1.48      www      5104: # ---------------------------------------------------------- course.description
1.620     albertel 5105:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5106:     } elsif ($realm eq 'resource') {
1.165     www      5107: 
1.620     albertel 5108: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5109: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5110: 	}
1.693     albertel 5111: 
                   5112: 	if ($space eq 'title') {
                   5113: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5114: 	    return &gettitle($symbparm);
                   5115: 	}
                   5116: 	
                   5117: 	if ($space eq 'map') {
                   5118: 	    my ($map) = &decode_symb($symbparm);
                   5119: 	    return &symbread($map);
                   5120: 	}
                   5121: 
                   5122: 	my ($section, $group, @groups);
1.593     albertel 5123: 	my ($courselevelm,$courselevel);
1.539     albertel 5124: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5125: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5126: 
1.218     albertel 5127: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5128: 
1.60      www      5129: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5130: 	    my $symbp=$symbparm;
1.409     www      5131: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 5132: 
                   5133: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5134: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5135: 
1.620     albertel 5136: 	    if (($env{'user.name'} eq $uname) &&
                   5137: 		($env{'user.domain'} eq $udom)) {
                   5138: 		$section=$env{'request.course.sec'};
1.691     raeburn  5139:                 @groups=&sort_course_groups($env{'request.course.groups'},$courseid); 
1.218     albertel 5140: 	    } else {
1.539     albertel 5141: 		if (! defined($usection)) {
1.551     albertel 5142: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5143: 		} else {
                   5144: 		    $section = $usection;
                   5145: 		}
1.684     raeburn  5146:                 my $grouplist = &get_users_groups($udom,$uname,$courseid);
                   5147:                 if ($grouplist) {
1.691     raeburn  5148:                     @groups=&sort_course_groups($grouplist,$courseid);
1.684     raeburn  5149:                 }
1.218     albertel 5150: 	    }
                   5151: 
                   5152: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5153: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5154: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5155: 
1.593     albertel 5156: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5157: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5158: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5159: 
1.60      www      5160: # ----------------------------------------------------------- first, check user
1.624     albertel 5161: 
                   5162: 	    my $userreply=&resdata($uname,$udom,'user',
                   5163: 				       ($courselevelr,$courselevelm,
                   5164: 					$courselevel));
                   5165: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5166: 
1.594     albertel 5167: # ------------------------------------------------ second, check some of course
1.684     raeburn  5168:             my $coursereply;
1.691     raeburn  5169:             if (@groups > 0) {
                   5170:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5171:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5172:                 if (defined($coursereply)) { return $coursereply; }
                   5173:             }
1.96      www      5174: 
1.684     raeburn  5175: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5176: 				     $env{'course.'.$courseid.'.domain'},
                   5177: 				     'course',
                   5178: 				     ($seclevelr,$seclevelm,$seclevel,
                   5179: 				      $courselevelr));
1.287     albertel 5180: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5181: 
1.60      www      5182: # ------------------------------------------------------ third, check map parms
1.218     albertel 5183: 	    my %parmhash=();
                   5184: 	    my $thisparm='';
                   5185: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5186: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5187: 		    &GDBM_READER(),0640)) {
1.218     albertel 5188: 		$thisparm=$parmhash{$symbparm};
                   5189: 		untie(%parmhash);
                   5190: 	    }
                   5191: 	    if ($thisparm) { return $thisparm; }
                   5192: 	}
1.594     albertel 5193: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5194: 
1.218     albertel 5195: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5196: 	my $filename;
                   5197: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5198: 	if ($symbparm) {
1.409     www      5199: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5200: 	} else {
1.620     albertel 5201: 	    $filename=$env{'request.filename'};
1.282     albertel 5202: 	}
                   5203: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5204: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5205: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5206: 	if (defined($metadata)) { return $metadata; }
1.142     www      5207: 
1.594     albertel 5208: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5209: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5210: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5211: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5212: 				     $env{'course.'.$courseid.'.domain'},
                   5213: 				     'course',
                   5214: 				     ($courselevelm,$courselevel));
1.593     albertel 5215: 	    if (defined($coursereply)) { return $coursereply; }
                   5216: 	}
1.145     www      5217: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5218: 	unless ($space eq '0') {
1.336     albertel 5219: 	    my @parts=split(/_/,$space);
                   5220: 	    my $id=pop(@parts);
                   5221: 	    my $part=join('_',@parts);
                   5222: 	    if ($part eq '') { $part='0'; }
                   5223: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5224: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5225: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5226: 	}
1.395     albertel 5227: 	if ($recurse) { return undef; }
                   5228: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5229: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5230: 
1.48      www      5231: # ---------------------------------------------------- Any other user namespace
                   5232:     } elsif ($realm eq 'environment') {
                   5233: # ----------------------------------------------------------------- environment
1.620     albertel 5234: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5235: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5236: 	} else {
                   5237: 	    my %returnhash=&userenvironment($udom,$uname,
                   5238: 					    $spacequalifierrest);
                   5239: 	    return $returnhash{$spacequalifierrest};
                   5240: 	}
1.28      www      5241:     } elsif ($realm eq 'system') {
1.48      www      5242: # ----------------------------------------------------------------- system.time
                   5243: 	if ($space eq 'time') {
                   5244: 	    return time;
                   5245:         }
1.696     albertel 5246:     } elsif ($realm eq 'server') {
                   5247: # ----------------------------------------------------------------- system.time
                   5248: 	if ($space eq 'name') {
                   5249: 	    return $ENV{'SERVER_NAME'};
                   5250:         }
1.28      www      5251:     }
1.48      www      5252:     return '';
1.61      www      5253: }
                   5254: 
1.691     raeburn  5255: sub check_group_parms {
                   5256:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5257:     my @groupitems = ();
                   5258:     my $resultitem;
                   5259:     my @levels = ($symbparm,$mapparm,$what);
                   5260:     foreach my $group (@{$groups}) {
                   5261:         foreach my $level (@levels) {
                   5262:              my $item = $courseid.'.['.$group.'].'.$level;
                   5263:              push(@groupitems,$item);
                   5264:         }
                   5265:     }
                   5266:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5267:                             $env{'course.'.$courseid.'.domain'},
                   5268:                                      'course',@groupitems);
                   5269:     return $coursereply;
                   5270: }
                   5271: 
                   5272: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
                   5273:     my ($grouplist,$courseid) = @_;
1.720     albertel 5274:     my @groups = sort(split(/:/,$grouplist));
1.691     raeburn  5275:     return @groups;
                   5276: }
                   5277: 
1.395     albertel 5278: sub packages_tab_default {
                   5279:     my ($uri,$varname)=@_;
                   5280:     my (undef,$part,$name)=split(/\./,$varname);
                   5281:     my $packages=&metadata($uri,'packages');
                   5282:     foreach my $package (split(/,/,$packages)) {
                   5283: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 5284: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5285: 	    return $packagetab{"$pack_type&$name&default"};
                   5286: 	}
1.585     albertel 5287: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5288: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5289: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5290: 	}
                   5291:     }
                   5292:     return undef;
                   5293: }
                   5294: 
1.334     albertel 5295: sub add_prefix_and_part {
                   5296:     my ($prefix,$part)=@_;
                   5297:     my $keyroot;
                   5298:     if (defined($prefix) && $prefix !~ /^__/) {
                   5299: 	# prefix that has a part already
                   5300: 	$keyroot=$prefix;
                   5301:     } elsif (defined($prefix)) {
                   5302: 	# prefix that is missing a part
                   5303: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5304:     } else {
                   5305: 	# no prefix at all
                   5306: 	if (defined($part)) { $keyroot='_'.$part; }
                   5307:     }
                   5308:     return $keyroot;
                   5309: }
                   5310: 
1.71      www      5311: # ---------------------------------------------------------------- Get metadata
                   5312: 
1.599     albertel 5313: my %metaentry;
1.71      www      5314: sub metadata {
1.176     www      5315:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5316:     $uri=&declutter($uri);
1.288     albertel 5317:     # if it is a non metadata possible uri return quickly
1.529     albertel 5318:     if (($uri eq '') || 
                   5319: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5320: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5321:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5322: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5323: 	return undef;
1.288     albertel 5324:     }
1.73      www      5325:     my $filename=$uri;
                   5326:     $uri=~s/\.meta$//;
1.172     www      5327: #
                   5328: # Is the metadata already cached?
1.177     www      5329: # Look at timestamp of caching
1.172     www      5330: # Everything is cached by the main uri, libraries are never directly cached
                   5331: #
1.428     albertel 5332:     if (!defined($liburi)) {
1.599     albertel 5333: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5334: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5335:     }
                   5336:     {
1.172     www      5337: #
                   5338: # Is this a recursive call for a library?
                   5339: #
1.599     albertel 5340: #	if (! exists($metacache{$uri})) {
                   5341: #	    $metacache{$uri}={};
                   5342: #	}
1.171     www      5343:         if ($liburi) {
                   5344: 	    $liburi=&declutter($liburi);
                   5345:             $filename=$liburi;
1.401     bowersj2 5346:         } else {
1.599     albertel 5347: 	    &devalidate_cache_new('meta',$uri);
                   5348: 	    undef(%metaentry);
1.401     bowersj2 5349: 	}
1.140     www      5350:         my %metathesekeys=();
1.73      www      5351:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5352: 	my $metastring;
1.609     banghart 5353: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 5354: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5355: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5356: 	    $metastring=&getfile($file);
1.489     albertel 5357: 	}
1.208     albertel 5358:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5359:         my $token;
1.140     www      5360:         undef %metathesekeys;
1.71      www      5361:         while ($token=$parser->get_token) {
1.339     albertel 5362: 	    if ($token->[0] eq 'S') {
                   5363: 		if (defined($token->[2]->{'package'})) {
1.172     www      5364: #
                   5365: # This is a package - get package info
                   5366: #
1.339     albertel 5367: 		    my $package=$token->[2]->{'package'};
                   5368: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5369: 		    if (defined($token->[2]->{'id'})) { 
                   5370: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5371: 		    }
1.599     albertel 5372: 		    if ($metaentry{':packages'}) {
                   5373: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5374: 		    } else {
1.599     albertel 5375: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5376: 		    }
1.613     albertel 5377: 		    foreach (sort keys %packagetab) {
1.432     albertel 5378: 			my $part=$keyroot;
                   5379: 			$part=~s/^\_//;
                   5380: 			if ($_=~/^\Q$package\E\&/ || 
                   5381: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 5382: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 5383: 			    # ignore package.tab specified default values
                   5384:                             # here &package_tab_default() will fetch those
                   5385: 			    if ($subp eq 'default') { next; }
1.339     albertel 5386: 			    my $value=$packagetab{$_};
1.432     albertel 5387: 			    my $unikey;
                   5388: 			    if ($pack =~ /_0$/) {
                   5389: 				$unikey='parameter_0_'.$name;
                   5390: 				$part=0;
                   5391: 			    } else {
                   5392: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5393: 			    }
1.339     albertel 5394: 			    if ($subp eq 'display') {
                   5395: 				$value.=' [Part: '.$part.']';
                   5396: 			    }
1.599     albertel 5397: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5398: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5399: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5400: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5401: 			    }
1.599     albertel 5402: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5403: 				$metaentry{':'.$unikey}=
                   5404: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5405: 			    }
1.339     albertel 5406: 			}
                   5407: 		    }
                   5408: 		} else {
1.172     www      5409: #
                   5410: # This is not a package - some other kind of start tag
1.339     albertel 5411: #
                   5412: 		    my $entry=$token->[1];
                   5413: 		    my $unikey;
                   5414: 		    if ($entry eq 'import') {
                   5415: 			$unikey='';
                   5416: 		    } else {
                   5417: 			$unikey=$entry;
                   5418: 		    }
                   5419: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5420: 
                   5421: 		    if (defined($token->[2]->{'id'})) { 
                   5422: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5423: 		    }
1.175     www      5424: 
1.339     albertel 5425: 		    if ($entry eq 'import') {
1.175     www      5426: #
                   5427: # Importing a library here
1.339     albertel 5428: #
                   5429: 			if ($depthcount<20) {
                   5430: 			    my $location=$parser->get_text('/import');
                   5431: 			    my $dir=$filename;
                   5432: 			    $dir=~s|[^/]*$||;
                   5433: 			    $location=&filelocation($dir,$location);
                   5434: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5435: 							       $location,$unikey,
                   5436: 							       $depthcount+1)))) {
1.599     albertel 5437: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 5438: 				$metathesekeys{$_}=1;
                   5439: 			    }
                   5440: 			}
                   5441: 		    } else { 
                   5442: 			
                   5443: 			if (defined($token->[2]->{'name'})) { 
                   5444: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5445: 			}
                   5446: 			$metathesekeys{$unikey}=1;
                   5447: 			foreach (@{$token->[3]}) {
1.599     albertel 5448: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 5449: 			}
                   5450: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5451: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5452: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5453: 		 # only ws inside the tag, and not in default, so use default
                   5454: 		 # as value
1.599     albertel 5455: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5456: 			} else {
1.321     albertel 5457: 		  # either something interesting inside the tag or default
                   5458:                   # uninteresting
1.599     albertel 5459: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5460: 			}
1.172     www      5461: # end of not-a-package not-a-library import
1.339     albertel 5462: 		    }
1.172     www      5463: # end of not-a-package start tag
1.339     albertel 5464: 		}
1.172     www      5465: # the next is the end of "start tag"
1.339     albertel 5466: 	    }
                   5467: 	}
1.483     albertel 5468: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   5469: 	foreach my $key (sort(keys(%packagetab))) {
                   5470: 	    #no specific packages #how's our extension
                   5471: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5472: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5473: 					 \%metathesekeys);
                   5474: 	}
1.599     albertel 5475: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 5476: 	    foreach my $key (sort(keys(%packagetab))) {
                   5477: 		#no specific packages well let's get default then
                   5478: 		if ($key!~/^default&/) { next; }
1.488     albertel 5479: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5480: 					     \%metathesekeys);
                   5481: 	    }
                   5482: 	}
1.338     www      5483: # are there custom rights to evaluate
1.599     albertel 5484: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5485: 
1.338     www      5486:     #
                   5487:     # Importing a rights file here
1.339     albertel 5488:     #
                   5489: 	    unless ($depthcount) {
1.599     albertel 5490: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5491: 		my $dir=$filename;
                   5492: 		$dir=~s|[^/]*$||;
                   5493: 		$location=&filelocation($dir,$location);
                   5494: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5495: 						   $location,'_rights',
                   5496: 						   $depthcount+1)))) {
1.599     albertel 5497: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 5498: 		    $metathesekeys{$_}=1;
                   5499: 		}
                   5500: 	    }
                   5501: 	}
1.599     albertel 5502: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   5503: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5504: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 5505: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      5506: # this is the end of "was not already recently cached
1.71      www      5507:     }
1.599     albertel 5508:     return $metaentry{':'.$what};
1.261     albertel 5509: }
                   5510: 
1.488     albertel 5511: sub metadata_create_package_def {
1.483     albertel 5512:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5513:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5514:     if ($subp eq 'default') { next; }
                   5515:     
1.599     albertel 5516:     if (defined($metaentry{':packages'})) {
                   5517: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5518:     } else {
1.599     albertel 5519: 	$metaentry{':packages'}=$package;
1.483     albertel 5520:     }
                   5521:     my $value=$packagetab{$key};
                   5522:     my $unikey;
                   5523:     $unikey='parameter_0_'.$name;
1.599     albertel 5524:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5525:     $$metathesekeys{$unikey}=1;
1.599     albertel 5526:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5527: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5528:     }
1.599     albertel 5529:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5530: 	$metaentry{':'.$unikey}=
                   5531: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5532:     }
                   5533: }
                   5534: 
1.261     albertel 5535: sub metadata_generate_part0 {
                   5536:     my ($metadata,$metacache,$uri) = @_;
                   5537:     my %allnames;
                   5538:     foreach my $metakey (sort keys %$metadata) {
                   5539: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5540: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5541: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5542: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5543: 	    $allnames{$name}=$part;
                   5544: 	  }
                   5545: 	}
                   5546:     }
                   5547:     foreach my $name (keys(%allnames)) {
                   5548:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5549:       my $key=":parameter_0_$name";
1.261     albertel 5550:       $$metacache{"$key.part"}='0';
                   5551:       $$metacache{"$key.name"}=$name;
1.428     albertel 5552:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5553: 					   $allnames{$name}.'_'.$name.
                   5554: 					   '.type'};
1.428     albertel 5555:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5556: 			     '.display'};
1.644     www      5557:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5558:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5559:       $$metacache{"$key.display"}=$olddis;
                   5560:     }
1.71      www      5561: }
                   5562: 
1.301     www      5563: # ------------------------------------------------- Get the title of a resource
                   5564: 
                   5565: sub gettitle {
                   5566:     my $urlsymb=shift;
                   5567:     my $symb=&symbread($urlsymb);
1.534     albertel 5568:     if ($symb) {
1.620     albertel 5569: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5570: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5571: 	if (defined($cached)) { 
                   5572: 	    return $result;
                   5573: 	}
1.534     albertel 5574: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5575: 	my $title='';
                   5576: 	my %bighash;
1.620     albertel 5577: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5578: 		&GDBM_READER(),0640)) {
                   5579: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5580: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5581: 	    untie %bighash;
                   5582: 	}
                   5583: 	$title=~s/\&colon\;/\:/gs;
                   5584: 	if ($title) {
1.599     albertel 5585: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5586: 	}
                   5587: 	$urlsymb=$url;
                   5588:     }
                   5589:     my $title=&metadata($urlsymb,'title');
                   5590:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5591:     return $title;
1.301     www      5592: }
1.613     albertel 5593: 
1.614     albertel 5594: sub get_slot {
                   5595:     my ($which,$cnum,$cdom)=@_;
                   5596:     if (!$cnum || !$cdom) {
                   5597: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5598: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5599: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5600:     }
1.703     albertel 5601:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   5602:     my %slotinfo;
                   5603:     if (exists($remembered{$key})) {
                   5604: 	$slotinfo{$which} = $remembered{$key};
                   5605:     } else {
                   5606: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5607: 	&Apache::lonhomework::showhash(%slotinfo);
                   5608: 	my ($tmp)=keys(%slotinfo);
                   5609: 	if ($tmp=~/^error:/) { return (); }
                   5610: 	$remembered{$key} = $slotinfo{$which};
                   5611:     }
1.616     albertel 5612:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5613: 	return %{$slotinfo{$which}};
                   5614:     }
                   5615:     return $slotinfo{$which};
1.614     albertel 5616: }
1.31      www      5617: # ------------------------------------------------- Update symbolic store links
                   5618: 
                   5619: sub symblist {
                   5620:     my ($mapname,%newhash)=@_;
1.438     www      5621:     $mapname=&deversion(&declutter($mapname));
1.31      www      5622:     my %hash;
1.620     albertel 5623:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5624:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5625:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 5626: 	    foreach my $url (keys %newhash) {
                   5627: 		next if ($url eq 'last_known'
                   5628: 			 && $env{'form.no_update_last_known'});
                   5629: 		$hash{declutter($url)}=&encode_symb($mapname,
                   5630: 						    $newhash{$url}->[1],
                   5631: 						    $newhash{$url}->[0]);
1.191     harris41 5632:             }
1.31      www      5633:             if (untie(%hash)) {
                   5634: 		return 'ok';
                   5635:             }
                   5636:         }
                   5637:     }
                   5638:     return 'error';
1.212     www      5639: }
                   5640: 
                   5641: # --------------------------------------------------------------- Verify a symb
                   5642: 
                   5643: sub symbverify {
1.510     www      5644:     my ($symb,$thisurl)=@_;
                   5645:     my $thisfn=$thisurl;
                   5646: # wrapper not part of symbs
                   5647:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 5648:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      5649:     $thisfn=&declutter($thisfn);
1.215     www      5650: # direct jump to resource in page or to a sequence - will construct own symbs
                   5651:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5652: # check URL part
1.409     www      5653:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5654: 
1.431     www      5655:     unless ($url eq $thisfn) { return 0; }
1.213     www      5656: 
1.216     www      5657:     $symb=&symbclean($symb);
1.510     www      5658:     $thisurl=&deversion($thisurl);
1.439     www      5659:     $thisfn=&deversion($thisfn);
1.213     www      5660: 
                   5661:     my %bighash;
                   5662:     my $okay=0;
1.431     www      5663: 
1.620     albertel 5664:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5665:                             &GDBM_READER(),0640)) {
1.510     www      5666:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5667:         unless ($ids) { 
1.510     www      5668:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5669:         }
                   5670:         if ($ids) {
                   5671: # ------------------------------------------------------------------- Has ID(s)
                   5672: 	    foreach (split(/\,/,$ids)) {
1.644     www      5673: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5674:                if (
                   5675:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5676:    eq $symb) { 
1.620     albertel 5677: 		   if (($env{'request.role.adv'}) ||
                   5678: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5679: 		       $okay=1; 
                   5680: 		   }
                   5681: 	       }
1.216     www      5682: 	   }
                   5683:         }
1.213     www      5684: 	untie(%bighash);
                   5685:     }
                   5686:     return $okay;
1.31      www      5687: }
                   5688: 
1.210     www      5689: # --------------------------------------------------------------- Clean-up symb
                   5690: 
                   5691: sub symbclean {
                   5692:     my $symb=shift;
1.568     albertel 5693:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5694: # remove version from map
                   5695:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      5696: 
1.210     www      5697: # remove version from URL
                   5698:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      5699: 
1.507     www      5700: # remove wrapper
                   5701: 
1.510     www      5702:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 5703:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      5704:     return $symb;
1.409     www      5705: }
                   5706: 
                   5707: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 5708: 
                   5709: sub encode_symb {
                   5710:     my ($map,$resid,$url)=@_;
                   5711:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   5712: }
1.409     www      5713: 
                   5714: sub decode_symb {
1.568     albertel 5715:     my $symb=shift;
                   5716:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   5717:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      5718:     return (&fixversion($map),$resid,&fixversion($url));
                   5719: }
                   5720: 
                   5721: sub fixversion {
                   5722:     my $fn=shift;
1.609     banghart 5723:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      5724:     my %bighash;
                   5725:     my $uri=&clutter($fn);
1.620     albertel 5726:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      5727: # is this cached?
1.599     albertel 5728:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      5729:     if (defined($cached)) { return $result; }
                   5730: # unfortunately not cached, or expired
1.620     albertel 5731:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      5732: 	    &GDBM_READER(),0640)) {
                   5733:  	if ($bighash{'version_'.$uri}) {
                   5734:  	    my $version=$bighash{'version_'.$uri};
1.444     www      5735:  	    unless (($version eq 'mostrecent') || 
                   5736: 		    ($version==&getversion($uri))) {
1.440     www      5737:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   5738:  	    }
                   5739:  	}
                   5740:  	untie %bighash;
1.413     www      5741:     }
1.599     albertel 5742:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      5743: }
                   5744: 
                   5745: sub deversion {
                   5746:     my $url=shift;
                   5747:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   5748:     return $url;
1.210     www      5749: }
                   5750: 
1.31      www      5751: # ------------------------------------------------------ Return symb list entry
                   5752: 
                   5753: sub symbread {
1.249     www      5754:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 5755:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 5756:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      5757: # no filename provided? try from environment
1.44      www      5758:     unless ($thisfn) {
1.620     albertel 5759:         if ($env{'request.symb'}) {
                   5760: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 5761: 	}
1.620     albertel 5762: 	$thisfn=$env{'request.filename'};
1.44      www      5763:     }
1.569     albertel 5764:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      5765: # is that filename actually a symb? Verify, clean, and return
                   5766:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 5767: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 5768: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 5769: 	}
1.242     www      5770:     }
1.44      www      5771:     $thisfn=declutter($thisfn);
1.31      www      5772:     my %hash;
1.37      www      5773:     my %bighash;
                   5774:     my $syval='';
1.620     albertel 5775:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  5776:         my $targetfn = $thisfn;
1.609     banghart 5777:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  5778:             $targetfn = 'adm/wrapper/'.$thisfn;
                   5779:         }
1.687     albertel 5780: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   5781: 	    $targetfn=$1;
                   5782: 	}
1.620     albertel 5783:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5784:                       &GDBM_READER(),0640)) {
1.481     raeburn  5785: 	    $syval=$hash{$targetfn};
1.37      www      5786:             untie(%hash);
                   5787:         }
                   5788: # ---------------------------------------------------------- There was an entry
                   5789:         if ($syval) {
1.601     albertel 5790: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 5791: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 5792: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 5793: 		    #return $env{$cache_str}='';
1.601     albertel 5794: 		#}    
                   5795: 		#$syval.=$1;
                   5796: 	    #}
1.37      www      5797:         } else {
                   5798: # ------------------------------------------------------- Was not in symb table
1.620     albertel 5799:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5800:                             &GDBM_READER(),0640)) {
1.37      www      5801: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      5802:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      5803:               unless ($ids) { 
                   5804:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      5805:               }
                   5806:               unless ($ids) {
                   5807: # alias?
                   5808: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      5809:               }
1.37      www      5810:               if ($ids) {
                   5811: # ------------------------------------------------------------------- Has ID(s)
                   5812:                  my @possibilities=split(/\,/,$ids);
1.39      www      5813:                  if ($#possibilities==0) {
                   5814: # ----------------------------------------------- There is only one possibility
1.37      www      5815: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 5816: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5817: 						    $resid,$thisfn);
1.249     www      5818:                  } elsif (!$donotrecurse) {
1.39      www      5819: # ------------------------------------------ There is more than one possibility
                   5820:                      my $realpossible=0;
1.191     harris41 5821:                      foreach (@possibilities) {
1.39      www      5822: 			 my $file=$bighash{'src_'.$_};
                   5823:                          if (&allowed('bre',$file)) {
                   5824:          		    my ($mapid,$resid)=split(/\./,$_);
                   5825:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   5826: 				$realpossible++;
1.626     albertel 5827:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5828: 						    $resid,$thisfn);
1.39      www      5829:                             }
                   5830: 			 }
1.191     harris41 5831:                      }
1.39      www      5832: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      5833:                  } else {
                   5834:                      $syval='';
1.37      www      5835:                  }
                   5836: 	      }
                   5837:               untie(%bighash)
1.481     raeburn  5838:            }
1.31      www      5839:         }
1.62      www      5840:         if ($syval) {
1.620     albertel 5841: 	    return $env{$cache_str}=$syval;
1.62      www      5842:         }
1.31      www      5843:     }
1.44      www      5844:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 5845:     return $env{$cache_str}='';
1.31      www      5846: }
                   5847: 
                   5848: # ---------------------------------------------------------- Return random seed
                   5849: 
1.32      www      5850: sub numval {
                   5851:     my $txt=shift;
                   5852:     $txt=~tr/A-J/0-9/;
                   5853:     $txt=~tr/a-j/0-9/;
                   5854:     $txt=~tr/K-T/0-9/;
                   5855:     $txt=~tr/k-t/0-9/;
                   5856:     $txt=~tr/U-Z/0-5/;
                   5857:     $txt=~tr/u-z/0-5/;
                   5858:     $txt=~s/\D//g;
1.564     albertel 5859:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      5860:     return int($txt);
1.368     albertel 5861: }
                   5862: 
1.484     albertel 5863: sub numval2 {
                   5864:     my $txt=shift;
                   5865:     $txt=~tr/A-J/0-9/;
                   5866:     $txt=~tr/a-j/0-9/;
                   5867:     $txt=~tr/K-T/0-9/;
                   5868:     $txt=~tr/k-t/0-9/;
                   5869:     $txt=~tr/U-Z/0-5/;
                   5870:     $txt=~tr/u-z/0-5/;
                   5871:     $txt=~s/\D//g;
                   5872:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5873:     my $total;
                   5874:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5875:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5876:     return int($total);
                   5877: }
                   5878: 
1.575     albertel 5879: sub numval3 {
                   5880:     use integer;
                   5881:     my $txt=shift;
                   5882:     $txt=~tr/A-J/0-9/;
                   5883:     $txt=~tr/a-j/0-9/;
                   5884:     $txt=~tr/K-T/0-9/;
                   5885:     $txt=~tr/k-t/0-9/;
                   5886:     $txt=~tr/U-Z/0-5/;
                   5887:     $txt=~tr/u-z/0-5/;
                   5888:     $txt=~s/\D//g;
                   5889:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5890:     my $total;
                   5891:     foreach my $val (@txts) { $total+=$val; }
                   5892:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5893:     return $total;
                   5894: }
                   5895: 
1.675     albertel 5896: sub digest {
                   5897:     my ($data)=@_;
                   5898:     my $digest=&Digest::MD5::md5($data);
                   5899:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   5900:     my ($e,$f);
                   5901:     {
                   5902:         use integer;
                   5903:         $e=($a+$b);
                   5904:         $f=($c+$d);
                   5905:         if ($_64bit) {
                   5906:             $e=(($e<<32)>>32);
                   5907:             $f=(($f<<32)>>32);
                   5908:         }
                   5909:     }
                   5910:     if (wantarray) {
                   5911: 	return ($e,$f);
                   5912:     } else {
                   5913: 	my $g;
                   5914: 	{
                   5915: 	    use integer;
                   5916: 	    $g=($e+$f);
                   5917: 	    if ($_64bit) {
                   5918: 		$g=(($g<<32)>>32);
                   5919: 	    }
                   5920: 	}
                   5921: 	return $g;
                   5922:     }
                   5923: }
                   5924: 
1.368     albertel 5925: sub latest_rnd_algorithm_id {
1.675     albertel 5926:     return '64bit5';
1.366     albertel 5927: }
1.32      www      5928: 
1.503     albertel 5929: sub get_rand_alg {
                   5930:     my ($courseid)=@_;
                   5931:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   5932:     if ($courseid) {
1.620     albertel 5933: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 5934:     }
                   5935:     return &latest_rnd_algorithm_id();
                   5936: }
                   5937: 
1.562     albertel 5938: sub validCODE {
                   5939:     my ($CODE)=@_;
                   5940:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5941:     return 0;
                   5942: }
                   5943: 
1.491     albertel 5944: sub getCODE {
1.620     albertel 5945:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 5946:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   5947: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   5948: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5949: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5950:     }
                   5951:     return undef;
                   5952: }
                   5953: 
1.31      www      5954: sub rndseed {
1.155     albertel 5955:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5956: 
                   5957:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5958:     if (!$symb) {
1.366     albertel 5959: 	unless ($symb=$wsymb) { return time; }
                   5960:     }
                   5961:     if (!$courseid) { $courseid=$wcourseid; }
                   5962:     if (!$domain) { $domain=$wdomain; }
                   5963:     if (!$username) { $username=$wusername }
1.503     albertel 5964:     my $which=&get_rand_alg();
1.491     albertel 5965:     if (defined(&getCODE())) {
1.675     albertel 5966: 	if ($which eq '64bit5') {
                   5967: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   5968: 	} elsif ($which eq '64bit4') {
1.575     albertel 5969: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5970: 	} else {
                   5971: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5972: 	}
1.675     albertel 5973:     } elsif ($which eq '64bit5') {
                   5974: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 5975:     } elsif ($which eq '64bit4') {
                   5976: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 5977:     } elsif ($which eq '64bit3') {
                   5978: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 5979:     } elsif ($which eq '64bit2') {
                   5980: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 5981:     } elsif ($which eq '64bit') {
                   5982: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   5983:     }
                   5984:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   5985: }
                   5986: 
                   5987: sub rndseed_32bit {
                   5988:     my ($symb,$courseid,$domain,$username)=@_;
                   5989:     {
                   5990: 	use integer;
                   5991: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   5992: 	my $symbseed=numval($symb) << 22;
                   5993: 	my $namechck=unpack("%32C*",$username) << 17;
                   5994: 	my $nameseed=numval($username) << 12;
                   5995: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   5996: 	my $courseseed=unpack("%32C*",$courseid);
                   5997: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   5998: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5999: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6000: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6001: 	return $num;
                   6002:     }
                   6003: }
                   6004: 
                   6005: sub rndseed_64bit {
                   6006:     my ($symb,$courseid,$domain,$username)=@_;
                   6007:     {
                   6008: 	use integer;
                   6009: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6010: 	my $symbseed=numval($symb) << 10;
                   6011: 	my $namechck=unpack("%32S*",$username);
                   6012: 	
                   6013: 	my $nameseed=numval($username) << 21;
                   6014: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6015: 	my $courseseed=unpack("%32S*",$courseid);
                   6016: 	
                   6017: 	my $num1=$symbchck+$symbseed+$namechck;
                   6018: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6019: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6020: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6021: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6022: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6023: 	return "$num1,$num2";
1.155     albertel 6024:     }
1.366     albertel 6025: }
                   6026: 
1.443     albertel 6027: sub rndseed_64bit2 {
                   6028:     my ($symb,$courseid,$domain,$username)=@_;
                   6029:     {
                   6030: 	use integer;
                   6031: 	# strings need to be an even # of cahracters long, it it is odd the
                   6032:         # last characters gets thrown away
                   6033: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6034: 	my $symbseed=numval($symb) << 10;
                   6035: 	my $namechck=unpack("%32S*",$username.' ');
                   6036: 	
                   6037: 	my $nameseed=numval($username) << 21;
1.501     albertel 6038: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6039: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6040: 	
                   6041: 	my $num1=$symbchck+$symbseed+$namechck;
                   6042: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6043: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6044: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6045: 	return "$num1,$num2";
                   6046:     }
                   6047: }
                   6048: 
                   6049: sub rndseed_64bit3 {
                   6050:     my ($symb,$courseid,$domain,$username)=@_;
                   6051:     {
                   6052: 	use integer;
                   6053: 	# strings need to be an even # of cahracters long, it it is odd the
                   6054:         # last characters gets thrown away
                   6055: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6056: 	my $symbseed=numval2($symb) << 10;
                   6057: 	my $namechck=unpack("%32S*",$username.' ');
                   6058: 	
                   6059: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6060: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6061: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6062: 	
                   6063: 	my $num1=$symbchck+$symbseed+$namechck;
                   6064: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6065: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6066: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6067: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6068: 	
1.503     albertel 6069: 	return "$num1:$num2";
1.443     albertel 6070:     }
                   6071: }
                   6072: 
1.575     albertel 6073: sub rndseed_64bit4 {
                   6074:     my ($symb,$courseid,$domain,$username)=@_;
                   6075:     {
                   6076: 	use integer;
                   6077: 	# strings need to be an even # of cahracters long, it it is odd the
                   6078:         # last characters gets thrown away
                   6079: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6080: 	my $symbseed=numval3($symb) << 10;
                   6081: 	my $namechck=unpack("%32S*",$username.' ');
                   6082: 	
                   6083: 	my $nameseed=numval3($username) << 21;
                   6084: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6085: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6086: 	
                   6087: 	my $num1=$symbchck+$symbseed+$namechck;
                   6088: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6089: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6090: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6091: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6092: 	
                   6093: 	return "$num1:$num2";
                   6094:     }
                   6095: }
                   6096: 
1.675     albertel 6097: sub rndseed_64bit5 {
                   6098:     my ($symb,$courseid,$domain,$username)=@_;
                   6099:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6100:     return "$num1:$num2";
                   6101: }
                   6102: 
1.366     albertel 6103: sub rndseed_CODE_64bit {
                   6104:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6105:     {
1.366     albertel 6106: 	use integer;
1.443     albertel 6107: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6108: 	my $symbseed=numval2($symb);
1.491     albertel 6109: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6110: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6111: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6112: 	my $num1=$symbseed+$CODEchck;
                   6113: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6114: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6115: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6116: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6117: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6118: 	return "$num1:$num2";
1.366     albertel 6119:     }
                   6120: }
                   6121: 
1.575     albertel 6122: sub rndseed_CODE_64bit4 {
                   6123:     my ($symb,$courseid,$domain,$username)=@_;
                   6124:     {
                   6125: 	use integer;
                   6126: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6127: 	my $symbseed=numval3($symb);
                   6128: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6129: 	my $CODEseed=numval3(&getCODE());
                   6130: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6131: 	my $num1=$symbseed+$CODEchck;
                   6132: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6133: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6134: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6135: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6136: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6137: 	return "$num1:$num2";
                   6138:     }
                   6139: }
                   6140: 
1.675     albertel 6141: sub rndseed_CODE_64bit5 {
                   6142:     my ($symb,$courseid,$domain,$username)=@_;
                   6143:     my $code = &getCODE();
                   6144:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6145:     return "$num1:$num2";
                   6146: }
                   6147: 
1.366     albertel 6148: sub setup_random_from_rndseed {
                   6149:     my ($rndseed)=@_;
1.503     albertel 6150:     if ($rndseed =~/([,:])/) {
                   6151: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6152: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6153:     } else {
                   6154: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6155:     }
1.36      albertel 6156: }
                   6157: 
1.474     albertel 6158: sub latest_receipt_algorithm_id {
                   6159:     return 'receipt2';
                   6160: }
                   6161: 
1.480     www      6162: sub recunique {
                   6163:     my $fucourseid=shift;
                   6164:     my $unique;
1.620     albertel 6165:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6166: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6167:     } else {
                   6168: 	$unique=$perlvar{'lonReceipt'};
                   6169:     }
                   6170:     return unpack("%32C*",$unique);
                   6171: }
                   6172: 
                   6173: sub recprefix {
                   6174:     my $fucourseid=shift;
                   6175:     my $prefix;
1.620     albertel 6176:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6177: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6178:     } else {
                   6179: 	$prefix=$perlvar{'lonHostID'};
                   6180:     }
                   6181:     return unpack("%32C*",$prefix);
                   6182: }
                   6183: 
1.76      www      6184: sub ireceipt {
1.474     albertel 6185:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6186:     my $cuname=unpack("%32C*",$funame);
                   6187:     my $cudom=unpack("%32C*",$fudom);
                   6188:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6189:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6190:     my $cunique=&recunique($fucourseid);
1.474     albertel 6191:     my $cpart=unpack("%32S*",$part);
1.480     www      6192:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6193:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6194: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6195: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6196: 			       " and ".($cpart%$cudom));
                   6197: 			       
                   6198: 	$return.= ($cunique%$cuname+
                   6199: 		   $cunique%$cudom+
                   6200: 		   $cusymb%$cuname+
                   6201: 		   $cusymb%$cudom+
                   6202: 		   $cucourseid%$cuname+
                   6203: 		   $cucourseid%$cudom+
                   6204: 		   $cpart%$cuname+
                   6205: 		   $cpart%$cudom);
                   6206:     } else {
                   6207: 	$return.= ($cunique%$cuname+
                   6208: 		   $cunique%$cudom+
                   6209: 		   $cusymb%$cuname+
                   6210: 		   $cusymb%$cudom+
                   6211: 		   $cucourseid%$cuname+
                   6212: 		   $cucourseid%$cudom);
                   6213:     }
                   6214:     return $return;
1.76      www      6215: }
                   6216: 
                   6217: sub receipt {
1.474     albertel 6218:     my ($part)=@_;
                   6219:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6220:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6221: }
1.260     ng       6222: 
1.36      albertel 6223: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6224: # returns either the contents of the file or 
                   6225: # -1 if the file doesn't exist
1.481     raeburn  6226: #
                   6227: # if the target is a file that was uploaded via DOCS, 
                   6228: # a check will be made to see if a current copy exists on the local server,
                   6229: # if it does this will be served, otherwise a copy will be retrieved from
                   6230: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6231: # the local server.   
1.472     albertel 6232: 
1.36      albertel 6233: sub getfile {
1.538     albertel 6234:     my ($file) = @_;
1.609     banghart 6235:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6236:     &repcopy($file);
                   6237:     return &readfile($file);
                   6238: }
                   6239: 
                   6240: sub repcopy_userfile {
                   6241:     my ($file)=@_;
1.609     banghart 6242:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6243:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6244:     my ($cdom,$cnum,$filename) = 
                   6245: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6246:     my ($info,$rtncode);
                   6247:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6248:     if (-e "$file") {
                   6249: 	my @fileinfo = stat($file);
                   6250: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6251: 	if ($lwpresp ne 'ok') {
                   6252: 	    if ($rtncode eq '404') {
1.538     albertel 6253: 		unlink($file);
1.482     albertel 6254: 	    }
1.517     albertel 6255: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6256: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6257: 	    #my $response=$ua->request($request);
                   6258: 	    #if ($response->is_success()) {
                   6259: 	#	return $response->content;
                   6260: 	#    } else {
                   6261: 	#	return -1;
                   6262: 	#    }
1.482     albertel 6263: 	    return -1;
                   6264: 	}
                   6265: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6266: 	    return 'ok';
1.482     albertel 6267: 	}
                   6268: 	$info = '';
1.538     albertel 6269: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6270: 	if ($lwpresp ne 'ok') {
                   6271: 	    return -1;
                   6272: 	}
                   6273:     } else {
1.538     albertel 6274: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6275: 	if ($lwpresp ne 'ok') {
1.517     albertel 6276: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6277: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6278: 	    my $response=$ua->request($request);
                   6279: 	    if ($response->is_success()) {
1.538     albertel 6280: 		$info=$response->content;
1.517     albertel 6281: 	    } else {
                   6282: 		return -1;
                   6283: 	    }
1.482     albertel 6284: 	}
                   6285: 	my @parts = ($cdom,$cnum); 
                   6286: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6287: 	    push @parts, split(/\//,$1);
1.518     albertel 6288: 	}
1.538     albertel 6289: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6290: 	foreach my $part (@parts) {
                   6291: 	    $path .= '/'.$part;
                   6292: 	    if (!-e $path) {
                   6293: 		mkdir($path,0770);
                   6294: 	    }
                   6295: 	}
                   6296:     }
1.538     albertel 6297:     open(FILE,">$file");
1.482     albertel 6298:     print FILE $info;
                   6299:     close(FILE);
1.607     raeburn  6300:     return 'ok';
1.481     raeburn  6301: }
                   6302: 
1.517     albertel 6303: sub tokenwrapper {
                   6304:     my $uri=shift;
1.552     albertel 6305:     $uri=~s|^http\://([^/]+)||;
                   6306:     $uri=~s|^/||;
1.620     albertel 6307:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6308:     my $token=$1;
1.552     albertel 6309:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6310:     if ($udom && $uname && $file) {
                   6311: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6312:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6313:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6314:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6315:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6316:     } else {
                   6317:         return '/adm/notfound.html';
                   6318:     }
                   6319: }
                   6320: 
1.481     raeburn  6321: sub getuploaded {
                   6322:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6323:     $uri=~s/^\///;
                   6324:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6325:     my $ua=new LWP::UserAgent;
                   6326:     my $request=new HTTP::Request($reqtype,$uri);
                   6327:     my $response=$ua->request($request);
                   6328:     $$rtncode = $response->code;
1.482     albertel 6329:     if (! $response->is_success()) {
                   6330: 	return 'failed';
                   6331:     }      
                   6332:     if ($reqtype eq 'HEAD') {
1.486     www      6333: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6334:     } elsif ($reqtype eq 'GET') {
                   6335: 	$$info = $response->content;
1.472     albertel 6336:     }
1.482     albertel 6337:     return 'ok';
1.36      albertel 6338: }
                   6339: 
1.481     raeburn  6340: sub readfile {
                   6341:     my $file = shift;
                   6342:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6343:     my $fh;
                   6344:     open($fh,"<$file");
                   6345:     my $a='';
                   6346:     while (<$fh>) { $a .=$_; }
                   6347:     return $a;
                   6348: }
                   6349: 
1.36      albertel 6350: sub filelocation {
1.590     banghart 6351:     my ($dir,$file) = @_;
                   6352:     my $location;
                   6353:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6354: 
                   6355:     if ($file =~ m-^/adm/-) {
                   6356: 	$file=~s-^/adm/wrapper/-/-;
                   6357: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6358:     }
1.590     banghart 6359:     if ($file=~m:^/~:) { # is a contruction space reference
                   6360:         $location = $file;
                   6361:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6362:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6363: 	# is a correct contruction space reference
                   6364:         $location = $file;
1.609     banghart 6365:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6366:         my ($udom,$uname,$filename)=
1.609     banghart 6367:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6368:         my $home=&homeserver($uname,$udom);
                   6369:         my $is_me=0;
                   6370:         my @ids=&current_machine_ids();
                   6371:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6372:         if ($is_me) {
                   6373:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   6374:   	      '/userfiles/'.$filename;
                   6375:         } else {
                   6376:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6377:   	      $udom.'/'.$uname.'/'.$filename;
                   6378:         }
                   6379:     } else {
                   6380:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6381:         $file=~s:^/res/:/:;
                   6382:         if ( !( $file =~ m:^/:) ) {
                   6383:             $location = $dir. '/'.$file;
                   6384:         } else {
                   6385:             $location = '/home/httpd/html/res'.$file;
                   6386:         }
1.59      albertel 6387:     }
1.590     banghart 6388:     $location=~s://+:/:g; # remove duplicate /
                   6389:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6390:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6391:     return $location;
1.46      www      6392: }
1.36      albertel 6393: 
1.46      www      6394: sub hreflocation {
                   6395:     my ($dir,$file)=@_;
1.460     albertel 6396:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6397: 	$file=filelocation($dir,$file);
1.700     albertel 6398:     } elsif ($file=~m-^/adm/-) {
                   6399: 	$file=~s-^/adm/wrapper/-/-;
                   6400: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6401:     }
                   6402:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6403: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6404:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6405: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6406:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6407: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6408: 	    -/uploaded/$1/$2/-x;
1.46      www      6409:     }
1.462     albertel 6410:     return $file;
1.465     albertel 6411: }
                   6412: 
                   6413: sub current_machine_domains {
                   6414:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6415:     my @domains;
                   6416:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6417: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6418: 	if ($hostname eq $name) {
                   6419: 	    push(@domains,$hostdom{$id});
                   6420: 	}
                   6421:     }
                   6422:     return @domains;
                   6423: }
                   6424: 
                   6425: sub current_machine_ids {
                   6426:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6427:     my @ids;
                   6428:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6429: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6430: 	if ($hostname eq $name) {
                   6431: 	    push(@ids,$id);
                   6432: 	}
                   6433:     }
                   6434:     return @ids;
1.31      www      6435: }
                   6436: 
                   6437: # ------------------------------------------------------------- Declutters URLs
                   6438: 
                   6439: sub declutter {
                   6440:     my $thisfn=shift;
1.569     albertel 6441:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6442:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6443:     $thisfn=~s/^\///;
1.697     albertel 6444:     $thisfn=~s|^adm/wrapper/||;
                   6445:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      6446:     $thisfn=~s/^res\///;
1.235     www      6447:     $thisfn=~s/\?.+$//;
1.268     www      6448:     return $thisfn;
                   6449: }
                   6450: 
                   6451: # ------------------------------------------------------------- Clutter up URLs
                   6452: 
                   6453: sub clutter {
                   6454:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6455:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6456:        $thisfn='/res'.$thisfn; 
                   6457:     }
1.694     albertel 6458:     if ($thisfn !~m|/adm|) {
1.695     albertel 6459: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 6460: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 6461: 	} else {
                   6462: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   6463: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 6464: 	    if ($embstyle eq 'ssi'
                   6465: 		|| ($embstyle eq 'hdn')
                   6466: 		|| ($embstyle eq 'rat')
                   6467: 		|| ($embstyle eq 'prv')
                   6468: 		|| ($embstyle eq 'ign')) {
                   6469: 		#do nothing with these
                   6470: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 6471: 		|| ($embstyle eq 'emb')
                   6472: 		|| ($embstyle eq 'wrp')) {
                   6473: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 6474: 	    } elsif ($embstyle eq 'unk'
                   6475: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 6476: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 6477: 	    } else {
1.718     www      6478: #		&logthis("Got a blank emb style");
1.695     albertel 6479: 	    }
1.694     albertel 6480: 	}
                   6481:     }
1.31      www      6482:     return $thisfn;
1.12      www      6483: }
                   6484: 
1.557     albertel 6485: sub freeze_escape {
                   6486:     my ($value)=@_;
                   6487:     if (ref($value)) {
                   6488: 	$value=&nfreeze($value);
                   6489: 	return '__FROZEN__'.&escape($value);
                   6490:     }
                   6491:     return &escape($value);
                   6492: }
                   6493: 
1.12      www      6494: # -------------------------------------------------------- Escape Special Chars
                   6495: 
                   6496: sub escape {
                   6497:     my $str=shift;
                   6498:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   6499:     return $str;
                   6500: }
                   6501: 
                   6502: # ----------------------------------------------------- Un-Escape Special Chars
                   6503: 
                   6504: sub unescape {
                   6505:     my $str=shift;
                   6506:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   6507:     return $str;
                   6508: }
1.11      www      6509: 
1.557     albertel 6510: sub thaw_unescape {
                   6511:     my ($value)=@_;
                   6512:     if ($value =~ /^__FROZEN__/) {
                   6513: 	substr($value,0,10,undef);
                   6514: 	$value=&unescape($value);
                   6515: 	return &thaw($value);
                   6516:     }
                   6517:     return &unescape($value);
                   6518: }
                   6519: 
1.436     albertel 6520: sub correct_line_ends {
                   6521:     my ($result)=@_;
                   6522:     $$result =~s/\r\n/\n/mg;
                   6523:     $$result =~s/\r/\n/mg;
1.415     albertel 6524: }
1.1       albertel 6525: # ================================================================ Main Program
                   6526: 
1.184     www      6527: sub goodbye {
1.204     albertel 6528:    &logthis("Starting Shut down");
1.443     albertel 6529: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6530:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6531: #converted
1.599     albertel 6532: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6533:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6534: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6535: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6536: #1.1 only
1.599     albertel 6537: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6538: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6539: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6540: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6541:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6542:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6543:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6544:    &flushcourselogs();
                   6545:    &logthis("Shutting down");
                   6546: }
                   6547: 
1.179     www      6548: BEGIN {
1.228     harris41 6549: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6550:     unless ($readit) {
1.217     harris41 6551: {
1.581     matthew  6552:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6553:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6554: 
                   6555:     while (my $configline=<$config>) {
1.484     albertel 6556:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6557: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6558:            chomp($varvalue);
1.1       albertel 6559:            $perlvar{$varname}=$varvalue;
                   6560:         }
                   6561:     }
1.448     albertel 6562:     close($config);
1.1       albertel 6563: }
1.227     harris41 6564: {
1.448     albertel 6565:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6566: 
                   6567:     while (my $configline=<$config>) {
                   6568:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6569: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6570:            chomp($varvalue);
                   6571:            $perlvar{$varname}=$varvalue;
                   6572:         }
                   6573:     }
1.448     albertel 6574:     close($config);
1.227     harris41 6575: }
1.1       albertel 6576: 
1.327     albertel 6577: # ------------------------------------------------------------ Read domain file
                   6578: {
                   6579:     %domaindescription = ();
                   6580:     %domain_auth_def = ();
                   6581:     %domain_auth_arg_def = ();
1.448     albertel 6582:     my $fh;
                   6583:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6584:        while (<$fh>) {
1.390     matthew  6585:            next if (/^(\#|\s*$)/);
                   6586: #           next if /^\#/;
1.327     albertel 6587:            chomp;
1.403     www      6588:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  6589: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      6590: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6591:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6592: 	   $domaindescription{$domain}=$domain_description;
                   6593: 	   $domain_lang_def{$domain}=$def_lang;
                   6594: 	   $domain_city{$domain}=$city;
                   6595: 	   $domain_longi{$domain}=$longi;
                   6596: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  6597:            $domain_primary{$domain}=$primary;
1.403     www      6598: 
1.448     albertel 6599:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6600: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6601: 	}
1.327     albertel 6602:     }
1.448     albertel 6603:     close ($fh);
1.327     albertel 6604: }
                   6605: 
                   6606: 
1.1       albertel 6607: # ------------------------------------------------------------- Read hosts file
                   6608: {
1.448     albertel 6609:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6610: 
                   6611:     while (my $configline=<$config>) {
1.303     matthew  6612:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6613:        chomp($configline);
1.595     albertel 6614:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6615:        $name=~s/\s//g;
1.595     albertel 6616:        if ($id && $domain && $role && $name) {
1.252     albertel 6617: 	 $hostname{$id}=$name;
                   6618: 	 $hostdom{$id}=$domain;
                   6619: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6620:        }
1.1       albertel 6621:     }
1.448     albertel 6622:     close($config);
1.619     albertel 6623:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 6624:     #&get_iphost();
1.1       albertel 6625: }
                   6626: 
1.598     albertel 6627: sub get_iphost {
                   6628:     if (%iphost) { return %iphost; }
1.653     albertel 6629:     my %name_to_ip;
1.598     albertel 6630:     foreach my $id (keys(%hostname)) {
                   6631: 	my $name=$hostname{$id};
1.653     albertel 6632: 	my $ip;
                   6633: 	if (!exists($name_to_ip{$name})) {
                   6634: 	    $ip = gethostbyname($name);
                   6635: 	    if (!$ip || length($ip) ne 4) {
                   6636: 		&logthis("Skipping host $id name $name no IP found\n");
                   6637: 		next;
                   6638: 	    }
                   6639: 	    $ip=inet_ntoa($ip);
                   6640: 	    $name_to_ip{$name} = $ip;
                   6641: 	} else {
                   6642: 	    $ip = $name_to_ip{$name};
1.598     albertel 6643: 	}
                   6644: 	push(@{$iphost{$ip}},$id);
                   6645:     }
                   6646:     return %iphost;
                   6647: }
                   6648: 
1.1       albertel 6649: # ------------------------------------------------------ Read spare server file
                   6650: {
1.448     albertel 6651:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 6652: 
                   6653:     while (my $configline=<$config>) {
                   6654:        chomp($configline);
1.284     matthew  6655:        if ($configline) {
1.1       albertel 6656:           $spareid{$configline}=1;
                   6657:        }
                   6658:     }
1.448     albertel 6659:     close($config);
1.1       albertel 6660: }
1.11      www      6661: # ------------------------------------------------------------ Read permissions
                   6662: {
1.448     albertel 6663:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      6664: 
                   6665:     while (my $configline=<$config>) {
1.448     albertel 6666: 	chomp($configline);
                   6667: 	if ($configline) {
                   6668: 	    my ($role,$perm)=split(/ /,$configline);
                   6669: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   6670: 	}
1.11      www      6671:     }
1.448     albertel 6672:     close($config);
1.11      www      6673: }
                   6674: 
                   6675: # -------------------------------------------- Read plain texts for permissions
                   6676: {
1.448     albertel 6677:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      6678: 
                   6679:     while (my $configline=<$config>) {
1.448     albertel 6680: 	chomp($configline);
                   6681: 	if ($configline) {
                   6682: 	    my ($short,$plain)=split(/:/,$configline);
                   6683: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   6684: 	}
1.135     www      6685:     }
1.448     albertel 6686:     close($config);
1.135     www      6687: }
                   6688: 
                   6689: # ---------------------------------------------------------- Read package table
                   6690: {
1.448     albertel 6691:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      6692: 
                   6693:     while (my $configline=<$config>) {
1.483     albertel 6694: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 6695: 	chomp($configline);
                   6696: 	my ($short,$plain)=split(/:/,$configline);
                   6697: 	my ($pack,$name)=split(/\&/,$short);
                   6698: 	if ($plain ne '') {
                   6699: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   6700: 	    $packagetab{$short}=$plain; 
                   6701: 	}
1.11      www      6702:     }
1.448     albertel 6703:     close($config);
1.329     matthew  6704: }
                   6705: 
                   6706: # ------------- set up temporary directory
                   6707: {
                   6708:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   6709: 
1.11      www      6710: }
                   6711: 
1.599     albertel 6712: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      6713: 
1.281     www      6714: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      6715: $dumpcount=0;
1.22      www      6716: 
1.163     harris41 6717: &logtouch();
1.672     albertel 6718: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      6719: $readit=1;
1.564     albertel 6720:     {
                   6721: 	use integer;
                   6722: 	my $test=(2**32)+1;
1.568     albertel 6723: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 6724: 	&logthis(" Detected 64bit platform ($_64bit)");
                   6725:     }
1.195     www      6726: }
1.1       albertel 6727: }
1.179     www      6728: 
1.1       albertel 6729: 1;
1.191     harris41 6730: __END__
                   6731: 
1.243     albertel 6732: =pod
                   6733: 
1.191     harris41 6734: =head1 NAME
                   6735: 
1.243     albertel 6736: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 6737: 
                   6738: =head1 SYNOPSIS
                   6739: 
1.243     albertel 6740: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 6741: 
                   6742:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   6743: 
1.243     albertel 6744: Common parameters:
                   6745: 
                   6746: =over 4
                   6747: 
                   6748: =item *
                   6749: 
                   6750: $uname : an internal username (if $cname expecting a course Id specifically)
                   6751: 
                   6752: =item *
                   6753: 
                   6754: $udom : a domain (if $cdom expecting a course's domain specifically)
                   6755: 
                   6756: =item *
                   6757: 
                   6758: $symb : a resource instance identifier
                   6759: 
                   6760: =item *
                   6761: 
                   6762: $namespace : the name of a .db file that contains the data needed or
                   6763: being set.
                   6764: 
                   6765: =back
                   6766: 
1.394     bowersj2 6767: =head1 OVERVIEW
1.191     harris41 6768: 
1.394     bowersj2 6769: lonnet provides subroutines which interact with the
                   6770: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   6771: about classes, users, and resources.
1.243     albertel 6772: 
                   6773: For many of these objects you can also use this to store data about
                   6774: them or modify them in various ways.
1.191     harris41 6775: 
1.394     bowersj2 6776: =head2 Symbs
1.191     harris41 6777: 
1.394     bowersj2 6778: To identify a specific instance of a resource, LON-CAPA uses symbols
                   6779: or "symbs"X<symb>. These identifiers are built from the URL of the
                   6780: map, the resource number of the resource in the map, and the URL of
                   6781: the resource itself. The latter is somewhat redundant, but might help
                   6782: if maps change.
                   6783: 
                   6784: An example is
                   6785: 
                   6786:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   6787: 
                   6788: The respective map entry is
                   6789: 
                   6790:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   6791:   title="Problem 2">
                   6792:  </resource>
                   6793: 
                   6794: Symbs are used by the random number generator, as well as to store and
                   6795: restore data specific to a certain instance of for example a problem.
                   6796: 
                   6797: =head2 Storing And Retrieving Data
                   6798: 
                   6799: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   6800: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   6801: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   6802: is is the non-critical message twin of cstore. These functions are for
                   6803: handlers to store a perl hash to a user's permanent data space in an
                   6804: easy manner, and to retrieve it again on another call. It is expected
                   6805: that a handler would use this once at the beginning to retrieve data,
                   6806: and then again once at the end to send only the new data back.
                   6807: 
                   6808: The data is stored in the user's data directory on the user's
                   6809: homeserver under the ID of the course.
                   6810: 
                   6811: The hash that is returned by restore will have all of the previous
                   6812: value for all of the elements of the hash.
                   6813: 
                   6814: Example:
                   6815: 
                   6816:  #creating a hash
                   6817:  my %hash;
                   6818:  $hash{'foo'}='bar';
                   6819: 
                   6820:  #storing it
                   6821:  &Apache::lonnet::cstore(\%hash);
                   6822: 
                   6823:  #changing a value
                   6824:  $hash{'foo'}='notbar';
                   6825: 
                   6826:  #adding a new value
                   6827:  $hash{'bar'}='foo';
                   6828:  &Apache::lonnet::cstore(\%hash);
                   6829: 
                   6830:  #retrieving the hash
                   6831:  my %history=&Apache::lonnet::restore();
                   6832: 
                   6833:  #print the hash
                   6834:  foreach my $key (sort(keys(%history))) {
                   6835:    print("\%history{$key} = $history{$key}");
                   6836:  }
                   6837: 
                   6838: Will print out:
1.191     harris41 6839: 
1.394     bowersj2 6840:  %history{1:foo} = bar
                   6841:  %history{1:keys} = foo:timestamp
                   6842:  %history{1:timestamp} = 990455579
                   6843:  %history{2:bar} = foo
                   6844:  %history{2:foo} = notbar
                   6845:  %history{2:keys} = foo:bar:timestamp
                   6846:  %history{2:timestamp} = 990455580
                   6847:  %history{bar} = foo
                   6848:  %history{foo} = notbar
                   6849:  %history{timestamp} = 990455580
                   6850:  %history{version} = 2
                   6851: 
                   6852: Note that the special hash entries C<keys>, C<version> and
                   6853: C<timestamp> were added to the hash. C<version> will be equal to the
                   6854: total number of versions of the data that have been stored. The
                   6855: C<timestamp> attribute will be the UNIX time the hash was
                   6856: stored. C<keys> is available in every historical section to list which
                   6857: keys were added or changed at a specific historical revision of a
                   6858: hash.
                   6859: 
                   6860: B<Warning>: do not store the hash that restore returns directly. This
                   6861: will cause a mess since it will restore the historical keys as if the
                   6862: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 6863: 
1.394     bowersj2 6864: Calling convention:
1.191     harris41 6865: 
1.394     bowersj2 6866:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   6867:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 6868: 
1.394     bowersj2 6869: For more detailed information, see lonnet specific documentation.
1.191     harris41 6870: 
1.394     bowersj2 6871: =head1 RETURN MESSAGES
1.191     harris41 6872: 
1.394     bowersj2 6873: =over 4
1.191     harris41 6874: 
1.394     bowersj2 6875: =item * B<con_lost>: unable to contact remote host
1.191     harris41 6876: 
1.394     bowersj2 6877: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   6878: when the connection is brought back up
1.191     harris41 6879: 
1.394     bowersj2 6880: =item * B<con_failed>: unable to contact remote host and unable to save message
                   6881: for later delivery
1.191     harris41 6882: 
1.394     bowersj2 6883: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 6884: 
1.394     bowersj2 6885: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 6886: that was requested
1.191     harris41 6887: 
1.243     albertel 6888: =back
1.191     harris41 6889: 
1.243     albertel 6890: =head1 PUBLIC SUBROUTINES
1.191     harris41 6891: 
1.243     albertel 6892: =head2 Session Environment Functions
1.191     harris41 6893: 
1.243     albertel 6894: =over 4
1.191     harris41 6895: 
1.394     bowersj2 6896: =item * 
                   6897: X<appenv()>
                   6898: B<appenv(%hash)>: the value of %hash is written to
                   6899: the user envirnoment file, and will be restored for each access this
1.620     albertel 6900: user makes during this session, also modifies the %env for the current
1.394     bowersj2 6901: process
1.191     harris41 6902: 
                   6903: =item *
1.394     bowersj2 6904: X<delenv()>
                   6905: B<delenv($regexp)>: removes all items from the session
                   6906: environment file that matches the regular expression in $regexp. The
1.620     albertel 6907: values are also delted from the current processes %env.
1.191     harris41 6908: 
1.243     albertel 6909: =back
                   6910: 
                   6911: =head2 User Information
1.191     harris41 6912: 
1.243     albertel 6913: =over 4
1.191     harris41 6914: 
                   6915: =item *
1.394     bowersj2 6916: X<queryauthenticate()>
                   6917: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 6918: authentication scheme
                   6919: 
                   6920: =item *
1.394     bowersj2 6921: X<authenticate()>
                   6922: B<authenticate($uname,$upass,$udom)>: try to
                   6923: authenticate user from domain's lib servers (first use the current
                   6924: one). C<$upass> should be the users password.
1.191     harris41 6925: 
                   6926: =item *
1.394     bowersj2 6927: X<homeserver()>
                   6928: B<homeserver($uname,$udom)>: find the server which has
                   6929: the user's directory and files (there must be only one), this caches
                   6930: the answer, and also caches if there is a borken connection.
1.191     harris41 6931: 
                   6932: =item *
1.394     bowersj2 6933: X<idget()>
                   6934: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   6935: (IDs are a unique resource in a domain, there must be only 1 ID per
                   6936: username, and only 1 username per ID in a specific domain) (returns
                   6937: hash: id=>name,id=>name)
1.191     harris41 6938: 
                   6939: =item *
1.394     bowersj2 6940: X<idrget()>
                   6941: B<idrget($udom,@unames)>: find the IDs behind a list of
                   6942: usernames (returns hash: name=>id,name=>id)
1.191     harris41 6943: 
                   6944: =item *
1.394     bowersj2 6945: X<idput()>
                   6946: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 6947: 
                   6948: =item *
1.394     bowersj2 6949: X<rolesinit()>
                   6950: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 6951: 
                   6952: =item *
1.551     albertel 6953: X<getsection()>
                   6954: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 6955: course $cname, return section name/number or '' for "not in course"
                   6956: and '-1' for "no section"
                   6957: 
                   6958: =item *
1.394     bowersj2 6959: X<userenvironment()>
                   6960: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 6961: passed in @what from the requested user's environment, returns a hash
                   6962: 
                   6963: =back
                   6964: 
                   6965: =head2 User Roles
                   6966: 
                   6967: =over 4
                   6968: 
                   6969: =item *
                   6970: 
                   6971: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   6972: actions
                   6973:  F: full access
                   6974:  U,I,K: authentication modes (cxx only)
                   6975:  '': forbidden
                   6976:  1: user needs to choose course
                   6977:  2: browse allowed
                   6978: 
                   6979: =item *
                   6980: 
                   6981: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   6982: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   6983: and course level
                   6984: 
                   6985: =item *
                   6986: 
                   6987: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   6988: explanation of a user role term
                   6989: 
                   6990: =back
                   6991: 
                   6992: =head2 User Modification
                   6993: 
                   6994: =over 4
                   6995: 
                   6996: =item *
                   6997: 
                   6998: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   6999: user for the level given by URL.  Optional start and end dates (leave empty
                   7000: string or zero for "no date")
1.191     harris41 7001: 
                   7002: =item *
                   7003: 
1.243     albertel 7004: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7005: change a users, password, possible return values are: ok,
                   7006: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7007: refused
1.191     harris41 7008: 
                   7009: =item *
                   7010: 
1.243     albertel 7011: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7012: 
                   7013: =item *
                   7014: 
1.243     albertel 7015: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7016: modify user
1.191     harris41 7017: 
                   7018: =item *
                   7019: 
1.286     matthew  7020: modifystudent
                   7021: 
                   7022: modify a students enrollment and identification information.
                   7023: The course id is resolved based on the current users environment.  
                   7024: This means the envoking user must be a course coordinator or otherwise
                   7025: associated with a course.
                   7026: 
1.297     matthew  7027: This call is essentially a wrapper for lonnet::modifyuser and
                   7028: lonnet::modify_student_enrollment
1.286     matthew  7029: 
                   7030: Inputs: 
                   7031: 
                   7032: =over 4
                   7033: 
                   7034: =item B<$udom> Students loncapa domain
                   7035: 
                   7036: =item B<$uname> Students loncapa login name
                   7037: 
                   7038: =item B<$uid> Students id/student number
                   7039: 
                   7040: =item B<$umode> Students authentication mode
                   7041: 
                   7042: =item B<$upass> Students password
                   7043: 
                   7044: =item B<$first> Students first name
                   7045: 
                   7046: =item B<$middle> Students middle name
                   7047: 
                   7048: =item B<$last> Students last name
                   7049: 
                   7050: =item B<$gene> Students generation
                   7051: 
                   7052: =item B<$usec> Students section in course
                   7053: 
                   7054: =item B<$end> Unix time of the roles expiration
                   7055: 
                   7056: =item B<$start> Unix time of the roles start date
                   7057: 
                   7058: =item B<$forceid> If defined, allow $uid to be changed
                   7059: 
                   7060: =item B<$desiredhome> server to use as home server for student
                   7061: 
                   7062: =back
1.297     matthew  7063: 
                   7064: =item *
                   7065: 
                   7066: modify_student_enrollment
                   7067: 
                   7068: Change a students enrollment status in a class.  The environment variable
                   7069: 'role.request.course' must be defined for this function to proceed.
                   7070: 
                   7071: Inputs:
                   7072: 
                   7073: =over 4
                   7074: 
                   7075: =item $udom, students domain
                   7076: 
                   7077: =item $uname, students name
                   7078: 
                   7079: =item $uid, students user id
                   7080: 
                   7081: =item $first, students first name
                   7082: 
                   7083: =item $middle
                   7084: 
                   7085: =item $last
                   7086: 
                   7087: =item $gene
                   7088: 
                   7089: =item $usec
                   7090: 
                   7091: =item $end
                   7092: 
                   7093: =item $start
                   7094: 
                   7095: =back
                   7096: 
1.191     harris41 7097: 
                   7098: =item *
                   7099: 
1.243     albertel 7100: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7101: custom role; give a custom role to a user for the level given by URL.  Specify
                   7102: name and domain of role author, and role name
1.191     harris41 7103: 
                   7104: =item *
                   7105: 
1.243     albertel 7106: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7107: 
                   7108: =item *
                   7109: 
1.243     albertel 7110: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7111: 
                   7112: =back
                   7113: 
                   7114: =head2 Course Infomation
                   7115: 
                   7116: =over 4
1.191     harris41 7117: 
                   7118: =item *
                   7119: 
1.631     albertel 7120: coursedescription($courseid) : returns a hash of information about the
                   7121: specified course id, including all environment settings for the
                   7122: course, the description of the course will be in the hash under the
                   7123: key 'description'
1.191     harris41 7124: 
                   7125: =item *
                   7126: 
1.624     albertel 7127: resdata($name,$domain,$type,@which) : request for current parameter
                   7128: setting for a specific $type, where $type is either 'course' or 'user',
                   7129: @what should be a list of parameters to ask about. This routine caches
                   7130: answers for 5 minutes.
1.243     albertel 7131: 
                   7132: =back
                   7133: 
                   7134: =head2 Course Modification
                   7135: 
                   7136: =over 4
1.191     harris41 7137: 
                   7138: =item *
                   7139: 
1.243     albertel 7140: writecoursepref($courseid,%prefs) : write preferences (environment
                   7141: database) for a course
1.191     harris41 7142: 
                   7143: =item *
                   7144: 
1.243     albertel 7145: createcourse($udom,$description,$url) : make/modify course
                   7146: 
                   7147: =back
                   7148: 
                   7149: =head2 Resource Subroutines
                   7150: 
                   7151: =over 4
1.191     harris41 7152: 
                   7153: =item *
                   7154: 
1.243     albertel 7155: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7156: 
                   7157: =item *
                   7158: 
1.243     albertel 7159: repcopy($filename) : subscribes to the requested file, and attempts to
                   7160: replicate from the owning library server, Might return
1.607     raeburn  7161: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7162: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7163: resource. Expects the local filesystem pathname
                   7164: (/home/httpd/html/res/....)
                   7165: 
                   7166: =back
                   7167: 
                   7168: =head2 Resource Information
                   7169: 
                   7170: =over 4
1.191     harris41 7171: 
                   7172: =item *
                   7173: 
1.243     albertel 7174: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7175: a vairety of different possible values, $varname should be a request
                   7176: string, and the other parameters can be used to specify who and what
                   7177: one is asking about.
                   7178: 
                   7179: Possible values for $varname are environment.lastname (or other item
                   7180: from the envirnment hash), user.name (or someother aspect about the
                   7181: user), resource.0.maxtries (or some other part and parameter of a
                   7182: resource)
1.204     albertel 7183: 
                   7184: =item *
                   7185: 
1.243     albertel 7186: directcondval($number) : get current value of a condition; reads from a state
                   7187: string
1.204     albertel 7188: 
                   7189: =item *
                   7190: 
1.243     albertel 7191: condval($condidx) : value of condition index based on state
1.204     albertel 7192: 
                   7193: =item *
                   7194: 
1.243     albertel 7195: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7196: resource's metadata, $what should be either a specific key, or either
                   7197: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7198: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7199: 
                   7200: this function automatically caches all requests
1.191     harris41 7201: 
                   7202: =item *
                   7203: 
1.243     albertel 7204: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7205: network of library servers; returns file handle of where SQL and regex results
                   7206: will be stored for query
1.191     harris41 7207: 
                   7208: =item *
                   7209: 
1.243     albertel 7210: symbread($filename) : return symbolic list entry (filename argument optional);
                   7211: returns the data handle
1.191     harris41 7212: 
                   7213: =item *
                   7214: 
1.243     albertel 7215: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7216: a possible symb for the URL in $thisfn, and if is an encryypted
                   7217: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7218: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7219: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7220: 
1.191     harris41 7221: 
                   7222: =item *
                   7223: 
1.243     albertel 7224: symbclean($symb) : removes versions numbers from a symb, returns the
                   7225: cleaned symb
1.191     harris41 7226: 
                   7227: =item *
                   7228: 
1.243     albertel 7229: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7230: course map, user must be in a course for it to work.
1.191     harris41 7231: 
                   7232: =item *
                   7233: 
1.243     albertel 7234: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7235: 
                   7236: =item *
                   7237: 
1.243     albertel 7238: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7239: a random seed, all arguments are optional, if they aren't sent it uses the
                   7240: environment to derive them. Note: if symb isn't sent and it can't get one
                   7241: from &symbread it will use the current time as its return value
1.191     harris41 7242: 
                   7243: =item *
                   7244: 
1.243     albertel 7245: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7246: unfakeable, receipt
1.191     harris41 7247: 
                   7248: =item *
                   7249: 
1.620     albertel 7250: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7251: 
                   7252: =item *
                   7253: 
1.243     albertel 7254: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7255: 
                   7256: =item *
                   7257: 
1.243     albertel 7258: 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 7259: 
                   7260: =item *
                   7261: 
1.243     albertel 7262: 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 7263: 
                   7264: =item *
                   7265: 
1.243     albertel 7266: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7267: 
                   7268: =item *
                   7269: 
1.243     albertel 7270: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7271: forcing spreadsheet to reevaluate the resource scores next time.
                   7272: 
                   7273: =back
                   7274: 
                   7275: =head2 Storing/Retreiving Data
                   7276: 
                   7277: =over 4
1.191     harris41 7278: 
                   7279: =item *
                   7280: 
1.243     albertel 7281: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7282: for this url; hashref needs to be given and should be a \%hashname; the
                   7283: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7284: be derived from the env
1.191     harris41 7285: 
                   7286: =item *
                   7287: 
1.243     albertel 7288: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7289: uses critical subroutine
1.191     harris41 7290: 
                   7291: =item *
                   7292: 
1.243     albertel 7293: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7294: all args are optional
1.191     harris41 7295: 
                   7296: =item *
                   7297: 
1.717     albertel 7298: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7299: dumps the complete (or key matching regexp) namespace into a hash
                   7300: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7301: normally &store()ed into
                   7302: 
                   7303: $range should be either an integer '100' (give me the first 100
                   7304:                                            matching records)
                   7305:               or be  two integers sperated by a - with no spaces
                   7306:                  '30-50' (give me the 30th through the 50th matching
                   7307:                           records)
                   7308: 
                   7309: 
                   7310: =item *
                   7311: 
                   7312: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7313: replaces a &store() version of data with a replacement set of data
                   7314: for a particular resource in a namespace passed in the $storehash hash 
                   7315: reference
                   7316: 
                   7317: =item *
                   7318: 
1.243     albertel 7319: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7320: works very similar to store/cstore, but all data is stored in a
                   7321: temporary location and can be reset using tmpreset, $storehash should
                   7322: be a hash reference, returns nothing on success
1.191     harris41 7323: 
                   7324: =item *
                   7325: 
1.243     albertel 7326: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7327: similar to restore, but all data is stored in a temporary location and
                   7328: can be reset using tmpreset. Returns a hash of values on success,
                   7329: error string otherwise.
1.191     harris41 7330: 
                   7331: =item *
                   7332: 
1.243     albertel 7333: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7334: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7335: 
                   7336: =item *
                   7337: 
1.243     albertel 7338: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7339: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7340: 
                   7341: =item *
                   7342: 
1.243     albertel 7343: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7344: namesp ($udom and $uname are optional)
1.191     harris41 7345: 
                   7346: =item *
                   7347: 
1.702     albertel 7348: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7349: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7350: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7351: 
1.702     albertel 7352: $range should be either an integer '100' (give me the first 100
                   7353:                                            matching records)
                   7354:               or be  two integers sperated by a - with no spaces
                   7355:                  '30-50' (give me the 30th through the 50th matching
                   7356:                           records)
1.449     matthew  7357: =item *
                   7358: 
                   7359: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7360: $store can be a scalar, an array reference, or if the amount to be 
                   7361: incremented is > 1, a hash reference.
                   7362: 
                   7363: ($udom and $uname are optional)
1.191     harris41 7364: 
                   7365: =item *
                   7366: 
1.243     albertel 7367: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7368: ($udom and $uname are optional)
1.191     harris41 7369: 
                   7370: =item *
                   7371: 
1.243     albertel 7372: cput($namespace,$storehash,$udom,$uname) : critical put
                   7373: ($udom and $uname are optional)
1.191     harris41 7374: 
                   7375: =item *
                   7376: 
1.243     albertel 7377: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7378: reference filled in from namesp (encrypts the return communication)
                   7379: ($udom and $uname are optional)
1.191     harris41 7380: 
                   7381: =item *
                   7382: 
1.243     albertel 7383: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7384: critical subroutine
                   7385: 
                   7386: =back
                   7387: 
                   7388: =head2 Network Status Functions
                   7389: 
                   7390: =over 4
1.191     harris41 7391: 
                   7392: =item *
                   7393: 
                   7394: dirlist($uri) : return directory list based on URI
                   7395: 
                   7396: =item *
                   7397: 
1.243     albertel 7398: spareserver() : find server with least workload from spare.tab
                   7399: 
                   7400: =back
                   7401: 
                   7402: =head2 Apache Request
                   7403: 
                   7404: =over 4
1.191     harris41 7405: 
                   7406: =item *
                   7407: 
1.243     albertel 7408: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7409: localhost, posts hash
                   7410: 
                   7411: =back
                   7412: 
                   7413: =head2 Data to String to Data
                   7414: 
                   7415: =over 4
1.191     harris41 7416: 
                   7417: =item *
                   7418: 
1.243     albertel 7419: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7420: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7421: 
                   7422: =item *
                   7423: 
1.243     albertel 7424: hashref2str($hashref) : convert a hashref into a string complete with
                   7425: escaping and '=' and '&' separators, supports elements that are
                   7426: arrayrefs and hashrefs
1.191     harris41 7427: 
                   7428: =item *
                   7429: 
1.243     albertel 7430: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7431: with escaping and '&' separators, supports elements that are arrayrefs
                   7432: and hashrefs
1.191     harris41 7433: 
                   7434: =item *
                   7435: 
1.243     albertel 7436: str2hash($string) : convert string to hash using unescaping and
                   7437: splitting on '=' and '&', supports elements that are arrayrefs and
                   7438: hashrefs
1.191     harris41 7439: 
                   7440: =item *
                   7441: 
1.243     albertel 7442: str2array($string) : convert string to hash using unescaping and
                   7443: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7444: 
                   7445: =back
                   7446: 
                   7447: =head2 Logging Routines
                   7448: 
                   7449: =over 4
                   7450: 
                   7451: These routines allow one to make log messages in the lonnet.log and
                   7452: lonnet.perm logfiles.
1.191     harris41 7453: 
                   7454: =item *
                   7455: 
1.243     albertel 7456: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 7457: 
                   7458: =item *
                   7459: 
1.243     albertel 7460: logthis() : append message to the normal lonnet.log file, it gets
                   7461: preiodically rolled over and deleted.
1.191     harris41 7462: 
                   7463: =item *
                   7464: 
1.243     albertel 7465: logperm() : append a permanent message to lonnet.perm.log, this log
                   7466: file never gets deleted by any automated portion of the system, only
                   7467: messages of critical importance should go in here.
                   7468: 
                   7469: =back
                   7470: 
                   7471: =head2 General File Helper Routines
                   7472: 
                   7473: =over 4
1.191     harris41 7474: 
                   7475: =item *
                   7476: 
1.481     raeburn  7477: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7478: (a) files in /uploaded
                   7479:   (i) If a local copy of the file exists - 
                   7480:       compares modification date of local copy with last-modified date for 
                   7481:       definitive version stored on home server for course. If local copy is 
                   7482:       stale, requests a new version from the home server and stores it. 
                   7483:       If the original has been removed from the home server, then local copy 
                   7484:       is unlinked.
                   7485:   (ii) If local copy does not exist -
                   7486:       requests the file from the home server and stores it. 
                   7487:   
                   7488:   If $caller is 'uploadrep':  
                   7489:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7490:     for request for files originally uploaded via DOCS. 
                   7491:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7492:   
                   7493:   Otherwise:
                   7494:      This indicates a call from the content generation phase of the request.
                   7495:      -  returns the entire contents of the file or -1.
                   7496:      
                   7497: (b) files in /res
                   7498:    - returns the entire contents of a file or -1; 
                   7499:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7500: 
1.712     albertel 7501: 
                   7502: =item *
                   7503: 
                   7504: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   7505:                   reference
                   7506: 
                   7507: returns either a stat() list of data about the file or an empty list
                   7508: if the file doesn't exist or couldn't find out about it (connection
                   7509: problems or user unknown)
                   7510: 
1.191     harris41 7511: =item *
                   7512: 
1.243     albertel 7513: filelocation($dir,$file) : returns file system location of a file
                   7514: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7515: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7516: and a file of ../bob will become /a/bob)
1.191     harris41 7517: 
                   7518: =item *
                   7519: 
                   7520: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7521: filelocation except for hrefs
                   7522: 
                   7523: =item *
                   7524: 
                   7525: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7526: 
1.243     albertel 7527: =back
                   7528: 
1.608     albertel 7529: =head2 Usererfile file routines (/uploaded*)
                   7530: 
                   7531: =over 4
                   7532: 
                   7533: =item *
                   7534: 
                   7535: userfileupload(): main rotine for putting a file in a user or course's
                   7536:                   filespace, arguments are,
                   7537: 
1.620     albertel 7538:  formname - required - this is the name of the element in $env where the
1.608     albertel 7539:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7540:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7541:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7542:  coursedoc - if true, store the file in the course of the active role
                   7543:              of the current user
                   7544:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7545:          if undefined, it will be placed in "unknown"
                   7546: 
                   7547:  (This routine calls clean_filename() to remove any dangerous
                   7548:  characters from the filename, and then calls finuserfileupload() to
                   7549:  complete the transaction)
                   7550: 
                   7551:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7552:  and /adm/notfound.html if unsuccessful
                   7553: 
                   7554: =item *
                   7555: 
                   7556: clean_filename(): routine for cleaing a filename up for storage in
                   7557:                  userfile space, argument is:
                   7558: 
                   7559:  filename - proposed filename
                   7560: 
                   7561: returns: the new clean filename
                   7562: 
                   7563: =item *
                   7564: 
                   7565: finishuserfileupload(): routine that creaes and sends the file to
                   7566: userspace, probably shouldn't be called directly
                   7567: 
                   7568:   docuname: username or courseid of destination for the file
                   7569:   docudom: domain of user/course of destination for the file
                   7570:   formname: same as for userfileupload()
                   7571:   fname: filename (inculding subdirectories) for the file
                   7572: 
                   7573:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7574:  and /adm/notfound.html if unsuccessful
                   7575: 
                   7576: =item *
                   7577: 
                   7578: renameuserfile(): renames an existing userfile to a new name
                   7579: 
                   7580:   Args:
                   7581:    docuname: username or courseid of destination for the file
                   7582:    docudom: domain of user/course of destination for the file
                   7583:    old: current file name (including any subdirs under userfiles)
                   7584:    new: desired file name (including any subdirs under userfiles)
                   7585: 
                   7586: =item *
                   7587: 
                   7588: mkdiruserfile(): creates a directory is a userfiles dir
                   7589: 
                   7590:   Args:
                   7591:    docuname: username or courseid of destination for the file
                   7592:    docudom: domain of user/course of destination for the file
                   7593:    dir: dir to create (including any subdirs under userfiles)
                   7594: 
                   7595: =item *
                   7596: 
                   7597: removeuserfile(): removes a file that exists in userfiles
                   7598: 
                   7599:   Args:
                   7600:    docuname: username or courseid of destination for the file
                   7601:    docudom: domain of user/course of destination for the file
                   7602:    fname: filname to delete (including any subdirs under userfiles)
                   7603: 
                   7604: =item *
                   7605: 
                   7606: removeuploadedurl(): convience function for removeuserfile()
                   7607: 
                   7608:   Args:
                   7609:    url:  a full /uploaded/... url to delete
                   7610: 
                   7611: =back
                   7612: 
1.243     albertel 7613: =head2 HTTP Helper Routines
                   7614: 
                   7615: =over 4
                   7616: 
1.191     harris41 7617: =item *
                   7618: 
                   7619: escape() : unpack non-word characters into CGI-compatible hex codes
                   7620: 
                   7621: =item *
                   7622: 
                   7623: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   7624: 
1.243     albertel 7625: =back
                   7626: 
                   7627: =head1 PRIVATE SUBROUTINES
                   7628: 
                   7629: =head2 Underlying communication routines (Shouldn't call)
                   7630: 
                   7631: =over 4
                   7632: 
                   7633: =item *
                   7634: 
                   7635: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   7636: 
                   7637: =item *
                   7638: 
                   7639: reply() : uses subreply to send a message to remote machine, logs all failures
                   7640: 
                   7641: =item *
                   7642: 
                   7643: critical() : passes a critical message to another server; if cannot
                   7644: get through then place message in connection buffer directory and
                   7645: returns con_delayed, if incapable of saving message, returns
                   7646: con_failed
                   7647: 
                   7648: =item *
                   7649: 
                   7650: reconlonc() : tries to reconnect lonc client processes.
                   7651: 
                   7652: =back
                   7653: 
                   7654: =head2 Resource Access Logging
                   7655: 
                   7656: =over 4
                   7657: 
                   7658: =item *
                   7659: 
                   7660: flushcourselogs() : flush (save) buffer logs and access logs
                   7661: 
                   7662: =item *
                   7663: 
                   7664: courselog($what) : save message for course in hash
                   7665: 
                   7666: =item *
                   7667: 
                   7668: courseacclog($what) : save message for course using &courselog().  Perform
                   7669: special processing for specific resource types (problems, exams, quizzes, etc).
                   7670: 
1.191     harris41 7671: =item *
                   7672: 
                   7673: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   7674: as a PerlChildExitHandler
1.243     albertel 7675: 
                   7676: =back
                   7677: 
                   7678: =head2 Other
                   7679: 
                   7680: =over 4
                   7681: 
                   7682: =item *
                   7683: 
                   7684: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 7685: 
                   7686: =back
                   7687: 
                   7688: =cut

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