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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.754     albertel    4: # $Id: lonnet.pm,v 1.753 2006/06/22 13:16:09 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.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   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;
1.740     www        55: use lib '/home/httpd/lib/perl';
                     56: use LONCAPA;
                     57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755   ! albertel  284: # ------------------------------------------- check if return value is an error
        !           285: 
        !           286: sub error {
        !           287:     my ($result) = @_;
        !           288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) )/) {
        !           289: 	if ($2 == 2) { return undef; }
        !           290: 	return $1;
        !           291:     }
        !           292:     &logthis("accepting $result");
        !           293:     return undef;
        !           294: }
        !           295: 
1.374     www       296: # ------------------------------------------- Transfer profile into environment
                    297: 
                    298: sub transfer_profile_to_env {
                    299:     my ($lonidsdir,$handle)=@_;
1.720     albertel  300:     if (!defined($lonidsdir)) {
                    301: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    302:     }
                    303:     if (!defined($handle)) {
                    304:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    305:     }
                    306: 
1.374     www       307:     my @profile;
                    308:     {
1.448     albertel  309: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       310: 	flock($idf,LOCK_SH);
                    311: 	@profile=<$idf>;
1.448     albertel  312: 	close($idf);
1.374     www       313:     }
                    314:     my $envi;
1.433     matthew   315:     my %Remove;
1.374     www       316:     for ($envi=0;$envi<=$#profile;$envi++) {
                    317: 	chomp($profile[$envi]);
1.690     albertel  318: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  319: 	$envname=&unescape($envname);
                    320: 	$envvalue=&unescape($envvalue);
1.619     albertel  321: 	$env{$envname} = $envvalue;
1.433     matthew   322:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    323:             if ($time < time-300) {
                    324:                 $Remove{$key}++;
                    325:             }
                    326:         }
                    327:     }
1.619     albertel  328:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   329:     foreach my $expired_key (keys(%Remove)) {
                    330:         &delenv($expired_key);
1.374     www       331:     }
1.1       albertel  332: }
                    333: 
1.5       www       334: # ---------------------------------------------------------- Append Environment
                    335: 
                    336: sub appenv {
1.6       www       337:     my %newenv=@_;
1.692     albertel  338:     foreach my $key (keys(%newenv)) {
                    339: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  340:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  341:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       342:                 .'</font>');
1.692     albertel  343: 	    delete($newenv{$key});
1.35      www       344:         } else {
1.692     albertel  345:             $env{$key}=$newenv{$key};
1.35      www       346:         }
1.191     harris41  347:     }
1.95      www       348: 
                    349:     my $lockfh;
1.620     albertel  350:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  351: 	return 'error: '.$!;
1.95      www       352:     }
                    353:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  354:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       355:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  356:          close($lockfh);
1.95      www       357:          return 'error: '.$!;
                    358:     }
                    359: 
1.6       www       360:     my @oldenv;
                    361:     {
1.448     albertel  362: 	my $fh;
1.620     albertel  363: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  364: 	    return 'error: '.$!;
                    365: 	}
                    366: 	@oldenv=<$fh>;
                    367: 	close($fh);
1.6       www       368:     }
                    369:     for (my $i=0; $i<=$#oldenv; $i++) {
                    370:         chomp($oldenv[$i]);
1.9       www       371:         if ($oldenv[$i] ne '') {
1.690     albertel  372: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.726     albertel  373: 	    $name=&unescape($name);
                    374: 	    $value=&unescape($value);
1.448     albertel  375: 	    unless (defined($newenv{$name})) {
                    376: 		$newenv{$name}=$value;
                    377: 	    }
1.9       www       378:         }
1.6       www       379:     }
                    380:     {
1.448     albertel  381: 	my $fh;
1.620     albertel  382: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  383: 	    return 'error';
                    384: 	}
                    385: 	my $newname;
                    386: 	foreach $newname (keys %newenv) {
1.726     albertel  387: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
1.448     albertel  388: 	}
                    389: 	close($fh);
1.56      www       390:     }
1.448     albertel  391: 	
                    392:     close($lockfh);
1.56      www       393:     return 'ok';
                    394: }
                    395: # ----------------------------------------------------- Delete from Environment
                    396: 
                    397: sub delenv {
                    398:     my $delthis=shift;
                    399:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  400:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       401:                 "Attempt to delete from environment ".$delthis);
                    402:         return 'error';
                    403:     }
                    404:     my @oldenv;
                    405:     {
1.448     albertel  406: 	my $fh;
1.620     albertel  407: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  408: 	    return 'error';
                    409: 	}
                    410: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  411: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  412: 		     'Could not obtain shared lock in delenv: '.$!);
                    413: 	    close($fh);
                    414: 	    return 'error: '.$!;
                    415: 	}
                    416: 	@oldenv=<$fh>;
                    417: 	close($fh);
1.56      www       418:     }
                    419:     {
1.448     albertel  420: 	my $fh;
1.620     albertel  421: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  422: 	    return 'error';
                    423: 	}
                    424: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  425: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  426: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    427: 	    close($fh);
                    428: 	    return 'error: '.$!;
                    429: 	}
1.692     albertel  430: 	foreach my $cur_key (@oldenv) {
1.726     albertel  431: 	    my $unescaped_cur_key = &unescape($cur_key);
                    432: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    433:                 my ($key) = split('=',$cur_key,2);
                    434: 		$key = &unescape($key);
1.619     albertel  435:                 delete($env{$key});
1.473     matthew   436:             } else {
1.692     albertel  437:                 print $fh $cur_key; 
1.473     matthew   438:             }
1.448     albertel  439: 	}
                    440: 	close($fh);
1.5       www       441:     }
                    442:     return 'ok';
1.369     albertel  443: }
                    444: 
                    445: # ------------------------------------------ Find out current server userload
                    446: # there is a copy in lond
                    447: sub userload {
                    448:     my $numusers=0;
                    449:     {
                    450: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    451: 	my $filename;
                    452: 	my $curtime=time;
                    453: 	while ($filename=readdir(LONIDS)) {
                    454: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  455: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  456: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  457: 	}
                    458: 	closedir(LONIDS);
                    459:     }
                    460:     my $userloadpercent=0;
                    461:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    462:     if ($maxuserload) {
1.371     albertel  463: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  464:     }
1.372     albertel  465:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  466:     return $userloadpercent;
1.283     www       467: }
                    468: 
                    469: # ------------------------------------------ Fight off request when overloaded
                    470: 
                    471: sub overloaderror {
                    472:     my ($r,$checkserver)=@_;
                    473:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    474:     my $loadavg;
                    475:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  476:        open(my $loadfile,'/proc/loadavg');
1.283     www       477:        $loadavg=<$loadfile>;
                    478:        $loadavg =~ s/\s.*//g;
1.285     matthew   479:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  480:        close($loadfile);
1.283     www       481:     } else {
                    482:        $loadavg=&reply('load',$checkserver);
                    483:     }
1.285     matthew   484:     my $overload=$loadavg-100;
1.283     www       485:     if ($overload>0) {
1.285     matthew   486: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       487:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       488:         return 413;
1.283     www       489:     }    
                    490:     return '';
1.5       www       491: }
1.1       albertel  492: 
                    493: # ------------------------------ Find server with least workload from spare.tab
1.11      www       494: 
1.1       albertel  495: sub spareserver {
1.670     albertel  496:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  497:     my $tryserver;
                    498:     my $spareserver='';
1.370     albertel  499:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    500:     my $lowestserver=$loadpercent > $userloadpercent?
                    501: 	             $loadpercent :  $userloadpercent;
1.670     albertel  502:     foreach $tryserver (keys(%spareid)) {
                    503: 	my $loadans=&reply('load',$tryserver);
                    504: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  505: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    506: 	    next; #didn't get a number from the server
                    507: 	}
                    508: 	my $answer;
                    509: 	if ($loadans =~ /\d/) {
                    510: 	    if ($userloadans =~ /\d/) {
                    511: 		#both are numbers, pick the bigger one
                    512: 		$answer=$loadans > $userloadans?
                    513: 		    $loadans :  $userloadans;
                    514: 	    } else {
                    515: 		$answer = $loadans;
                    516: 	    }
                    517: 	} else {
                    518: 	    $answer = $userloadans;
                    519: 	}
                    520: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  521: 	    if ($want_server_name) {
                    522: 		$spareserver=$tryserver;
                    523: 	    } else {
                    524: 		$spareserver="http://$hostname{$tryserver}";
                    525: 	    }
1.411     albertel  526: 	    $lowestserver=$answer;
                    527: 	}
1.370     albertel  528:     }
1.1       albertel  529:     return $spareserver;
1.202     matthew   530: }
                    531: 
                    532: # --------------------------------------------- Try to change a user's password
                    533: 
                    534: sub changepass {
                    535:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    536:     $currentpass = &escape($currentpass);
                    537:     $newpass     = &escape($newpass);
                    538:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    539: 		       $server);
                    540:     if (! $answer) {
                    541: 	&logthis("No reply on password change request to $server ".
                    542: 		 "by $uname in domain $udom.");
                    543:     } elsif ($answer =~ "^ok") {
                    544:         &logthis("$uname in $udom successfully changed their password ".
                    545: 		 "on $server.");
                    546:     } elsif ($answer =~ "^pwchange_failure") {
                    547: 	&logthis("$uname in $udom was unable to change their password ".
                    548: 		 "on $server.  The action was blocked by either lcpasswd ".
                    549: 		 "or pwchange");
                    550:     } elsif ($answer =~ "^non_authorized") {
                    551:         &logthis("$uname in $udom did not get their password correct when ".
                    552: 		 "attempting to change it on $server.");
                    553:     } elsif ($answer =~ "^auth_mode_error") {
                    554:         &logthis("$uname in $udom attempted to change their password despite ".
                    555: 		 "not being locally or internally authenticated on $server.");
                    556:     } elsif ($answer =~ "^unknown_user") {
                    557:         &logthis("$uname in $udom attempted to change their password ".
                    558: 		 "on $server but were unable to because $server is not ".
                    559: 		 "their home server.");
                    560:     } elsif ($answer =~ "^refused") {
                    561: 	&logthis("$server refused to change $uname in $udom password because ".
                    562: 		 "it was sent an unencrypted request to change the password.");
                    563:     }
                    564:     return $answer;
1.1       albertel  565: }
                    566: 
1.169     harris41  567: # ----------------------- Try to determine user's current authentication scheme
                    568: 
                    569: sub queryauthenticate {
                    570:     my ($uname,$udom)=@_;
1.456     albertel  571:     my $uhome=&homeserver($uname,$udom);
                    572:     if (!$uhome) {
                    573: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    574: 	return 'no_host';
                    575:     }
                    576:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    577:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    578: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  579:     }
1.456     albertel  580:     return $answer;
1.169     harris41  581: }
                    582: 
1.1       albertel  583: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       584: 
1.1       albertel  585: sub authenticate {
                    586:     my ($uname,$upass,$udom)=@_;
1.12      www       587:     $upass=escape($upass);
1.199     www       588:     $uname=~s/\W//g;
1.471     albertel  589:     my $uhome=&homeserver($uname,$udom);
                    590:     if (!$uhome) {
                    591: 	&logthis("User $uname at $udom is unknown in authenticate");
                    592: 	return 'no_host';
1.1       albertel  593:     }
1.471     albertel  594:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    595:     if ($answer eq 'authorized') {
                    596: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    597: 	return $uhome; 
                    598:     }
                    599:     if ($answer eq 'non_authorized') {
                    600: 	&logthis("User $uname at $udom rejected by $uhome");
                    601: 	return 'no_host'; 
1.9       www       602:     }
1.471     albertel  603:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  604:     return 'no_host';
                    605: }
                    606: 
                    607: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       608: 
1.599     albertel  609: my %homecache;
1.1       albertel  610: sub homeserver {
1.230     stredwic  611:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  612:     my $index="$uname:$udom";
1.426     albertel  613: 
1.599     albertel  614:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  615:     my $tryserver;
                    616:     foreach $tryserver (keys %libserv) {
1.230     stredwic  617:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  618: 		 exists($badServerCache{$tryserver}));
1.1       albertel  619: 	if ($hostdom{$tryserver} eq $udom) {
                    620:            my $answer=reply("home:$udom:$uname",$tryserver);
                    621:            if ($answer eq 'found') { 
1.599     albertel  622: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  623:            } elsif ($answer eq 'no_host') {
                    624: 	       $badServerCache{$tryserver}=1;
1.221     matthew   625:            }
1.1       albertel  626:        }
                    627:     }    
                    628:     return 'no_host';
1.70      www       629: }
                    630: 
                    631: # ------------------------------------- Find the usernames behind a list of IDs
                    632: 
                    633: sub idget {
                    634:     my ($udom,@ids)=@_;
                    635:     my %returnhash=();
                    636:     
                    637:     my $tryserver;
                    638:     foreach $tryserver (keys %libserv) {
                    639:        if ($hostdom{$tryserver} eq $udom) {
                    640: 	  my $idlist=join('&',@ids);
                    641:           $idlist=~tr/A-Z/a-z/; 
                    642: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    643:           my @answer=();
1.76      www       644:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       645: 	      @answer=split(/\&/,$reply);
                    646:           }                    ;
                    647:           my $i;
                    648:           for ($i=0;$i<=$#ids;$i++) {
                    649:               if ($answer[$i]) {
                    650: 		  $returnhash{$ids[$i]}=$answer[$i];
                    651:               } 
                    652:           }
                    653:        }
                    654:     }    
                    655:     return %returnhash;
                    656: }
                    657: 
                    658: # ------------------------------------- Find the IDs behind a list of usernames
                    659: 
                    660: sub idrget {
                    661:     my ($udom,@unames)=@_;
                    662:     my %returnhash=();
1.191     harris41  663:     foreach (@unames) {
1.70      www       664:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  665:     }
1.70      www       666:     return %returnhash;
                    667: }
                    668: 
                    669: # ------------------------------- Store away a list of names and associated IDs
                    670: 
                    671: sub idput {
                    672:     my ($udom,%ids)=@_;
                    673:     my %servers=();
1.191     harris41  674:     foreach (keys %ids) {
1.487     albertel  675: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       676:         my $uhom=&homeserver($_,$udom);
                    677:         if ($uhom ne 'no_host') {
                    678:             my $id=&escape($ids{$_});
                    679:             $id=~tr/A-Z/a-z/;
                    680:             my $unam=&escape($_);
                    681: 	    if ($servers{$uhom}) {
                    682: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    683:             } else {
                    684:                 $servers{$uhom}=$id.'='.$unam;
                    685:             }
                    686:         }
1.191     harris41  687:     }
                    688:     foreach (keys %servers) {
1.70      www       689:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  690:     }
1.344     www       691: }
                    692: 
                    693: # --------------------------------------------------- Assign a key to a student
                    694: 
                    695: sub assign_access_key {
1.364     www       696: #
                    697: # a valid key looks like uname:udom#comments
                    698: # comments are being appended
                    699: #
1.498     www       700:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    701:     $kdom=
1.620     albertel  702:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       703:     $knum=
1.620     albertel  704:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       705:     $cdom=
1.620     albertel  706:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       707:     $cnum=
1.620     albertel  708:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    709:     $udom=$env{'user.name'} unless (defined($udom));
                    710:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       711:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       712:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  713:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       714:                                                   # assigned to this person
                    715:                                                   # - this should not happen,
1.345     www       716:                                                   # unless something went wrong
                    717:                                                   # the first time around
                    718: # ready to assign
1.364     www       719:         $logentry=$1.'; '.$logentry;
1.496     www       720:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       721:                                                  $kdom,$knum) eq 'ok') {
1.345     www       722: # key now belongs to user
1.346     www       723: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       724:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    725:                 &appenv('environment.'.$envkey => $ckey);
                    726:                 return 'ok';
                    727:             } else {
                    728:                 return 
                    729:   'error: Count not permanently assign key, will need to be re-entered later.';
                    730: 	    }
                    731:         } else {
                    732:             return 'error: Could not assign key, try again later.';
                    733:         }
1.364     www       734:     } elsif (!$existing{$ckey}) {
1.345     www       735: # the key does not exist
                    736: 	return 'error: The key does not exist';
                    737:     } else {
                    738: # the key is somebody else's
                    739: 	return 'error: The key is already in use';
                    740:     }
1.344     www       741: }
                    742: 
1.364     www       743: # ------------------------------------------ put an additional comment on a key
                    744: 
                    745: sub comment_access_key {
                    746: #
                    747: # a valid key looks like uname:udom#comments
                    748: # comments are being appended
                    749: #
                    750:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    751:     $cdom=
1.620     albertel  752:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       753:     $cnum=
1.620     albertel  754:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       755:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    756:     if ($existing{$ckey}) {
                    757:         $existing{$ckey}.='; '.$logentry;
                    758: # ready to assign
1.367     www       759:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       760:                                                  $cdom,$cnum) eq 'ok') {
                    761: 	    return 'ok';
                    762:         } else {
                    763: 	    return 'error: Count not store comment.';
                    764:         }
                    765:     } else {
                    766: # the key does not exist
                    767: 	return 'error: The key does not exist';
                    768:     }
                    769: }
                    770: 
1.344     www       771: # ------------------------------------------------------ Generate a set of keys
                    772: 
                    773: sub generate_access_keys {
1.364     www       774:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       775:     $cdom=
1.620     albertel  776:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       777:     $cnum=
1.620     albertel  778:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       779:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       780:     unless (($cdom) && ($cnum)) { return 0; }
                    781:     if ($number>10000) { return 0; }
                    782:     sleep(2); # make sure don't get same seed twice
                    783:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    784:     my $total=0;
                    785:     for (my $i=1;$i<=$number;$i++) {
                    786:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    787:                   sprintf("%lx",int(100000*rand)).'-'.
                    788:                   sprintf("%lx",int(100000*rand));
                    789:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    790:        $newkey=~s/0/h/g; # and also 0 and O
                    791:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    792:        if ($existing{$newkey}) {
                    793:            $i--;
                    794:        } else {
1.364     www       795: 	  if (&put('accesskeys',
                    796:               { $newkey => '# generated '.localtime().
1.620     albertel  797:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       798:                            '; '.$logentry },
                    799: 		   $cdom,$cnum) eq 'ok') {
1.344     www       800:               $total++;
                    801: 	  }
                    802:        }
                    803:     }
1.620     albertel  804:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       805:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    806:     return $total;
                    807: }
                    808: 
                    809: # ------------------------------------------------------- Validate an accesskey
                    810: 
                    811: sub validate_access_key {
                    812:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    813:     $cdom=
1.620     albertel  814:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       815:     $cnum=
1.620     albertel  816:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    817:     $udom=$env{'user.domain'} unless (defined($udom));
                    818:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       819:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  820:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       821: }
                    822: 
                    823: # ------------------------------------- Find the section of student in a course
1.652     albertel  824: sub devalidate_getsection_cache {
                    825:     my ($udom,$unam,$courseid)=@_;
                    826:     $courseid=~s/\_/\//g;
                    827:     $courseid=~s/^(\w)/\/$1/;
                    828:     my $hashid="$udom:$unam:$courseid";
                    829:     &devalidate_cache_new('getsection',$hashid);
                    830: }
1.298     matthew   831: 
                    832: sub getsection {
                    833:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  834:     my $cachetime=1800;
1.298     matthew   835:     $courseid=~s/\_/\//g;
                    836:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  837: 
                    838:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  839:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  840:     if (defined($cached)) { return $result; }
                    841: 
1.298     matthew   842:     my %Pending; 
                    843:     my %Expired;
                    844:     #
                    845:     # Each role can either have not started yet (pending), be active, 
                    846:     #    or have expired.
                    847:     #
                    848:     # If there is an active role, we are done.
                    849:     #
                    850:     # If there is more than one role which has not started yet, 
                    851:     #     choose the one which will start sooner
                    852:     # If there is one role which has not started yet, return it.
                    853:     #
                    854:     # If there is more than one expired role, choose the one which ended last.
                    855:     # If there is a role which has expired, return it.
                    856:     #
                    857:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    858:                         &homeserver($unam,$udom)))) {
                    859:         my ($key,$value)=split(/\=/,$_);
                    860:         $key=&unescape($key);
1.479     albertel  861:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   862:         my $section=$1;
                    863:         if ($key eq $courseid.'_st') { $section=''; }
                    864:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    865:         my $now=time;
1.548     albertel  866:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   867:             $Expired{$end}=$section;
                    868:             next;
                    869:         }
1.548     albertel  870:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   871:             $Pending{$start}=$section;
                    872:             next;
                    873:         }
1.599     albertel  874:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   875:     }
                    876:     #
                    877:     # Presumedly there will be few matching roles from the above
                    878:     # loop and the sorting time will be negligible.
                    879:     if (scalar(keys(%Pending))) {
                    880:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  881:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   882:     } 
                    883:     if (scalar(keys(%Expired))) {
                    884:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    885:         my $time = pop(@sorted);
1.599     albertel  886:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   887:     }
1.599     albertel  888:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   889: }
1.70      www       890: 
1.599     albertel  891: sub save_cache {
                    892:     &purge_remembered();
1.722     albertel  893:     #&Apache::loncommon::validate_page();
1.620     albertel  894:     undef(%env);
1.599     albertel  895: }
1.452     albertel  896: 
1.599     albertel  897: my $to_remember=-1;
                    898: my %remembered;
                    899: my %accessed;
                    900: my $kicks=0;
                    901: my $hits=0;
                    902: sub devalidate_cache_new {
                    903:     my ($name,$id,$debug) = @_;
                    904:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    905:     $id=&escape($name.':'.$id);
                    906:     $memcache->delete($id);
                    907:     delete($remembered{$id});
                    908:     delete($accessed{$id});
                    909: }
                    910: 
                    911: sub is_cached_new {
                    912:     my ($name,$id,$debug) = @_;
                    913:     $id=&escape($name.':'.$id);
                    914:     if (exists($remembered{$id})) {
                    915: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    916: 	$accessed{$id}=[&gettimeofday()];
                    917: 	$hits++;
                    918: 	return ($remembered{$id},1);
                    919:     }
                    920:     my $value = $memcache->get($id);
                    921:     if (!(defined($value))) {
                    922: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  923: 	return (undef,undef);
1.416     albertel  924:     }
1.599     albertel  925:     if ($value eq '__undef__') {
                    926: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    927: 	$value=undef;
                    928:     }
                    929:     &make_room($id,$value,$debug);
                    930:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    931:     return ($value,1);
                    932: }
                    933: 
                    934: sub do_cache_new {
                    935:     my ($name,$id,$value,$time,$debug) = @_;
                    936:     $id=&escape($name.':'.$id);
                    937:     my $setvalue=$value;
                    938:     if (!defined($setvalue)) {
                    939: 	$setvalue='__undef__';
                    940:     }
1.623     albertel  941:     if (!defined($time) ) {
                    942: 	$time=600;
                    943:     }
1.599     albertel  944:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  945:     $memcache->set($id,$setvalue,$time);
                    946:     # need to make a copy of $value
                    947:     #&make_room($id,$value,$debug);
1.599     albertel  948:     return $value;
                    949: }
                    950: 
                    951: sub make_room {
                    952:     my ($id,$value,$debug)=@_;
                    953:     $remembered{$id}=$value;
                    954:     if ($to_remember<0) { return; }
                    955:     $accessed{$id}=[&gettimeofday()];
                    956:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    957:     my $to_kick;
                    958:     my $max_time=0;
                    959:     foreach my $other (keys(%accessed)) {
                    960: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    961: 	    $to_kick=$other;
                    962: 	    $max_time=&tv_interval($accessed{$other});
                    963: 	}
                    964:     }
                    965:     delete($remembered{$to_kick});
                    966:     delete($accessed{$to_kick});
                    967:     $kicks++;
                    968:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  969:     return;
                    970: }
                    971: 
1.599     albertel  972: sub purge_remembered {
1.604     albertel  973:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    974:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  975:     undef(%remembered);
                    976:     undef(%accessed);
1.428     albertel  977: }
1.70      www       978: # ------------------------------------- Read an entry from a user's environment
                    979: 
                    980: sub userenvironment {
                    981:     my ($udom,$unam,@what)=@_;
                    982:     my %returnhash=();
                    983:     my @answer=split(/\&/,
                    984:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    985:                       &homeserver($unam,$udom)));
                    986:     my $i;
                    987:     for ($i=0;$i<=$#what;$i++) {
                    988: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    989:     }
                    990:     return %returnhash;
1.1       albertel  991: }
                    992: 
1.617     albertel  993: # ---------------------------------------------------------- Get a studentphoto
                    994: sub studentphoto {
                    995:     my ($udom,$unam,$ext) = @_;
                    996:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   997:     if (defined($env{'request.course.id'})) {
1.708     raeburn   998:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   999:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1000:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1001:             } else {
                   1002:                 my ($result,$perm_reqd)=
1.707     albertel 1003: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1004:                 if ($result eq 'ok') {
                   1005:                     if (!($perm_reqd eq 'yes')) {
                   1006:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1007:                     }
                   1008:                 }
                   1009:             }
                   1010:         }
                   1011:     } else {
                   1012:         my ($result,$perm_reqd) = 
1.707     albertel 1013: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1014:         if ($result eq 'ok') {
                   1015:             if (!($perm_reqd eq 'yes')) {
                   1016:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1017:             }
                   1018:         }
                   1019:     }
                   1020:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1021: }
                   1022: 
                   1023: sub retrievestudentphoto {
                   1024:     my ($udom,$unam,$ext,$type) = @_;
                   1025:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1026:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1027:     if ($ret eq 'ok') {
                   1028:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1029:         if ($type eq 'thumbnail') {
                   1030:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1031:         }
                   1032:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1033:         return $tokenurl;
                   1034:     } else {
                   1035:         if ($type eq 'thumbnail') {
                   1036:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1037:         } else { 
                   1038:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1039:         }
1.617     albertel 1040:     }
                   1041: }
                   1042: 
1.263     www      1043: # -------------------------------------------------------------------- New chat
                   1044: 
                   1045: sub chatsend {
1.724     raeburn  1046:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1047:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1048:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1049:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1050:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1051: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1052: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1053: }
                   1054: 
                   1055: # ------------------------------------------ Find current version of a resource
                   1056: 
                   1057: sub getversion {
                   1058:     my $fname=&clutter(shift);
                   1059:     unless ($fname=~/^\/res\//) { return -1; }
                   1060:     return &currentversion(&filelocation('',$fname));
                   1061: }
                   1062: 
                   1063: sub currentversion {
                   1064:     my $fname=shift;
1.599     albertel 1065:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1066:     if (defined($cached)) { return $result; }
1.292     www      1067:     my $author=$fname;
                   1068:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1069:     my ($udom,$uname)=split(/\//,$author);
                   1070:     my $home=homeserver($uname,$udom);
                   1071:     if ($home eq 'no_host') { 
                   1072:         return -1; 
                   1073:     }
                   1074:     my $answer=reply("currentversion:$fname",$home);
                   1075:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1076: 	return -1;
                   1077:     }
1.599     albertel 1078:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1079: }
                   1080: 
1.1       albertel 1081: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1082: 
1.1       albertel 1083: sub subscribe {
                   1084:     my $fname=shift;
1.312     www      1085:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1086:     $fname=~s/[\n\r]//g;
1.1       albertel 1087:     my $author=$fname;
                   1088:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1089:     my ($udom,$uname)=split(/\//,$author);
                   1090:     my $home=homeserver($uname,$udom);
1.335     albertel 1091:     if ($home eq 'no_host') {
                   1092:         return 'not_found';
1.1       albertel 1093:     }
                   1094:     my $answer=reply("sub:$fname",$home);
1.64      www      1095:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1096: 	$answer.=' by '.$home;
                   1097:     }
1.1       albertel 1098:     return $answer;
                   1099: }
                   1100:     
1.8       www      1101: # -------------------------------------------------------------- Replicate file
                   1102: 
                   1103: sub repcopy {
                   1104:     my $filename=shift;
1.23      www      1105:     $filename=~s/\/+/\//g;
1.607     raeburn  1106:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1107:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1108:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1109: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1110: 	return &repcopy_userfile($filename);
                   1111:     }
1.532     albertel 1112:     $filename=~s/[\n\r]//g;
1.8       www      1113:     my $transname="$filename.in.transfer";
1.607     raeburn  1114:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1115:     my $remoteurl=subscribe($filename);
1.64      www      1116:     if ($remoteurl =~ /^con_lost by/) {
                   1117: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1118:            return 'unavailable';
1.8       www      1119:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1120: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1121: 	   return 'not_found';
1.64      www      1122:     } elsif ($remoteurl =~ /^rejected by/) {
                   1123: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1124:            return 'forbidden';
1.20      www      1125:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1126:            return 'ok';
1.8       www      1127:     } else {
1.290     www      1128:         my $author=$filename;
                   1129:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1130:         my ($udom,$uname)=split(/\//,$author);
                   1131:         my $home=homeserver($uname,$udom);
                   1132:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1133:            my @parts=split(/\//,$filename);
                   1134:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1135:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1136:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1137: 	       return 'bad_request';
1.8       www      1138:            }
                   1139:            my $count;
                   1140:            for ($count=5;$count<$#parts;$count++) {
                   1141:                $path.="/$parts[$count]";
                   1142:                if ((-e $path)!=1) {
                   1143: 		   mkdir($path,0777);
                   1144:                }
                   1145:            }
                   1146:            my $ua=new LWP::UserAgent;
                   1147:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1148:            my $response=$ua->request($request,$transname);
                   1149:            if ($response->is_error()) {
                   1150: 	       unlink($transname);
                   1151:                my $message=$response->status_line;
1.672     albertel 1152:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1153:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1154:                return 'unavailable';
1.8       www      1155:            } else {
1.16      www      1156: 	       if ($remoteurl!~/\.meta$/) {
                   1157:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1158:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1159:                   if ($mresponse->is_error()) {
                   1160: 		      unlink($filename.'.meta');
                   1161:                       &logthis(
1.672     albertel 1162:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1163:                   }
                   1164: 	       }
1.8       www      1165:                rename($transname,$filename);
1.607     raeburn  1166:                return 'ok';
1.8       www      1167:            }
1.290     www      1168:        }
1.8       www      1169:     }
1.330     www      1170: }
                   1171: 
                   1172: # ------------------------------------------------ Get server side include body
                   1173: sub ssi_body {
1.381     albertel 1174:     my ($filelink,%form)=@_;
1.606     matthew  1175:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1176:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1177:     }
1.330     www      1178:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1179:                                      &ssi($filelink,%form));
1.565     albertel 1180:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1181:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1182:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1183:     return $output;
1.8       www      1184: }
                   1185: 
1.15      www      1186: # --------------------------------------------------------- Server Side Include
                   1187: 
                   1188: sub ssi {
                   1189: 
1.23      www      1190:     my ($fn,%form)=@_;
1.15      www      1191: 
                   1192:     my $ua=new LWP::UserAgent;
1.23      www      1193:     
                   1194:     my $request;
1.711     albertel 1195: 
                   1196:     $form{'no_update_last_known'}=1;
                   1197: 
1.23      www      1198:     if (%form) {
                   1199:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1200:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1201:     } else {
                   1202:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1203:     }
                   1204: 
1.15      www      1205:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1206:     my $response=$ua->request($request);
                   1207: 
1.324     www      1208:     return $response->content;
                   1209: }
                   1210: 
                   1211: sub externalssi {
                   1212:     my ($url)=@_;
                   1213:     my $ua=new LWP::UserAgent;
                   1214:     my $request=new HTTP::Request('GET',$url);
                   1215:     my $response=$ua->request($request);
1.15      www      1216:     return $response->content;
                   1217: }
1.254     www      1218: 
1.492     albertel 1219: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1220: 
                   1221: sub allowuploaded {
                   1222:     my ($srcurl,$url)=@_;
                   1223:     $url=&clutter(&declutter($url));
                   1224:     my $dir=$url;
                   1225:     $dir=~s/\/[^\/]+$//;
                   1226:     my %httpref=();
                   1227:     my $httpurl=&hreflocation('',$url);
                   1228:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1229:     &Apache::lonnet::appenv(%httpref);
1.254     www      1230: }
1.477     raeburn  1231: 
1.478     albertel 1232: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1233: # input: action, courseID, current domain, intended
1.637     raeburn  1234: #        path to file, source of file, instruction to parse file for objects,
                   1235: #        ref to hash for embedded objects,
                   1236: #        ref to hash for codebase of java objects.
                   1237: #
1.485     raeburn  1238: # output: url to file (if action was uploaddoc), 
                   1239: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1240: #
1.478     albertel 1241: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1242: # course.
1.477     raeburn  1243: #
1.478     albertel 1244: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1245: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1246: #          course's home server.
1.477     raeburn  1247: #
1.478     albertel 1248: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1249: #          be copied from $source (current location) to 
                   1250: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1251: #         and will then be copied to
                   1252: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1253: #         course's home server.
1.485     raeburn  1254: #
1.481     raeburn  1255: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1256: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1257: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1258: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1259: #         in course's home server.
1.637     raeburn  1260: #
1.477     raeburn  1261: 
                   1262: sub process_coursefile {
1.638     albertel 1263:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1264:     my $fetchresult;
1.638     albertel 1265:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1266:     if ($action eq 'propagate') {
1.638     albertel 1267:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1268: 			     $home);
1.481     raeburn  1269:     } else {
1.477     raeburn  1270:         my $fpath = '';
                   1271:         my $fname = $file;
1.478     albertel 1272:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1273:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1274:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1275:         if ($action eq 'copy') {
                   1276:             if ($source eq '') {
                   1277:                 $fetchresult = 'no source file';
                   1278:                 return $fetchresult;
                   1279:             } else {
                   1280:                 my $destination = $filepath.'/'.$fname;
                   1281:                 rename($source,$destination);
                   1282:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1283:                                  $home);
1.481     raeburn  1284:             }
                   1285:         } elsif ($action eq 'uploaddoc') {
                   1286:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1287:             print $fh $env{'form.'.$source};
1.481     raeburn  1288:             close($fh);
1.637     raeburn  1289:             if ($parser eq 'parse') {
                   1290:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1291:                 unless ($parse_result eq 'ok') {
                   1292:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1293:                 }
                   1294:             }
1.477     raeburn  1295:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1296:                                  $home);
1.481     raeburn  1297:             if ($fetchresult eq 'ok') {
                   1298:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1299:             } else {
                   1300:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1301:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1302:                 return '/adm/notfound.html';
                   1303:             }
1.477     raeburn  1304:         }
                   1305:     }
1.485     raeburn  1306:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1307:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1308:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1309:     }
                   1310:     return $fetchresult;
                   1311: }
                   1312: 
1.637     raeburn  1313: sub build_filepath {
                   1314:     my ($fpath) = @_;
                   1315:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1316:     unless ($fpath eq '') {
                   1317:         my @parts=split('/',$fpath);
                   1318:         foreach my $part (@parts) {
                   1319:             $filepath.= '/'.$part;
                   1320:             if ((-e $filepath)!=1) {
                   1321:                 mkdir($filepath,0777);
                   1322:             }
                   1323:         }
                   1324:     }
                   1325:     return $filepath;
                   1326: }
                   1327: 
                   1328: sub store_edited_file {
1.638     albertel 1329:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1330:     my $file = $primary_url;
                   1331:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1332:     my $fpath = '';
                   1333:     my $fname = $file;
                   1334:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1335:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1336:     my $filepath = &build_filepath($fpath);
                   1337:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1338:     print $fh $content;
                   1339:     close($fh);
1.638     albertel 1340:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1341:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1342: 			  $home);
1.637     raeburn  1343:     if ($$fetchresult eq 'ok') {
                   1344:         return '/uploaded/'.$fpath.'/'.$fname;
                   1345:     } else {
1.638     albertel 1346:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1347: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1348:         return '/adm/notfound.html';
                   1349:     }
                   1350: }
                   1351: 
1.531     albertel 1352: sub clean_filename {
                   1353:     my ($fname)=@_;
1.315     www      1354: # Replace Windows backslashes by forward slashes
1.257     www      1355:     $fname=~s/\\/\//g;
1.315     www      1356: # Get rid of everything but the actual filename
1.257     www      1357:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1358: # Replace spaces by underscores
                   1359:     $fname=~s/\s+/\_/g;
                   1360: # Replace all other weird characters by nothing
1.317     www      1361:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1362: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1363: # numbers
                   1364:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1365:     return $fname;
                   1366: }
                   1367: 
1.608     albertel 1368: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1369: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1370: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1371: #        $coursedoc - if true up to the current course
                   1372: #                     if false
                   1373: #        $subdir - directory in userfile to store the file into
                   1374: #        $parser, $allfiles, $codebase - unknown
                   1375: #
                   1376: # output: url of file in userspace, or error: <message> 
                   1377: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1378: 
                   1379: 
1.531     albertel 1380: sub userfileupload {
1.719     banghart 1381:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1382:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1383:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1384:     $fname=&clean_filename($fname);
1.315     www      1385: # See if there is anything left
1.257     www      1386:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1387:     chop($env{'form.'.$formname});
1.523     raeburn  1388:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1389:         my $now = time;
                   1390:         my $filepath = 'tmp/helprequests/'.$now;
                   1391:         my @parts=split(/\//,$filepath);
                   1392:         my $fullpath = $perlvar{'lonDaemons'};
                   1393:         for (my $i=0;$i<@parts;$i++) {
                   1394:             $fullpath .= '/'.$parts[$i];
                   1395:             if ((-e $fullpath)!=1) {
                   1396:                 mkdir($fullpath,0777);
                   1397:             }
                   1398:         }
                   1399:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1400:         print $fh $env{'form.'.$formname};
1.523     raeburn  1401:         close($fh);
1.741     raeburn  1402:         return $fullpath.'/'.$fname;
                   1403:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1404:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1405:                        '_'.$env{'user.domain'}.'/pending';
                   1406:         my @parts=split(/\//,$filepath);
                   1407:         my $fullpath = $perlvar{'lonDaemons'};
                   1408:         for (my $i=0;$i<@parts;$i++) {
                   1409:             $fullpath .= '/'.$parts[$i];
                   1410:             if ((-e $fullpath)!=1) {
                   1411:                 mkdir($fullpath,0777);
                   1412:             }
                   1413:         }
                   1414:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1415:         print $fh $env{'form.'.$formname};
                   1416:         close($fh);
                   1417:         return $fullpath.'/'.$fname;
1.523     raeburn  1418:     }
1.719     banghart 1419:     
1.258     www      1420: # Create the directory if not present
1.493     albertel 1421:     $fname="$subdir/$fname";
1.259     www      1422:     if ($coursedoc) {
1.638     albertel 1423: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1424: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1425:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1426:             return &finishuserfileupload($docuname,$docudom,
                   1427: 					 $formname,$fname,$parser,$allfiles,
                   1428: 					 $codebase);
1.481     raeburn  1429:         } else {
1.620     albertel 1430:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1431:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1432: 				       $fname,$formname,$parser,
                   1433: 				       $allfiles,$codebase);
1.481     raeburn  1434:         }
1.719     banghart 1435:     } elsif (defined($destuname)) {
                   1436:         my $docuname=$destuname;
                   1437:         my $docudom=$destudom;
                   1438: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1439: 				     $fname,$parser,$allfiles,$codebase);
                   1440:         
1.259     www      1441:     } else {
1.638     albertel 1442:         my $docuname=$env{'user.name'};
                   1443:         my $docudom=$env{'user.domain'};
1.714     raeburn  1444:         if (exists($env{'form.group'})) {
                   1445:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1446:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1447:         }
1.638     albertel 1448: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1449: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1450:     }
1.271     www      1451: }
                   1452: 
                   1453: sub finishuserfileupload {
1.638     albertel 1454:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1455:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1456:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1457:     my ($fnamepath,$file);
                   1458:     $file=$fname;
                   1459:     if ($fname=~m|/|) {
                   1460:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1461: 	$path.=$fnamepath.'/';
                   1462:     }
1.259     www      1463:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1464:     my $count;
                   1465:     for ($count=4;$count<=$#parts;$count++) {
                   1466:         $filepath.="/$parts[$count]";
                   1467:         if ((-e $filepath)!=1) {
                   1468: 	    mkdir($filepath,0777);
                   1469:         }
                   1470:     }
                   1471: # Save the file
                   1472:     {
1.701     albertel 1473: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1474: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1475: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1476: 	    return '/adm/notfound.html';
                   1477: 	}
                   1478: 	if (!print FH ($env{'form.'.$formname})) {
                   1479: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1480: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1481: 	    return '/adm/notfound.html';
                   1482: 	}
1.570     albertel 1483: 	close(FH);
1.258     www      1484:     }
1.637     raeburn  1485:     if ($parser eq 'parse') {
1.638     albertel 1486:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1487: 						   $codebase);
1.637     raeburn  1488:         unless ($parse_result eq 'ok') {
1.638     albertel 1489:             &logthis('Failed to parse '.$filepath.$file.
                   1490: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1491:         }
                   1492:     }
1.259     www      1493: # Notify homeserver to grep it
                   1494: #
1.638     albertel 1495:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1496:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1497:     if ($fetchresult eq 'ok') {
1.259     www      1498: #
1.258     www      1499: # Return the URL to it
1.494     albertel 1500:         return '/uploaded/'.$path.$file;
1.263     www      1501:     } else {
1.494     albertel 1502:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1503: 		 ': '.$fetchresult);
1.263     www      1504:         return '/adm/notfound.html';
                   1505:     }    
1.493     albertel 1506: }
                   1507: 
1.637     raeburn  1508: sub extract_embedded_items {
1.648     raeburn  1509:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1510:     my @state = ();
                   1511:     my %javafiles = (
                   1512:                       codebase => '',
                   1513:                       code => '',
                   1514:                       archive => ''
                   1515:                     );
                   1516:     my %mediafiles = (
                   1517:                       src => '',
                   1518:                       movie => '',
                   1519:                      );
1.648     raeburn  1520:     my $p;
                   1521:     if ($content) {
                   1522:         $p = HTML::LCParser->new($content);
                   1523:     } else {
                   1524:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1525:     }
1.641     albertel 1526:     while (my $t=$p->get_token()) {
1.640     albertel 1527: 	if ($t->[0] eq 'S') {
                   1528: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1529: 	    push (@state, $tagname);
1.648     raeburn  1530:             if (lc($tagname) eq 'allow') {
                   1531:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1532:             }
1.640     albertel 1533: 	    if (lc($tagname) eq 'img') {
                   1534: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1535: 	    }
1.645     raeburn  1536:             if (lc($tagname) eq 'script') {
                   1537:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1538:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1539:                 } else {
                   1540:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1541:                 }
                   1542:             }
                   1543:             if (lc($tagname) eq 'link') {
                   1544:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1545:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1546:                 }
                   1547:             }
1.640     albertel 1548: 	    if (lc($tagname) eq 'object' ||
                   1549: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1550: 		foreach my $item (keys(%javafiles)) {
                   1551: 		    $javafiles{$item} = '';
                   1552: 		}
                   1553: 	    }
                   1554: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1555: 		my $name = lc($attr->{'name'});
                   1556: 		foreach my $item (keys(%javafiles)) {
                   1557: 		    if ($name eq $item) {
                   1558: 			$javafiles{$item} = $attr->{'value'};
                   1559: 			last;
                   1560: 		    }
                   1561: 		}
                   1562: 		foreach my $item (keys(%mediafiles)) {
                   1563: 		    if ($name eq $item) {
                   1564: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1565: 			last;
                   1566: 		    }
                   1567: 		}
                   1568: 	    }
                   1569: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1570: 		foreach my $item (keys(%javafiles)) {
                   1571: 		    if ($attr->{$item}) {
                   1572: 			$javafiles{$item} = $attr->{$item};
                   1573: 			last;
                   1574: 		    }
                   1575: 		}
                   1576: 		foreach my $item (keys(%mediafiles)) {
                   1577: 		    if ($attr->{$item}) {
                   1578: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1579: 			last;
                   1580: 		    }
                   1581: 		}
                   1582: 	    }
                   1583: 	} elsif ($t->[0] eq 'E') {
                   1584: 	    my ($tagname) = ($t->[1]);
                   1585: 	    if ($javafiles{'codebase'} ne '') {
                   1586: 		$javafiles{'codebase'} .= '/';
                   1587: 	    }  
                   1588: 	    if (lc($tagname) eq 'applet' ||
                   1589: 		lc($tagname) eq 'object' ||
                   1590: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1591: 		) {
                   1592: 		foreach my $item (keys(%javafiles)) {
                   1593: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1594: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1595: 			&add_filetype($allfiles,$file,$item);
                   1596: 		    }
                   1597: 		}
                   1598: 	    } 
                   1599: 	    pop @state;
                   1600: 	}
                   1601:     }
1.637     raeburn  1602:     return 'ok';
                   1603: }
                   1604: 
1.639     albertel 1605: sub add_filetype {
                   1606:     my ($allfiles,$file,$type)=@_;
                   1607:     if (exists($allfiles->{$file})) {
                   1608: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1609: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1610: 	}
                   1611:     } else {
                   1612: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1613:     }
                   1614: }
                   1615: 
1.493     albertel 1616: sub removeuploadedurl {
                   1617:     my ($url)=@_;
                   1618:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1619:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1620: }
                   1621: 
                   1622: sub removeuserfile {
                   1623:     my ($docuname,$docudom,$fname)=@_;
                   1624:     my $home=&homeserver($docuname,$docudom);
                   1625:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1626: }
1.15      www      1627: 
1.530     albertel 1628: sub mkdiruserfile {
                   1629:     my ($docuname,$docudom,$dir)=@_;
                   1630:     my $home=&homeserver($docuname,$docudom);
                   1631:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1632: }
                   1633: 
1.531     albertel 1634: sub renameuserfile {
                   1635:     my ($docuname,$docudom,$old,$new)=@_;
                   1636:     my $home=&homeserver($docuname,$docudom);
                   1637:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1638: 		  &escape("$new"),$home);
                   1639: }
                   1640: 
1.14      www      1641: # ------------------------------------------------------------------------- Log
                   1642: 
                   1643: sub log {
                   1644:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1645:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1646: }
                   1647: 
                   1648: # ------------------------------------------------------------------ Course Log
1.352     www      1649: #
                   1650: # This routine flushes several buffers of non-mission-critical nature
                   1651: #
1.157     www      1652: 
                   1653: sub flushcourselogs {
1.352     www      1654:     &logthis('Flushing log buffers');
                   1655: #
                   1656: # course logs
                   1657: # This is a log of all transactions in a course, which can be used
                   1658: # for data mining purposes
                   1659: #
                   1660: # It also collects the courseid database, which lists last transaction
                   1661: # times and course titles for all courseids
                   1662: #
                   1663:     my %courseidbuffer=();
1.191     harris41 1664:     foreach (keys %courselogs) {
1.157     www      1665:         my $crsid=$_;
1.352     www      1666:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1667: 		          &escape($courselogs{$crsid}),
                   1668: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1669: 	    delete $courselogs{$crsid};
                   1670:         } else {
                   1671:             &logthis('Failed to flush log buffer for '.$crsid);
                   1672:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1673:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1674:                         " exceeded maximum size, deleting.</font>");
                   1675:                delete $courselogs{$crsid};
                   1676:             }
1.352     www      1677:         }
                   1678:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1679:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1680: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1681:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1682:         } else {
                   1683:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1684: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1685:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1686:         }
1.191     harris41 1687:     }
1.352     www      1688: #
                   1689: # Write course id database (reverse lookup) to homeserver of courses 
                   1690: # Is used in pickcourse
                   1691: #
                   1692:     foreach (keys %courseidbuffer) {
1.353     www      1693:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1694:     }
                   1695: #
                   1696: # File accesses
                   1697: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1698: #
1.449     matthew  1699:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1700:         if ($entry =~ /___count$/) {
                   1701:             my ($dom,$name);
                   1702:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1703:             if (! defined($dom) || $dom eq '' || 
                   1704:                 ! defined($name) || $name eq '') {
1.620     albertel 1705:                 my $cid = $env{'request.course.id'};
                   1706:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1707:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1708:             }
1.450     matthew  1709:             my $value = $accesshash{$entry};
                   1710:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1711:             my %temphash=($url => $value);
1.449     matthew  1712:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1713:             if ($result eq 'ok') {
                   1714:                 delete $accesshash{$entry};
                   1715:             } elsif ($result eq 'unknown_cmd') {
                   1716:                 # Target server has old code running on it.
1.450     matthew  1717:                 my %temphash=($entry => $value);
1.449     matthew  1718:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1719:                     delete $accesshash{$entry};
                   1720:                 }
                   1721:             }
                   1722:         } else {
1.458     matthew  1723:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1724:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1725:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1726:                 delete $accesshash{$entry};
                   1727:             }
1.185     www      1728:         }
1.191     harris41 1729:     }
1.352     www      1730: #
                   1731: # Roles
                   1732: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1733: #
1.349     www      1734:     foreach (keys %userrolehash) {
                   1735:         my $entry=$_;
1.351     www      1736:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1737: 	    split(/\:/,$entry);
                   1738:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1739:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1740:                 $rudom,$runame) eq 'ok') {
                   1741: 	    delete $userrolehash{$entry};
                   1742:         }
                   1743:     }
1.662     raeburn  1744: #
                   1745: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1746: #
                   1747:     my %domrolebuffer = ();
                   1748:     foreach my $entry (keys %domainrolehash) {
                   1749:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1750:         if ($domrolebuffer{$rudom}) {
                   1751:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1752:                       '='.&escape($domainrolehash{$entry});
                   1753:         } else {
                   1754:             $domrolebuffer{$rudom}.=&escape($entry).
                   1755:                       '='.&escape($domainrolehash{$entry});
                   1756:         }
                   1757:         delete $domainrolehash{$entry};
                   1758:     }
                   1759:     foreach my $dom (keys(%domrolebuffer)) {
                   1760:         foreach my $tryserver (keys %libserv) {
                   1761:             if ($hostdom{$tryserver} eq $dom) {
                   1762:                 unless (&reply('domroleput:'.$dom.':'.
                   1763:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1764:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1765:                 }
                   1766:             }
                   1767:         }
                   1768:     }
1.186     www      1769:     $dumpcount++;
1.157     www      1770: }
                   1771: 
                   1772: sub courselog {
                   1773:     my $what=shift;
1.158     www      1774:     $what=time.':'.$what;
1.620     albertel 1775:     unless ($env{'request.course.id'}) { return ''; }
                   1776:     $coursedombuf{$env{'request.course.id'}}=
                   1777:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1778:     $coursenumbuf{$env{'request.course.id'}}=
                   1779:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1780:     $coursehombuf{$env{'request.course.id'}}=
                   1781:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1782:     $coursedescrbuf{$env{'request.course.id'}}=
                   1783:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1784:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1785:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1786:     $courseownerbuf{$env{'request.course.id'}}=
                   1787:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1788:     $coursetypebuf{$env{'request.course.id'}}=
                   1789:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1790:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1791: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1792:     } else {
1.620     albertel 1793: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1794:     }
1.620     albertel 1795:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1796: 	&flushcourselogs();
                   1797:     }
1.158     www      1798: }
                   1799: 
                   1800: sub courseacclog {
                   1801:     my $fnsymb=shift;
1.620     albertel 1802:     unless ($env{'request.course.id'}) { return ''; }
                   1803:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1804:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1805:         $what.=':POST';
1.583     matthew  1806:         # FIXME: Probably ought to escape things....
1.620     albertel 1807: 	foreach (keys %env) {
1.158     www      1808:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1809: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1810:             }
1.191     harris41 1811:         }
1.583     matthew  1812:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1813:         # FIXME: We should not be depending on a form parameter that someone
                   1814:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1815:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1816:             $what.= ':POST';
                   1817:             # FIXME: Probably ought to escape things....
                   1818:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1819:                                  'crsdiscuss') {
1.620     albertel 1820:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1821:             }
                   1822:         }
1.158     www      1823:     }
                   1824:     &courselog($what);
1.149     www      1825: }
                   1826: 
1.185     www      1827: sub countacc {
                   1828:     my $url=&declutter(shift);
1.458     matthew  1829:     return if (! defined($url) || $url eq '');
1.620     albertel 1830:     unless ($env{'request.course.id'}) { return ''; }
                   1831:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1832:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1833:     $accesshash{$key}++;
1.185     www      1834: }
1.349     www      1835: 
1.361     www      1836: sub linklog {
                   1837:     my ($from,$to)=@_;
                   1838:     $from=&declutter($from);
                   1839:     $to=&declutter($to);
                   1840:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1841:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1842: }
                   1843:   
1.349     www      1844: sub userrolelog {
                   1845:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1846:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1847:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1848:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1849:         ($trole=~/^ta/)) {
1.350     www      1850:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1851:        $userrolehash
                   1852:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1853:                     =$tend.':'.$tstart;
1.662     raeburn  1854:     }
                   1855:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1856:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1857:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1858:         ($trole=~/^sc/)) {
                   1859:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1860:        $domainrolehash
                   1861:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1862:                     = $tend.':'.$tstart;
                   1863:     }
1.351     www      1864: }
                   1865: 
                   1866: sub get_course_adv_roles {
                   1867:     my $cid=shift;
1.620     albertel 1868:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1869:     my %coursehash=&coursedescription($cid);
1.470     www      1870:     my %nothide=();
                   1871:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1872: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1873:     }
1.351     www      1874:     my %returnhash=();
                   1875:     my %dumphash=
                   1876:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1877:     my $now=time;
                   1878:     foreach (keys %dumphash) {
                   1879: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1880:         if (($tstart) && ($tstart<0)) { next; }
                   1881:         if (($tend) && ($tend<$now)) { next; }
                   1882:         if (($tstart) && ($now<$tstart)) { next; }
                   1883:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1884: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1885: 	if ((&privileged($username,$domain)) && 
                   1886: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1887: 	if ($role eq 'cr') { next; }
1.351     www      1888:         my $key=&plaintext($role);
1.656     albertel 1889: 	if ($role =~ /^cr/) {
                   1890: 	    $key=(split('/',$role))[3];
                   1891: 	}
1.351     www      1892:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1893:         if ($returnhash{$key}) {
                   1894: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1895:         } else {
                   1896:             $returnhash{$key}=$username.':'.$domain;
                   1897:         }
1.400     www      1898:      }
                   1899:     return %returnhash;
                   1900: }
                   1901: 
                   1902: sub get_my_roles {
                   1903:     my ($uname,$udom)=@_;
1.620     albertel 1904:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1905:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1906:     my %dumphash=
                   1907:             &dump('nohist_userroles',$udom,$uname);
                   1908:     my %returnhash=();
                   1909:     my $now=time;
                   1910:     foreach (keys %dumphash) {
                   1911: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1912:         if (($tstart) && ($tstart<0)) { next; }
                   1913:         if (($tend) && ($tend<$now)) { next; }
                   1914:         if (($tstart) && ($now<$tstart)) { next; }
                   1915:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1916: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1917:      }
                   1918:     return %returnhash;
1.399     www      1919: }
                   1920: 
                   1921: # ----------------------------------------------------- Frontpage Announcements
                   1922: #
                   1923: #
                   1924: 
                   1925: sub postannounce {
                   1926:     my ($server,$text)=@_;
                   1927:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1928:     unless ($text=~/\w/) { $text=''; }
                   1929:     return &reply('setannounce:'.&escape($text),$server);
                   1930: }
                   1931: 
                   1932: sub getannounce {
1.448     albertel 1933: 
                   1934:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1935: 	my $announcement='';
                   1936: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1937: 	close($fh);
1.399     www      1938: 	if ($announcement=~/\w/) { 
                   1939: 	    return 
                   1940:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1941:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1942: 	} else {
                   1943: 	    return '';
                   1944: 	}
                   1945:     } else {
                   1946: 	return '';
                   1947:     }
1.351     www      1948: }
1.353     www      1949: 
                   1950: # ---------------------------------------------------------- Course ID routines
                   1951: # Deal with domain's nohist_courseid.db files
                   1952: #
                   1953: 
                   1954: sub courseidput {
                   1955:     my ($domain,$what,$coursehome)=@_;
                   1956:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1957: }
                   1958: 
                   1959: sub courseiddump {
1.741     raeburn  1960:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1961:     my %returnhash=();
1.355     www      1962:     unless ($domfilter) { $domfilter=''; }
1.353     www      1963:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1964:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1965: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1966: 	        foreach (
                   1967:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1968: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1969:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1970:                                $tryserver))) {
1.506     raeburn  1971: 		    my ($key,$value)=split(/\=/,$_);
                   1972:                     if (($key) && ($value)) {
1.516     raeburn  1973: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1974:                     }
1.353     www      1975:                 }
                   1976:             }
                   1977:         }
                   1978:     }
                   1979:     return %returnhash;
                   1980: }
                   1981: 
1.658     raeburn  1982: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1983: 
                   1984: sub dcmailput {
1.685     raeburn  1985:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1986:     my $status = &Apache::lonnet::critical(
1.740     www      1987:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1988:        &escape($message),$server);
1.662     raeburn  1989:     return $status;
                   1990: }
                   1991: 
1.658     raeburn  1992: sub dcmaildump {
                   1993:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1994:     my %returnhash=();
                   1995:     if (exists($domain_primary{$dom})) {
                   1996:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1997:                                                          &escape($enddate).':';
                   1998: 	my @esc_senders=map { &escape($_)} @$senders;
                   1999: 	$cmd.=&escape(join('&',@esc_senders));
                   2000: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2001:             my ($key,$value) = split(/\=/,$_);
                   2002:             if (($key) && ($value)) {
                   2003:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2004:             }
                   2005:         }
                   2006:     }
                   2007:     return %returnhash;
                   2008: }
1.662     raeburn  2009: # ---------------------------------------------------------- Domain roles
                   2010: 
                   2011: sub get_domain_roles {
                   2012:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2013:     if (undef($startdate) || $startdate eq '') {
                   2014:         $startdate = '.';
                   2015:     }
                   2016:     if (undef($enddate) || $enddate eq '') {
                   2017:         $enddate = '.';
                   2018:     }
                   2019:     my $rolelist = join(':',@{$roles});
                   2020:     my %personnel = ();
                   2021:     foreach my $tryserver (keys(%libserv)) {
                   2022:         if ($hostdom{$tryserver} eq $dom) {
                   2023:             %{$personnel{$tryserver}}=();
                   2024:             foreach (
                   2025:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2026:                    &escape($startdate).':'.&escape($enddate).':'.
                   2027:                    &escape($rolelist), $tryserver))) {
                   2028:                 my($key,$value) = split(/\=/,$_);
                   2029:                 if (($key) && ($value)) {
                   2030:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2031:                 }
                   2032:             }
                   2033:         }
                   2034:     }
                   2035:     return %personnel;
                   2036: }
1.658     raeburn  2037: 
1.149     www      2038: # ----------------------------------------------------------- Check out an item
                   2039: 
1.504     albertel 2040: sub get_first_access {
                   2041:     my ($type,$argsymb)=@_;
                   2042:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2043:     if ($argsymb) { $symb=$argsymb; }
                   2044:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2045:     if ($type eq 'map') {
                   2046: 	$res=&symbread($map);
                   2047:     } else {
                   2048: 	$res=$symb;
                   2049:     }
                   2050:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2051:     return $times{"$courseid\0$res"};
1.504     albertel 2052: }
                   2053: 
                   2054: sub set_first_access {
                   2055:     my ($type)=@_;
                   2056:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2057:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2058:     if ($type eq 'map') {
                   2059: 	$res=&symbread($map);
                   2060:     } else {
                   2061: 	$res=$symb;
                   2062:     }
                   2063:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2064:     if (!$firstaccess) {
1.588     albertel 2065: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2066:     }
                   2067:     return 'already_set';
1.504     albertel 2068: }
                   2069: 
1.149     www      2070: sub checkout {
                   2071:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2072:     my $now=time;
                   2073:     my $lonhost=$perlvar{'lonHostID'};
                   2074:     my $infostr=&escape(
1.234     www      2075:                  'CHECKOUTTOKEN&'.
1.149     www      2076:                  $tuname.'&'.
                   2077:                  $tudom.'&'.
                   2078:                  $tcrsid.'&'.
                   2079:                  $symb.'&'.
                   2080: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2081:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2082:     if ($token=~/^error\:/) { 
1.672     albertel 2083:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2084:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2085:                  "</font>");
                   2086:         return ''; 
                   2087:     }
                   2088: 
1.149     www      2089:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2090:     $token=~tr/a-z/A-Z/;
                   2091: 
1.153     www      2092:     my %infohash=('resource.0.outtoken' => $token,
                   2093:                   'resource.0.checkouttime' => $now,
                   2094:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2095: 
                   2096:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2097:        return '';
1.151     www      2098:     } else {
1.672     albertel 2099:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2100:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2101:                  "</font>");
1.149     www      2102:     }    
                   2103: 
                   2104:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2105:                          &escape('Checkout '.$infostr.' - '.
                   2106:                                                  $token)) ne 'ok') {
                   2107: 	return '';
1.151     www      2108:     } else {
1.672     albertel 2109:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2110:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2111:                  "</font>");
1.149     www      2112:     }
1.151     www      2113:     return $token;
1.149     www      2114: }
                   2115: 
                   2116: # ------------------------------------------------------------ Check in an item
                   2117: 
                   2118: sub checkin {
                   2119:     my $token=shift;
1.150     www      2120:     my $now=time;
                   2121:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2122:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2123:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2124:     $dtoken=~s/\W/\_/g;
1.234     www      2125:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2126:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2127: 
1.154     www      2128:     unless (($tuname) && ($tudom)) {
                   2129:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2130:         return '';
                   2131:     }
                   2132:     
                   2133:     unless (&allowed('mgr',$tcrsid)) {
                   2134:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2135:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2136:         return '';
                   2137:     }
                   2138: 
1.153     www      2139:     my %infohash=('resource.0.intoken' => $token,
                   2140:                   'resource.0.checkintime' => $now,
                   2141:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2142: 
                   2143:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2144:        return '';
                   2145:     }    
                   2146: 
                   2147:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2148:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2149: 	return '';
                   2150:     }
                   2151: 
                   2152:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2153: }
                   2154: 
                   2155: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2156: 
                   2157: sub expirespread {
                   2158:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2159:     my $cid=$env{'request.course.id'}; 
1.110     www      2160:     if ($cid) {
                   2161:        my $now=time;
                   2162:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2163:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2164:                             $env{'course.'.$cid.'.num'}.
1.110     www      2165: 	        	    ':nohist_expirationdates:'.
                   2166:                             &escape($key).'='.$now,
1.620     albertel 2167:                             $env{'course.'.$cid.'.home'})
1.110     www      2168:     }
                   2169:     return 'ok';
1.14      www      2170: }
                   2171: 
1.109     www      2172: # ----------------------------------------------------- Devalidate Spreadsheets
                   2173: 
                   2174: sub devalidate {
1.325     www      2175:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2176:     my $cid=$env{'request.course.id'}; 
1.109     www      2177:     if ($cid) {
1.391     matthew  2178:         # delete the stored spreadsheets for
                   2179:         # - the student level sheet of this user in course's homespace
                   2180:         # - the assessment level sheet for this resource 
                   2181:         #   for this user in user's homespace
1.553     albertel 2182: 	# - current conditional state info
1.325     www      2183: 	my $key=$uname.':'.$udom.':';
1.109     www      2184:         my $status=
1.299     matthew  2185: 	    &del('nohist_calculatedsheets',
1.391     matthew  2186: 		 [$key.'studentcalc:'],
1.620     albertel 2187: 		 $env{'course.'.$cid.'.domain'},
                   2188: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2189: 		.' '.
                   2190: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2191: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2192:         unless ($status eq 'ok ok') {
                   2193:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2194:                     $uname.' at '.$udom.' for '.
1.109     www      2195: 		    $symb.': '.$status);
1.133     albertel 2196:         }
1.553     albertel 2197: 	&delenv('user.state.'.$cid);
1.109     www      2198:     }
                   2199: }
                   2200: 
1.265     albertel 2201: sub get_scalar {
                   2202:     my ($string,$end) = @_;
                   2203:     my $value;
                   2204:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2205: 	$value = $1;
                   2206:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2207: 	$value = $1;
                   2208:     }
                   2209:     return &unescape($value);
                   2210: }
                   2211: 
                   2212: sub array2str {
                   2213:   my (@array) = @_;
                   2214:   my $result=&arrayref2str(\@array);
                   2215:   $result=~s/^__ARRAY_REF__//;
                   2216:   $result=~s/__END_ARRAY_REF__$//;
                   2217:   return $result;
                   2218: }
                   2219: 
1.204     albertel 2220: sub arrayref2str {
                   2221:   my ($arrayref) = @_;
1.265     albertel 2222:   my $result='__ARRAY_REF__';
1.204     albertel 2223:   foreach my $elem (@$arrayref) {
1.265     albertel 2224:     if(ref($elem) eq 'ARRAY') {
                   2225:       $result.=&arrayref2str($elem).'&';
                   2226:     } elsif(ref($elem) eq 'HASH') {
                   2227:       $result.=&hashref2str($elem).'&';
                   2228:     } elsif(ref($elem)) {
                   2229:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2230:     } else {
                   2231:       $result.=&escape($elem).'&';
                   2232:     }
                   2233:   }
                   2234:   $result=~s/\&$//;
1.265     albertel 2235:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2236:   return $result;
                   2237: }
                   2238: 
1.168     albertel 2239: sub hash2str {
1.204     albertel 2240:   my (%hash) = @_;
                   2241:   my $result=&hashref2str(\%hash);
1.265     albertel 2242:   $result=~s/^__HASH_REF__//;
                   2243:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2244:   return $result;
                   2245: }
                   2246: 
                   2247: sub hashref2str {
                   2248:   my ($hashref)=@_;
1.265     albertel 2249:   my $result='__HASH_REF__';
1.495     albertel 2250:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2251:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2252:       $result.=&arrayref2str($_).'=';
1.204     albertel 2253:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2254:       $result.=&hashref2str($_).'=';
1.204     albertel 2255:     } elsif (ref($_)) {
1.265     albertel 2256:       $result.='=';
                   2257:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2258:     } else {
1.265     albertel 2259: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2260:     }
                   2261: 
1.265     albertel 2262:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2263:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2264:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2265:       $result.=&hashref2str($hashref->{$_}).'&';
                   2266:     } elsif(ref($hashref->{$_})) {
                   2267:        $result.='&';
                   2268:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2269:     } else {
1.265     albertel 2270:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2271:     }
                   2272:   }
1.168     albertel 2273:   $result=~s/\&$//;
1.265     albertel 2274:   $result .= '__END_HASH_REF__';
1.168     albertel 2275:   return $result;
                   2276: }
                   2277: 
                   2278: sub str2hash {
1.265     albertel 2279:     my ($string)=@_;
                   2280:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2281:     return %$hash;
                   2282: }
                   2283: 
                   2284: sub str2hashref {
1.168     albertel 2285:   my ($string) = @_;
1.265     albertel 2286: 
                   2287:   my %hash;
                   2288: 
                   2289:   if($string !~ /^__HASH_REF__/) {
                   2290:       if (! ($string eq '' || !defined($string))) {
                   2291: 	  $hash{'error'}='Not hash reference';
                   2292:       }
                   2293:       return (\%hash, $string);
                   2294:   }
                   2295: 
                   2296:   $string =~ s/^__HASH_REF__//;
                   2297: 
                   2298:   while($string !~ /^__END_HASH_REF__/) {
                   2299:       #key
                   2300:       my $key='';
                   2301:       if($string =~ /^__HASH_REF__/) {
                   2302:           ($key, $string)=&str2hashref($string);
                   2303:           if(defined($key->{'error'})) {
                   2304:               $hash{'error'}='Bad data';
                   2305:               return (\%hash, $string);
                   2306:           }
                   2307:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2308:           ($key, $string)=&str2arrayref($string);
                   2309:           if($key->[0] eq 'Array reference error') {
                   2310:               $hash{'error'}='Bad data';
                   2311:               return (\%hash, $string);
                   2312:           }
                   2313:       } else {
                   2314:           $string =~ s/^(.*?)=//;
1.267     albertel 2315: 	  $key=&unescape($1);
1.265     albertel 2316:       }
                   2317:       $string =~ s/^=//;
                   2318: 
                   2319:       #value
                   2320:       my $value='';
                   2321:       if($string =~ /^__HASH_REF__/) {
                   2322:           ($value, $string)=&str2hashref($string);
                   2323:           if(defined($value->{'error'})) {
                   2324:               $hash{'error'}='Bad data';
                   2325:               return (\%hash, $string);
                   2326:           }
                   2327:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2328:           ($value, $string)=&str2arrayref($string);
                   2329:           if($value->[0] eq 'Array reference error') {
                   2330:               $hash{'error'}='Bad data';
                   2331:               return (\%hash, $string);
                   2332:           }
                   2333:       } else {
                   2334: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2335:       }
                   2336:       $string =~ s/^&//;
                   2337: 
                   2338:       $hash{$key}=$value;
1.204     albertel 2339:   }
1.265     albertel 2340: 
                   2341:   $string =~ s/^__END_HASH_REF__//;
                   2342: 
                   2343:   return (\%hash, $string);
1.204     albertel 2344: }
                   2345: 
                   2346: sub str2array {
1.265     albertel 2347:     my ($string)=@_;
                   2348:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2349:     return @$array;
                   2350: }
                   2351: 
                   2352: sub str2arrayref {
1.204     albertel 2353:   my ($string) = @_;
1.265     albertel 2354:   my @array;
                   2355: 
                   2356:   if($string !~ /^__ARRAY_REF__/) {
                   2357:       if (! ($string eq '' || !defined($string))) {
                   2358: 	  $array[0]='Array reference error';
                   2359:       }
                   2360:       return (\@array, $string);
                   2361:   }
                   2362: 
                   2363:   $string =~ s/^__ARRAY_REF__//;
                   2364: 
                   2365:   while($string !~ /^__END_ARRAY_REF__/) {
                   2366:       my $value='';
                   2367:       if($string =~ /^__HASH_REF__/) {
                   2368:           ($value, $string)=&str2hashref($string);
                   2369:           if(defined($value->{'error'})) {
                   2370:               $array[0] ='Array reference error';
                   2371:               return (\@array, $string);
                   2372:           }
                   2373:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2374:           ($value, $string)=&str2arrayref($string);
                   2375:           if($value->[0] eq 'Array reference error') {
                   2376:               $array[0] ='Array reference error';
                   2377:               return (\@array, $string);
                   2378:           }
                   2379:       } else {
                   2380: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2381:       }
                   2382:       $string =~ s/^&//;
                   2383: 
                   2384:       push(@array, $value);
1.191     harris41 2385:   }
1.265     albertel 2386: 
                   2387:   $string =~ s/^__END_ARRAY_REF__//;
                   2388: 
                   2389:   return (\@array, $string);
1.168     albertel 2390: }
                   2391: 
1.167     albertel 2392: # -------------------------------------------------------------------Temp Store
                   2393: 
1.168     albertel 2394: sub tmpreset {
                   2395:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2396:   if (!$symb) {
                   2397:     $symb=&symbread();
1.620     albertel 2398:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2399:   }
                   2400:   $symb=escape($symb);
                   2401: 
1.620     albertel 2402:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2403:   $namespace=~s/\//\_/g;
                   2404:   $namespace=~s/\W//g;
                   2405: 
1.620     albertel 2406:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2407:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2408:   if ($domain eq 'public' && $stuname eq 'public') {
                   2409:       $stuname=$ENV{'REMOTE_ADDR'};
                   2410:   }
1.168     albertel 2411:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2412:   my %hash;
                   2413:   if (tie(%hash,'GDBM_File',
                   2414: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2415: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2416:     foreach my $key (keys %hash) {
1.180     albertel 2417:       if ($key=~ /:$symb/) {
1.168     albertel 2418: 	delete($hash{$key});
                   2419:       }
                   2420:     }
                   2421:   }
                   2422: }
                   2423: 
1.167     albertel 2424: sub tmpstore {
1.168     albertel 2425:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2426: 
                   2427:   if (!$symb) {
                   2428:     $symb=&symbread();
1.620     albertel 2429:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2430:   }
                   2431:   $symb=escape($symb);
                   2432: 
                   2433:   if (!$namespace) {
                   2434:     # I don't think we would ever want to store this for a course.
                   2435:     # it seems this will only be used if we don't have a course.
1.620     albertel 2436:     #$namespace=$env{'request.course.id'};
1.168     albertel 2437:     #if (!$namespace) {
1.620     albertel 2438:       $namespace=$env{'request.state'};
1.168     albertel 2439:     #}
                   2440:   }
                   2441:   $namespace=~s/\//\_/g;
                   2442:   $namespace=~s/\W//g;
1.620     albertel 2443:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2444:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2445:   if ($domain eq 'public' && $stuname eq 'public') {
                   2446:       $stuname=$ENV{'REMOTE_ADDR'};
                   2447:   }
1.168     albertel 2448:   my $now=time;
                   2449:   my %hash;
                   2450:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2451:   if (tie(%hash,'GDBM_File',
                   2452: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2453: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2454:     $hash{"version:$symb"}++;
                   2455:     my $version=$hash{"version:$symb"};
                   2456:     my $allkeys=''; 
                   2457:     foreach my $key (keys(%$storehash)) {
                   2458:       $allkeys.=$key.':';
1.591     albertel 2459:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2460:     }
                   2461:     $hash{"$version:$symb:timestamp"}=$now;
                   2462:     $allkeys.='timestamp';
                   2463:     $hash{"$version:keys:$symb"}=$allkeys;
                   2464:     if (untie(%hash)) {
                   2465:       return 'ok';
                   2466:     } else {
                   2467:       return "error:$!";
                   2468:     }
                   2469:   } else {
                   2470:     return "error:$!";
                   2471:   }
                   2472: }
1.167     albertel 2473: 
1.168     albertel 2474: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2475: 
1.168     albertel 2476: sub tmprestore {
                   2477:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2478: 
1.168     albertel 2479:   if (!$symb) {
                   2480:     $symb=&symbread();
1.620     albertel 2481:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2482:   }
                   2483:   $symb=escape($symb);
                   2484: 
1.620     albertel 2485:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2486: 
1.620     albertel 2487:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2488:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2489:   if ($domain eq 'public' && $stuname eq 'public') {
                   2490:       $stuname=$ENV{'REMOTE_ADDR'};
                   2491:   }
1.168     albertel 2492:   my %returnhash;
                   2493:   $namespace=~s/\//\_/g;
                   2494:   $namespace=~s/\W//g;
                   2495:   my %hash;
                   2496:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2497:   if (tie(%hash,'GDBM_File',
                   2498: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2499: 	  &GDBM_READER(),0640)) {
1.168     albertel 2500:     my $version=$hash{"version:$symb"};
                   2501:     $returnhash{'version'}=$version;
                   2502:     my $scope;
                   2503:     for ($scope=1;$scope<=$version;$scope++) {
                   2504:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2505:       my @keys=split(/:/,$vkeys);
                   2506:       my $key;
                   2507:       $returnhash{"$scope:keys"}=$vkeys;
                   2508:       foreach $key (@keys) {
1.591     albertel 2509: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2510: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2511:       }
                   2512:     }
1.168     albertel 2513:     if (!(untie(%hash))) {
                   2514:       return "error:$!";
                   2515:     }
                   2516:   } else {
                   2517:     return "error:$!";
                   2518:   }
                   2519:   return %returnhash;
1.167     albertel 2520: }
                   2521: 
1.9       www      2522: # ----------------------------------------------------------------------- Store
                   2523: 
                   2524: sub store {
1.124     www      2525:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2526:     my $home='';
                   2527: 
1.168     albertel 2528:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2529: 
1.213     www      2530:     $symb=&symbclean($symb);
1.122     albertel 2531:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2532: 
1.620     albertel 2533:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2534:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2535: 
                   2536:     &devalidate($symb,$stuname,$domain);
1.109     www      2537: 
                   2538:     $symb=escape($symb);
1.187     www      2539:     if (!$namespace) { 
1.620     albertel 2540:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2541:           return ''; 
                   2542:        } 
                   2543:     }
1.620     albertel 2544:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2545: 
                   2546:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2547:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2548: 
1.12      www      2549:     my $namevalue='';
1.191     harris41 2550:     foreach (keys %$storehash) {
1.591     albertel 2551:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2552:     }
1.12      www      2553:     $namevalue=~s/\&$//;
1.187     www      2554:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2555:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2556: }
                   2557: 
1.47      www      2558: # -------------------------------------------------------------- Critical Store
                   2559: 
                   2560: sub cstore {
1.124     www      2561:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2562:     my $home='';
                   2563: 
1.168     albertel 2564:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2565: 
1.213     www      2566:     $symb=&symbclean($symb);
1.122     albertel 2567:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2568: 
1.620     albertel 2569:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2570:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2571: 
                   2572:     &devalidate($symb,$stuname,$domain);
1.109     www      2573: 
                   2574:     $symb=escape($symb);
1.187     www      2575:     if (!$namespace) { 
1.620     albertel 2576:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2577:           return ''; 
                   2578:        } 
                   2579:     }
1.620     albertel 2580:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2581: 
                   2582:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2583:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2584: 
1.47      www      2585:     my $namevalue='';
1.191     harris41 2586:     foreach (keys %$storehash) {
1.591     albertel 2587:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2588:     }
1.47      www      2589:     $namevalue=~s/\&$//;
1.187     www      2590:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2591:     return critical
                   2592:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2593: }
                   2594: 
1.9       www      2595: # --------------------------------------------------------------------- Restore
                   2596: 
                   2597: sub restore {
1.124     www      2598:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2599:     my $home='';
                   2600: 
1.168     albertel 2601:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2602: 
1.122     albertel 2603:     if (!$symb) {
                   2604:       unless ($symb=escape(&symbread())) { return ''; }
                   2605:     } else {
1.213     www      2606:       $symb=&escape(&symbclean($symb));
1.122     albertel 2607:     }
1.188     www      2608:     if (!$namespace) { 
1.620     albertel 2609:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2610:           return ''; 
                   2611:        } 
                   2612:     }
1.620     albertel 2613:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2614:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2615:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2616:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2617: 
1.12      www      2618:     my %returnhash=();
1.191     harris41 2619:     foreach (split(/\&/,$answer)) {
1.12      www      2620: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2621:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2622:     }
1.75      www      2623:     my $version;
                   2624:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2625:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2626:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2627:        }
1.75      www      2628:     }
1.13      www      2629:     return %returnhash;
1.34      www      2630: }
                   2631: 
                   2632: # ---------------------------------------------------------- Course Description
                   2633: 
                   2634: sub coursedescription {
1.731     albertel 2635:     my ($courseid,$args)=@_;
1.34      www      2636:     $courseid=~s/^\///;
1.49      www      2637:     $courseid=~s/\_/\//g;
1.34      www      2638:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2639:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2640:     my $normalid=$cdomain.'_'.$cnum;
                   2641:     # need to always cache even if we get errors otherwise we keep 
                   2642:     # trying and trying and trying to get the course description.
                   2643:     my %envhash=();
                   2644:     my %returnhash=();
1.731     albertel 2645:     
                   2646:     my $expiretime=600;
                   2647:     if ($env{'request.course.id'} eq $normalid) {
                   2648: 	$expiretime=120;
                   2649:     }
                   2650: 
                   2651:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2652:     if (!$args->{'freshen_cache'}
                   2653: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2654: 	foreach my $key (keys(%env)) {
                   2655: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2656: 	    my ($setting) = $1;
                   2657: 	    $returnhash{$setting} = $env{$key};
                   2658: 	}
                   2659: 	return %returnhash;
                   2660:     }
                   2661: 
                   2662:     # get the data agin
                   2663:     if (!$args->{'one_time'}) {
                   2664: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2665:     }
1.34      www      2666:     if ($chome ne 'no_host') {
1.302     albertel 2667:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2668:        if (!exists($returnhash{'con_lost'})) {
                   2669:            $returnhash{'home'}= $chome;
                   2670: 	   $returnhash{'domain'} = $cdomain;
                   2671: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2672:            if (!defined($returnhash{'type'})) {
                   2673:                $returnhash{'type'} = 'Course';
                   2674:            }
1.130     albertel 2675:            while (my ($name,$value) = each %returnhash) {
1.53      www      2676:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2677:            }
1.270     www      2678:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2679:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2680: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2681:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2682:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2683:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2684:        }
                   2685:     }
1.731     albertel 2686:     if (!$args->{'one_time'}) {
                   2687: 	&appenv(%envhash);
                   2688:     }
1.302     albertel 2689:     return %returnhash;
1.461     www      2690: }
                   2691: 
                   2692: # -------------------------------------------------See if a user is privileged
                   2693: 
                   2694: sub privileged {
                   2695:     my ($username,$domain)=@_;
                   2696:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2697: 			&homeserver($username,$domain));
                   2698:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2699:     my $now=time;
                   2700:     if ($rolesdump ne '') {
                   2701:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2702: 	    if ($_!~/^rolesdef_/) {
1.461     www      2703: 		my ($area,$role)=split(/=/,$_);
                   2704: 		$area=~s/\_\w\w$//;
                   2705: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2706: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2707: 		    my $active=1;
                   2708: 		    if ($tend) {
                   2709: 			if ($tend<$now) { $active=0; }
                   2710: 		    }
                   2711: 		    if ($tstart) {
                   2712: 			if ($tstart>$now) { $active=0; }
                   2713: 		    }
                   2714: 		    if ($active) { return 1; }
                   2715: 		}
                   2716: 	    }
                   2717: 	}
                   2718:     }
                   2719:     return 0;
1.9       www      2720: }
1.1       albertel 2721: 
1.103     harris41 2722: # -------------------------------------------------------- Get user privileges
1.11      www      2723: 
                   2724: sub rolesinit {
                   2725:     my ($domain,$username,$authhost)=@_;
                   2726:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2727:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2728:     my %allroles=();
1.678     raeburn  2729:     my %allgroups=();   
1.11      www      2730:     my $now=time;
1.743     albertel 2731:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2732:     my $group_privs;
1.11      www      2733: 
                   2734:     if ($rolesdump ne '') {
1.191     harris41 2735:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2736: 	  if ($_!~/^rolesdef_/) {
1.11      www      2737:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2738: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2739:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2740: 	    if ($role=~/^cr/) { 
1.655     albertel 2741: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2742: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2743: 		    ($tend,$tstart)=split('_',$trest);
                   2744: 		} else {
                   2745: 		    $trole=$role;
                   2746: 		}
1.678     raeburn  2747:             } elsif ($role =~ m|^gr/|) {
                   2748:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2749:                 ($trole,$group_privs) = split(/\//,$trole);
                   2750:                 $group_privs = &unescape($group_privs);
1.587     albertel 2751: 	    } else {
                   2752: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2753: 	    }
1.743     albertel 2754: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2755: 					 $username);
                   2756: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2757:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2758:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2759:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2760: 		my $spec=$trole.'.'.$area;
                   2761: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2762: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2763:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2764:                 } elsif ($trole eq 'gr') {
                   2765:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2766: 		} else {
1.567     raeburn  2767:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2768: 		}
1.12      www      2769:             }
1.662     raeburn  2770:           }
1.191     harris41 2771:         }
1.743     albertel 2772:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2773:         $userroles{'user.adv'}    = $adv;
                   2774: 	$userroles{'user.author'} = $author;
1.620     albertel 2775:         $env{'user.adv'}=$adv;
1.11      www      2776:     }
1.743     albertel 2777:     return \%userroles;  
1.11      www      2778: }
                   2779: 
1.567     raeburn  2780: sub set_arearole {
                   2781:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2782: # log the associated role with the area
                   2783:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2784:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2785: }
                   2786: 
                   2787: sub custom_roleprivs {
                   2788:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2789:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2790:     my $homsvr=homeserver($rauthor,$rdomain);
                   2791:     if ($hostname{$homsvr} ne '') {
                   2792:         my ($rdummy,$roledef)=
                   2793:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2794:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2795:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2796:             if (defined($syspriv)) {
                   2797:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2798:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2799:             }
                   2800:             if ($tdomain ne '') {
                   2801:                 if (defined($dompriv)) {
                   2802:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2803:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2804:                 }
                   2805:                 if (($trest ne '') && (defined($coursepriv))) {
                   2806:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2807:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2808:                 }
                   2809:             }
                   2810:         }
                   2811:     }
                   2812: }
                   2813: 
1.678     raeburn  2814: sub group_roleprivs {
                   2815:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2816:     my $access = 1;
                   2817:     my $now = time;
                   2818:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2819:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2820:     if ($access) {
                   2821:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2822:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2823:     }
                   2824: }
1.567     raeburn  2825: 
                   2826: sub standard_roleprivs {
                   2827:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2828:     if (defined($pr{$trole.':s'})) {
                   2829:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2830:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2831:     }
                   2832:     if ($tdomain ne '') {
                   2833:         if (defined($pr{$trole.':d'})) {
                   2834:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2835:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2836:         }
                   2837:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2838:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2839:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2840:         }
                   2841:     }
                   2842: }
                   2843: 
                   2844: sub set_userprivs {
1.678     raeburn  2845:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2846:     my $author=0;
                   2847:     my $adv=0;
1.678     raeburn  2848:     my %grouproles = ();
                   2849:     if (keys(%{$allgroups}) > 0) {
                   2850:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2851:             my ($trole,$area,$sec,$extendedarea);
                   2852:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2853:                 $trole = $1;
                   2854:                 $area = $2;
1.681     raeburn  2855:                 $sec = $3;
                   2856:                 $extendedarea = $area.$sec;
                   2857:                 if (exists($$allgroups{$area})) {
                   2858:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2859:                         my $spec = $trole.'.'.$extendedarea;
                   2860:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2861:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2862:                     }
                   2863:                 }
                   2864:             }
                   2865:         }
                   2866:     }
                   2867:     foreach (keys(%grouproles)) {
                   2868:         $$allroles{$_} = $grouproles{$_};
                   2869:     }
1.567     raeburn  2870:     foreach (keys %{$allroles}) {
                   2871:         my %thesepriv=();
                   2872:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2873:         foreach (split(/:/,$$allroles{$_})) {
                   2874:             if ($_ ne '') {
                   2875:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2876:                 if ($restrictions eq '') {
                   2877:                     $thesepriv{$privilege}='F';
                   2878:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2879:                     $thesepriv{$privilege}.=$restrictions;
                   2880:                 }
                   2881:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2882:             }
                   2883:         }
                   2884:         my $thesestr='';
                   2885:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2886:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2887:     }
                   2888:     return ($author,$adv);
                   2889: }
                   2890: 
1.12      www      2891: # --------------------------------------------------------------- get interface
                   2892: 
                   2893: sub get {
1.131     albertel 2894:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2895:    my $items='';
1.191     harris41 2896:    foreach (@$storearr) {
1.12      www      2897:        $items.=escape($_).'&';
1.191     harris41 2898:    }
1.12      www      2899:    $items=~s/\&$//;
1.620     albertel 2900:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2901:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2902:    my $uhome=&homeserver($uname,$udomain);
                   2903: 
1.133     albertel 2904:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2905:    my @pairs=split(/\&/,$rep);
1.273     albertel 2906:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2907:      return @pairs;
                   2908:    }
1.15      www      2909:    my %returnhash=();
1.42      www      2910:    my $i=0;
1.191     harris41 2911:    foreach (@$storearr) {
1.557     albertel 2912:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2913:       $i++;
1.191     harris41 2914:    }
1.15      www      2915:    return %returnhash;
1.27      www      2916: }
                   2917: 
                   2918: # --------------------------------------------------------------- del interface
                   2919: 
                   2920: sub del {
1.133     albertel 2921:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2922:    my $items='';
1.191     harris41 2923:    foreach (@$storearr) {
1.27      www      2924:        $items.=escape($_).'&';
1.191     harris41 2925:    }
1.27      www      2926:    $items=~s/\&$//;
1.620     albertel 2927:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2928:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2929:    my $uhome=&homeserver($uname,$udomain);
                   2930: 
                   2931:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2932: }
                   2933: 
                   2934: # -------------------------------------------------------------- dump interface
                   2935: 
                   2936: sub dump {
1.755   ! albertel 2937:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
        !          2938:     if (!$udomain) { $udomain=$env{'user.domain'}; }
        !          2939:     if (!$uname) { $uname=$env{'user.name'}; }
        !          2940:     my $uhome=&homeserver($uname,$udomain);
        !          2941:     if ($regexp) {
        !          2942: 	$regexp=&escape($regexp);
        !          2943:     } else {
        !          2944: 	$regexp='.';
        !          2945:     }
        !          2946:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
        !          2947:     my @pairs=split(/\&/,$rep);
        !          2948:     my %returnhash=();
        !          2949:     foreach my $item (@pairs) {
        !          2950: 	my ($key,$value)=split(/=/,$item,2);
        !          2951: 	$key = &unescape($key);
        !          2952: 	next if ($key =~ /^error: 2 /);
        !          2953: 	$returnhash{$key}=&thaw_unescape($value);
        !          2954:     }
        !          2955:     return %returnhash;
1.407     www      2956: }
                   2957: 
1.717     albertel 2958: # --------------------------------------------------------- dumpstore interface
                   2959: 
                   2960: sub dumpstore {
                   2961:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2962:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2963: }
                   2964: 
1.407     www      2965: # -------------------------------------------------------------- keys interface
                   2966: 
                   2967: sub getkeys {
                   2968:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2969:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2970:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2971:    my $uhome=&homeserver($uname,$udomain);
                   2972:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2973:    my @keyarray=();
                   2974:    foreach (split(/\&/,$rep)) {
                   2975:       push (@keyarray,&unescape($_));
                   2976:    }
                   2977:    return @keyarray;
1.318     matthew  2978: }
                   2979: 
1.319     matthew  2980: # --------------------------------------------------------------- currentdump
                   2981: sub currentdump {
1.328     matthew  2982:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2983:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2984:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2985:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2986:    my $uhome = &homeserver($sname,$sdom);
                   2987:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2988:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2989:    #
1.318     matthew  2990:    my %returnhash=();
1.319     matthew  2991:    #
                   2992:    if ($rep eq "unknown_cmd") { 
                   2993:        # an old lond will not know currentdump
                   2994:        # Do a dump and make it look like a currentdump
1.326     matthew  2995:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2996:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2997:        my %hash = @tmp;
                   2998:        @tmp=();
1.424     matthew  2999:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3000:    } else {
                   3001:        my @pairs=split(/\&/,$rep);
                   3002:        foreach (@pairs) {
                   3003:            my ($key,$value)=split(/=/,$_);
                   3004:            my ($symb,$param) = split(/:/,$key);
                   3005:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3006:                                                         &thaw_unescape($value);
1.319     matthew  3007:        }
1.191     harris41 3008:    }
1.12      www      3009:    return %returnhash;
1.424     matthew  3010: }
                   3011: 
                   3012: sub convert_dump_to_currentdump{
                   3013:     my %hash = %{shift()};
                   3014:     my %returnhash;
                   3015:     # Code ripped from lond, essentially.  The only difference
                   3016:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3017:     # we might run in to problems with parameter names =~ /^v\./
                   3018:     while (my ($key,$value) = each(%hash)) {
                   3019:         my ($v,$symb,$param) = split(/:/,$key);
                   3020:         next if ($v eq 'version' || $symb eq 'keys');
                   3021:         next if (exists($returnhash{$symb}) &&
                   3022:                  exists($returnhash{$symb}->{$param}) &&
                   3023:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3024:         $returnhash{$symb}->{$param}=$value;
                   3025:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3026:     }
                   3027:     #
                   3028:     # Remove all of the keys in the hashes which keep track of
                   3029:     # the version of the parameter.
                   3030:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3031:         # use a foreach because we are going to delete from the hash.
                   3032:         foreach my $key (keys(%$param_hash)) {
                   3033:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3034:         }
                   3035:     }
                   3036:     return \%returnhash;
1.12      www      3037: }
                   3038: 
1.627     albertel 3039: # ------------------------------------------------------ critical inc interface
                   3040: 
                   3041: sub cinc {
                   3042:     return &inc(@_,'critical');
                   3043: }
                   3044: 
1.449     matthew  3045: # --------------------------------------------------------------- inc interface
                   3046: 
                   3047: sub inc {
1.627     albertel 3048:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3049:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3050:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3051:     my $uhome=&homeserver($uname,$udomain);
                   3052:     my $items='';
                   3053:     if (! ref($store)) {
                   3054:         # got a single value, so use that instead
                   3055:         $items = &escape($store).'=&';
                   3056:     } elsif (ref($store) eq 'SCALAR') {
                   3057:         $items = &escape($$store).'=&';        
                   3058:     } elsif (ref($store) eq 'ARRAY') {
                   3059:         $items = join('=&',map {&escape($_);} @{$store});
                   3060:     } elsif (ref($store) eq 'HASH') {
                   3061:         while (my($key,$value) = each(%{$store})) {
                   3062:             $items.= &escape($key).'='.&escape($value).'&';
                   3063:         }
                   3064:     }
                   3065:     $items=~s/\&$//;
1.627     albertel 3066:     if ($critical) {
                   3067: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3068:     } else {
                   3069: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3070:     }
1.449     matthew  3071: }
                   3072: 
1.12      www      3073: # --------------------------------------------------------------- put interface
                   3074: 
                   3075: sub put {
1.134     albertel 3076:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3077:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3078:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3079:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3080:    my $items='';
1.191     harris41 3081:    foreach (keys %$storehash) {
1.557     albertel 3082:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3083:    }
1.12      www      3084:    $items=~s/\&$//;
1.134     albertel 3085:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3086: }
                   3087: 
1.631     albertel 3088: # ------------------------------------------------------------ newput interface
                   3089: 
                   3090: sub newput {
                   3091:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3092:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3093:    if (!$uname) { $uname=$env{'user.name'}; }
                   3094:    my $uhome=&homeserver($uname,$udomain);
                   3095:    my $items='';
                   3096:    foreach my $key (keys(%$storehash)) {
                   3097:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3098:    }
                   3099:    $items=~s/\&$//;
                   3100:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3101: }
                   3102: 
                   3103: # ---------------------------------------------------------  putstore interface
                   3104: 
1.524     raeburn  3105: sub putstore {
1.715     albertel 3106:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3107:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3108:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3109:    my $uhome=&homeserver($uname,$udomain);
                   3110:    my $items='';
1.715     albertel 3111:    foreach my $key (keys(%$storehash)) {
                   3112:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3113:    }
1.715     albertel 3114:    $items=~s/\&$//;
1.716     albertel 3115:    my $esc_symb=&escape($symb);
                   3116:    my $esc_v=&escape($version);
1.715     albertel 3117:    my $reply =
1.716     albertel 3118:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3119: 	      $uhome);
                   3120:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3121:        # gfall back to way things use to be done
1.715     albertel 3122:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3123: 			    $uname);
1.524     raeburn  3124:    }
1.715     albertel 3125:    return $reply;
                   3126: }
                   3127: 
                   3128: sub old_putstore {
1.716     albertel 3129:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3130:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3131:     if (!$uname) { $uname=$env{'user.name'}; }
                   3132:     my $uhome=&homeserver($uname,$udomain);
                   3133:     my %newstorehash;
                   3134:     foreach (keys %$storehash) {
                   3135: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3136: 	$newstorehash{$key} = $storehash->{$_};
                   3137:     }
                   3138:     my $items='';
                   3139:     my %allitems = ();
                   3140:     foreach (keys %newstorehash) {
                   3141: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3142: 	    my $key = $1.':keys:'.$2;
                   3143: 	    $allitems{$key} .= $3.':';
                   3144: 	}
                   3145: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3146:     }
                   3147:     foreach (keys %allitems) {
                   3148: 	$allitems{$_} =~ s/\:$//;
                   3149: 	$items.= $_.'='.$allitems{$_}.'&';
                   3150:     }
                   3151:     $items=~s/\&$//;
                   3152:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3153: }
                   3154: 
1.47      www      3155: # ------------------------------------------------------ critical put interface
                   3156: 
                   3157: sub cput {
1.134     albertel 3158:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3159:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3160:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3161:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3162:    my $items='';
1.191     harris41 3163:    foreach (keys %$storehash) {
1.715     albertel 3164:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3165:    }
1.47      www      3166:    $items=~s/\&$//;
1.134     albertel 3167:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3168: }
                   3169: 
                   3170: # -------------------------------------------------------------- eget interface
                   3171: 
                   3172: sub eget {
1.133     albertel 3173:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3174:    my $items='';
1.191     harris41 3175:    foreach (@$storearr) {
1.12      www      3176:        $items.=escape($_).'&';
1.191     harris41 3177:    }
1.12      www      3178:    $items=~s/\&$//;
1.620     albertel 3179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3180:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3181:    my $uhome=&homeserver($uname,$udomain);
                   3182:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3183:    my @pairs=split(/\&/,$rep);
                   3184:    my %returnhash=();
1.42      www      3185:    my $i=0;
1.191     harris41 3186:    foreach (@$storearr) {
1.557     albertel 3187:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3188:       $i++;
1.191     harris41 3189:    }
1.12      www      3190:    return %returnhash;
                   3191: }
                   3192: 
1.667     albertel 3193: # ------------------------------------------------------------ tmpput interface
                   3194: sub tmpput {
                   3195:     my ($storehash,$server)=@_;
                   3196:     my $items='';
                   3197:     foreach (keys(%$storehash)) {
                   3198: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3199:     }
                   3200:     $items=~s/\&$//;
                   3201:     return &reply("tmpput:$items",$server);
                   3202: }
                   3203: 
                   3204: # ------------------------------------------------------------ tmpget interface
                   3205: sub tmpget {
1.688     albertel 3206:     my ($token,$server)=@_;
                   3207:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3208:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3209:     my %returnhash;
                   3210:     foreach my $item (split(/\&/,$rep)) {
                   3211: 	my ($key,$value)=split(/=/,$item);
                   3212: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3213:     }
                   3214:     return %returnhash;
                   3215: }
                   3216: 
1.688     albertel 3217: # ------------------------------------------------------------ tmpget interface
                   3218: sub tmpdel {
                   3219:     my ($token,$server)=@_;
                   3220:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3221:     return &reply("tmpdel:$token",$server);
                   3222: }
                   3223: 
1.341     www      3224: # ---------------------------------------------- Custom access rule evaluation
                   3225: 
                   3226: sub customaccess {
                   3227:     my ($priv,$uri)=@_;
1.620     albertel 3228:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3229:     $urealm=~s/^\W//;
                   3230:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3231:     my $access=0;
                   3232:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3233: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3234:         if ($role) {
                   3235: 	   if ($role ne $urole) { next; }
                   3236:         }
                   3237:         foreach (split(/\s*\,\s*/,$realm)) {
                   3238:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3239:             if ($tdom) {
                   3240: 		if ($tdom ne $udom) { next; }
                   3241:             }
                   3242:             if ($tcrs) {
                   3243: 		if ($tcrs ne $ucrs) { next; }
                   3244:             }
                   3245:             if ($tsec) {
                   3246: 		if ($tsec ne $usec) { next; }
                   3247:             }
                   3248:             $access=($effect eq 'allow');
                   3249:             last;
1.342     www      3250:         }
1.402     bowersj2 3251: 	if ($realm eq '' && $role eq '') {
                   3252:             $access=($effect eq 'allow');
                   3253: 	}
1.341     www      3254:     }
                   3255:     return $access;
                   3256: }
                   3257: 
1.103     harris41 3258: # ------------------------------------------------- Check for a user privilege
1.12      www      3259: 
                   3260: sub allowed {
1.579     albertel 3261:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3262:     my $ver_orguri=$uri;
1.439     www      3263:     $uri=&deversion($uri);
1.152     www      3264:     my $orguri=$uri;
1.52      www      3265:     $uri=&declutter($uri);
1.545     banghart 3266:     
1.620     albertel 3267:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3268: # Free bre access to adm and meta resources
1.529     albertel 3269:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3270: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3271: 	return 'F';
1.159     www      3272:     }
                   3273: 
1.545     banghart 3274: # Free bre access to user's own portfolio contents
1.714     raeburn  3275:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3276:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3277: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3278:         return 'F';
                   3279:     }
                   3280: 
1.714     raeburn  3281: # bre access to group if user has rgf priv for this group and course.
                   3282:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3283:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3284:         if (exists($env{'request.course.id'})) {
                   3285:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3286:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3287:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3288:                 my $courseprivid=$env{'request.course.id'};
                   3289:                 $courseprivid=~s/\_/\//;
                   3290:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3291:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3292:                     return $1; 
                   3293:                 }
                   3294:             }
                   3295:         }
                   3296:     }
                   3297: 
1.159     www      3298: # Free bre to public access
                   3299: 
                   3300:     if ($priv eq 'bre') {
1.238     www      3301:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3302: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3303:            return 'F'; 
                   3304:         }
1.238     www      3305:         if ($copyright eq 'priv') {
                   3306:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3307: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3308: 		return '';
                   3309:             }
                   3310:         }
                   3311:         if ($copyright eq 'domain') {
                   3312:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3313: 	    unless (($env{'user.domain'} eq $1) ||
                   3314:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3315: 		return '';
                   3316:             }
1.262     matthew  3317:         }
1.620     albertel 3318:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3319:             # Library role, so allow browsing of resources in this domain.
                   3320:             return 'F';
1.238     www      3321:         }
1.341     www      3322:         if ($copyright eq 'custom') {
                   3323: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3324:         }
1.14      www      3325:     }
1.264     matthew  3326:     # Domain coordinator is trying to create a course
1.620     albertel 3327:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3328:         # uri is the requested domain in this case.
                   3329:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3330:         # a role of dc for the domain in question.
1.620     albertel 3331:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3332:     }
1.29      www      3333: 
1.52      www      3334:     my $thisallowed='';
                   3335:     my $statecond=0;
                   3336:     my $courseprivid='';
                   3337: 
                   3338: # Course
                   3339: 
1.620     albertel 3340:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3341:        $thisallowed.=$1;
                   3342:     }
1.29      www      3343: 
1.52      www      3344: # Domain
                   3345: 
1.620     albertel 3346:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3347:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3348:        $thisallowed.=$1;
                   3349:     }
1.52      www      3350: 
                   3351: # Course: uri itself is a course
1.66      www      3352:     my $courseuri=$uri;
                   3353:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3354:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3355: 
1.620     albertel 3356:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3357:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3358:        $thisallowed.=$1;
                   3359:     }
1.29      www      3360: 
1.678     raeburn  3361: # Group: uri itself is a group
                   3362:     my $groupuri=$uri;
                   3363:     $groupuri=~s/^([^\/])/\/$1/;
                   3364:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3365:        =~/\Q$priv\E\&([^\:]*)/) {
                   3366:        $thisallowed.=$1;
                   3367:     }
                   3368: 
1.665     albertel 3369: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3370: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3371:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3372: 	$thisallowed='';
1.671     raeburn  3373:         my ($match)=&is_on_map($uri);
                   3374:         if ($match) {
                   3375:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3376:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3377:                 $thisallowed.=$1;
                   3378:             }
                   3379:         } else {
1.705     albertel 3380:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3381:             if ($refuri) {
                   3382:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3383:                     $thisallowed='F';
1.671     raeburn  3384:                 } else {
                   3385:                     $refuri=&declutter($refuri);
                   3386:                     my ($match) = &is_on_map($refuri);
                   3387:                     if ($match) {
                   3388:                         $thisallowed='F';
                   3389:                     }
1.669     raeburn  3390:                 }
1.671     raeburn  3391:             }
                   3392:         }
1.314     www      3393:     }
1.492     albertel 3394: 
1.52      www      3395: # Full access at system, domain or course-wide level? Exit.
1.29      www      3396: 
                   3397:     if ($thisallowed=~/F/) {
                   3398: 	return 'F';
                   3399:     }
                   3400: 
1.52      www      3401: # If this is generating or modifying users, exit with special codes
1.29      www      3402: 
1.643     www      3403:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3404: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3405: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3406: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3407: 	    unless ($auname) { return $thisallowed; }
                   3408: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3409: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3410: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3411: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3412: 	}
1.52      www      3413: 	return $thisallowed;
                   3414:     }
                   3415: #
1.103     harris41 3416: # Gathered so far: system, domain and course wide privileges
1.52      www      3417: #
                   3418: # Course: See if uri or referer is an individual resource that is part of 
                   3419: # the course
                   3420: 
1.620     albertel 3421:     if ($env{'request.course.id'}) {
1.232     www      3422: 
1.620     albertel 3423:        $courseprivid=$env{'request.course.id'};
                   3424:        if ($env{'request.course.sec'}) {
                   3425:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3426:        }
                   3427:        $courseprivid=~s/\_/\//;
                   3428:        my $checkreferer=1;
1.232     www      3429:        my ($match,$cond)=&is_on_map($uri);
                   3430:        if ($match) {
                   3431:            $statecond=$cond;
1.620     albertel 3432:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3433:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3434:                $thisallowed.=$1;
                   3435:                $checkreferer=0;
                   3436:            }
1.29      www      3437:        }
1.83      www      3438:        
1.148     www      3439:        if ($checkreferer) {
1.620     albertel 3440: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3441:             unless ($refuri) {
1.620     albertel 3442:                 foreach (keys %env) {
1.148     www      3443: 		    if ($_=~/^httpref\..*\*/) {
                   3444: 			my $pattern=$_;
1.156     www      3445:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3446:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3447:                         $pattern=~s/\//\\\//g;
1.152     www      3448:                         if ($orguri=~/$pattern/) {
1.620     albertel 3449: 			    $refuri=$env{$_};
1.148     www      3450:                         }
                   3451:                     }
1.191     harris41 3452:                 }
1.148     www      3453:             }
1.232     www      3454: 
1.148     www      3455:          if ($refuri) { 
1.152     www      3456: 	  $refuri=&declutter($refuri);
1.232     www      3457:           my ($match,$cond)=&is_on_map($refuri);
                   3458:             if ($match) {
                   3459:               my $refstatecond=$cond;
1.620     albertel 3460:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3461:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3462:                   $thisallowed.=$1;
1.53      www      3463:                   $uri=$refuri;
                   3464:                   $statecond=$refstatecond;
1.52      www      3465:               }
                   3466:           }
1.148     www      3467:         }
1.29      www      3468:        }
1.52      www      3469:    }
1.29      www      3470: 
1.52      www      3471: #
1.103     harris41 3472: # Gathered now: all privileges that could apply, and condition number
1.52      www      3473: # 
                   3474: #
                   3475: # Full or no access?
                   3476: #
1.29      www      3477: 
1.52      www      3478:     if ($thisallowed=~/F/) {
                   3479: 	return 'F';
                   3480:     }
1.29      www      3481: 
1.52      www      3482:     unless ($thisallowed) {
                   3483:         return '';
                   3484:     }
1.29      www      3485: 
1.52      www      3486: # Restrictions exist, deal with them
                   3487: #
                   3488: #   C:according to course preferences
                   3489: #   R:according to resource settings
                   3490: #   L:unless locked
                   3491: #   X:according to user session state
                   3492: #
                   3493: 
                   3494: # Possibly locked functionality, check all courses
1.54      www      3495: # Locks might take effect only after 10 minutes cache expiration for other
                   3496: # courses, and 2 minutes for current course
1.52      www      3497: 
                   3498:     my $envkey;
                   3499:     if ($thisallowed=~/L/) {
1.620     albertel 3500:         foreach $envkey (keys %env) {
1.54      www      3501:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3502:                my $courseid=$2;
                   3503:                my $roleid=$1.'.'.$2;
1.92      www      3504:                $courseid=~s/^\///;
1.54      www      3505:                my $expiretime=600;
1.620     albertel 3506:                if ($env{'request.role'} eq $roleid) {
1.54      www      3507: 		  $expiretime=120;
                   3508:                }
                   3509: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3510:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3511:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3512: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3513:                }
1.620     albertel 3514:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3515:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3516: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3517:                        &log($env{'user.domain'},$env{'user.name'},
                   3518:                             $env{'user.home'},
1.57      www      3519:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3520:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3521:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3522: 		       return '';
                   3523:                    }
                   3524:                }
1.620     albertel 3525:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3526:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3527: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3528:                        &log($env{'user.domain'},$env{'user.name'},
                   3529:                             $env{'user.home'},
1.57      www      3530:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3531:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3532:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3533: 		       return '';
                   3534:                    }
                   3535:                }
                   3536: 	   }
1.29      www      3537:        }
1.52      www      3538:     }
                   3539:    
                   3540: #
                   3541: # Rest of the restrictions depend on selected course
                   3542: #
                   3543: 
1.620     albertel 3544:     unless ($env{'request.course.id'}) {
1.52      www      3545:        return '1';
                   3546:     }
1.29      www      3547: 
1.52      www      3548: #
                   3549: # Now user is definitely in a course
                   3550: #
1.53      www      3551: 
                   3552: 
                   3553: # Course preferences
                   3554: 
                   3555:    if ($thisallowed=~/C/) {
1.620     albertel 3556:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3557:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3558:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3559: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3560: 	   if ($priv ne 'pch') { 
                   3561: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3562: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3563: 			$env{'request.course.id'});
                   3564: 	   }
1.237     www      3565:            return '';
                   3566:        }
                   3567: 
1.620     albertel 3568:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3569: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3570: 	   if ($priv ne 'pch') { 
                   3571: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3572: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3573: 			$env{'request.course.id'});
                   3574: 	   }
1.54      www      3575:            return '';
                   3576:        }
1.53      www      3577:    }
                   3578: 
                   3579: # Resource preferences
                   3580: 
                   3581:    if ($thisallowed=~/R/) {
1.620     albertel 3582:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3583:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3584: 	   if ($priv ne 'pch') { 
                   3585: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3586: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3587: 	   }
                   3588: 	   return '';
1.54      www      3589:        }
1.53      www      3590:    }
1.30      www      3591: 
1.246     www      3592: # Restricted by state or randomout?
1.30      www      3593: 
1.52      www      3594:    if ($thisallowed=~/X/) {
1.620     albertel 3595:       if ($env{'acc.randomout'}) {
1.579     albertel 3596: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3597:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3598:             return ''; 
                   3599:          }
1.247     www      3600:       }
                   3601:       if (&condval($statecond)) {
1.52      www      3602: 	 return '2';
                   3603:       } else {
                   3604:          return '';
                   3605:       }
                   3606:    }
1.30      www      3607: 
1.52      www      3608:    return 'F';
1.232     www      3609: }
                   3610: 
1.710     albertel 3611: sub split_uri_for_cond {
                   3612:     my $uri=&deversion(&declutter(shift));
                   3613:     my @uriparts=split(/\//,$uri);
                   3614:     my $filename=pop(@uriparts);
                   3615:     my $pathname=join('/',@uriparts);
                   3616:     return ($pathname,$filename);
                   3617: }
1.232     www      3618: # --------------------------------------------------- Is a resource on the map?
                   3619: 
                   3620: sub is_on_map {
1.710     albertel 3621:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3622:     #Trying to find the conditional for the file
1.620     albertel 3623:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3624: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3625:     if ($match) {
1.289     bowersj2 3626: 	return (1,$1);
                   3627:     } else {
1.434     www      3628: 	return (0,0);
1.289     bowersj2 3629:     }
1.12      www      3630: }
                   3631: 
1.427     www      3632: # --------------------------------------------------------- Get symb from alias
                   3633: 
                   3634: sub get_symb_from_alias {
                   3635:     my $symb=shift;
                   3636:     my ($map,$resid,$url)=&decode_symb($symb);
                   3637: # Already is a symb
                   3638:     if ($url) { return $symb; }
                   3639: # Must be an alias
                   3640:     my $aliassymb='';
                   3641:     my %bighash;
1.620     albertel 3642:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3643:                             &GDBM_READER(),0640)) {
                   3644:         my $rid=$bighash{'mapalias_'.$symb};
                   3645: 	if ($rid) {
                   3646: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3647: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3648: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3649: 	}
                   3650:         untie %bighash;
                   3651:     }
                   3652:     return $aliassymb;
                   3653: }
                   3654: 
1.12      www      3655: # ----------------------------------------------------------------- Define Role
                   3656: 
                   3657: sub definerole {
                   3658:   if (allowed('mcr','/')) {
                   3659:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3660:     foreach (split(':',$sysrole)) {
1.21      www      3661: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3662:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3663:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3664: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3665:                return "refused:s:$crole&$cqual"; 
                   3666:             }
                   3667:         }
1.191     harris41 3668:     }
1.392     www      3669:     foreach (split(':',$domrole)) {
1.21      www      3670: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3671:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3672:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3673: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3674:                return "refused:d:$crole&$cqual"; 
                   3675:             }
                   3676:         }
1.191     harris41 3677:     }
1.392     www      3678:     foreach (split(':',$courole)) {
1.21      www      3679: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3680:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3681:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3682: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3683:                return "refused:c:$crole&$cqual"; 
                   3684:             }
                   3685:         }
1.191     harris41 3686:     }
1.620     albertel 3687:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3688:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3689: 	        "rolesdef_$rolename=".
                   3690:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3691:     return reply($command,$env{'user.home'});
1.12      www      3692:   } else {
                   3693:     return 'refused';
                   3694:   }
1.105     harris41 3695: }
                   3696: 
                   3697: # ---------------- Make a metadata query against the network of library servers
                   3698: 
                   3699: sub metadata_query {
1.244     matthew  3700:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3701:     my %rhash;
1.244     matthew  3702:     my @server_list = (defined($server_array) ? @$server_array
                   3703:                                               : keys(%libserv) );
                   3704:     for my $server (@server_list) {
1.118     harris41 3705: 	unless ($custom or $customshow) {
                   3706: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3707: 	    $rhash{$server}=$reply;
                   3708: 	}
                   3709: 	else {
                   3710: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3711: 			     &escape($custom).':'.&escape($customshow),
                   3712: 			     $server);
                   3713: 	    $rhash{$server}=$reply;
                   3714: 	}
1.112     harris41 3715:     }
1.118     harris41 3716:     return \%rhash;
1.240     www      3717: }
                   3718: 
                   3719: # ----------------------------------------- Send log queries and wait for reply
                   3720: 
                   3721: sub log_query {
                   3722:     my ($uname,$udom,$query,%filters)=@_;
                   3723:     my $uhome=&homeserver($uname,$udom);
                   3724:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3725:     my $uhost=$hostname{$uhome};
1.241     www      3726:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3727:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3728:                        $uhome);
1.479     albertel 3729:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3730:     return get_query_reply($queryid);
                   3731: }
                   3732: 
1.508     raeburn  3733: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3734: 
                   3735: sub fetch_enrollment_query {
1.511     raeburn  3736:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3737:     my $homeserver;
1.547     raeburn  3738:     my $maxtries = 1;
1.508     raeburn  3739:     if ($context eq 'automated') {
                   3740:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3741:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3742:     } else {
                   3743:         $homeserver = &homeserver($cnum,$dom);
                   3744:     }
1.506     raeburn  3745:     my $host=$hostname{$homeserver};
                   3746:     my $cmd = '';
                   3747:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3748:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3749:     }
                   3750:     $cmd =~ s/%%$//;
                   3751:     $cmd = &escape($cmd);
                   3752:     my $query = 'fetchenrollment';
1.620     albertel 3753:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3754:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3755:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3756:         return 'error: '.$queryid;
                   3757:     }
1.506     raeburn  3758:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3759:     my $tries = 1;
                   3760:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3761:         $reply = &get_query_reply($queryid);
                   3762:         $tries ++;
                   3763:     }
1.526     raeburn  3764:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3765:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3766:     } else {
1.515     raeburn  3767:         my @responses = split/:/,$reply;
                   3768:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3769:             foreach (@responses) {
                   3770:                 my ($key,$value) = split/=/,$_;
                   3771:                 $$replyref{$key} = $value;
                   3772:             }
                   3773:         } else {
1.506     raeburn  3774:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3775:             foreach (@responses) {
                   3776:                 my ($key,$value) = split/=/,$_;
                   3777:                 $$replyref{$key} = $value;
                   3778:                 if ($value > 0) {
                   3779:                     foreach (@{$$affiliatesref{$key}}) {
                   3780:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3781:                         my $destname = $pathname.'/'.$filename;
                   3782:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3783:                         if ($xml_classlist =~ /^error/) {
                   3784:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3785:                         } else {
1.506     raeburn  3786:                             if ( open(FILE,">$destname") ) {
                   3787:                                 print FILE &unescape($xml_classlist);
                   3788:                                 close(FILE);
1.526     raeburn  3789:                             } else {
                   3790:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3791:                             }
                   3792:                         }
                   3793:                     }
                   3794:                 }
                   3795:             }
                   3796:         }
                   3797:         return 'ok';
                   3798:     }
                   3799:     return 'error';
                   3800: }
                   3801: 
1.242     www      3802: sub get_query_reply {
                   3803:     my $queryid=shift;
1.240     www      3804:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3805:     my $reply='';
                   3806:     for (1..100) {
                   3807: 	sleep 2;
                   3808:         if (-e $replyfile.'.end') {
1.448     albertel 3809: 	    if (open(my $fh,$replyfile)) {
1.240     www      3810:                $reply.=<$fh>;
1.448     albertel 3811:                close($fh);
1.240     www      3812: 	   } else { return 'error: reply_file_error'; }
1.242     www      3813:            return &unescape($reply);
                   3814: 	}
1.240     www      3815:     }
1.242     www      3816:     return 'timeout:'.$queryid;
1.240     www      3817: }
                   3818: 
                   3819: sub courselog_query {
1.241     www      3820: #
                   3821: # possible filters:
                   3822: # url: url or symb
                   3823: # username
                   3824: # domain
                   3825: # action: view, submit, grade
                   3826: # start: timestamp
                   3827: # end: timestamp
                   3828: #
1.240     www      3829:     my (%filters)=@_;
1.620     albertel 3830:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3831:     if ($filters{'url'}) {
                   3832: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3833:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3834:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3835:     }
1.620     albertel 3836:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3837:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3838:     return &log_query($cname,$cdom,'courselog',%filters);
                   3839: }
                   3840: 
                   3841: sub userlog_query {
                   3842:     my ($uname,$udom,%filters)=@_;
                   3843:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3844: }
                   3845: 
1.506     raeburn  3846: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3847: 
                   3848: sub auto_run {
1.508     raeburn  3849:     my ($cnum,$cdom) = @_;
                   3850:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3851:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3852:     return $response;
                   3853: }
                   3854:                                                                                    
                   3855: sub auto_get_sections {
1.508     raeburn  3856:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3857:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3858:     my @secs = ();
1.511     raeburn  3859:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3860:     unless ($response eq 'refused') {
                   3861:         @secs = split/:/,$response;
                   3862:     }
                   3863:     return @secs;
                   3864: }
                   3865:                                                                                    
                   3866: sub auto_new_course {
1.508     raeburn  3867:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3868:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3869:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3870:     return $response;
                   3871: }
                   3872:                                                                                    
                   3873: sub auto_validate_courseID {
1.508     raeburn  3874:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3875:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3876:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3877:     return $response;
                   3878: }
                   3879:                                                                                    
                   3880: sub auto_create_password {
1.508     raeburn  3881:     my ($cnum,$cdom,$authparam) = @_;
                   3882:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3883:     my $create_passwd = 0;
                   3884:     my $authchk = '';
1.511     raeburn  3885:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3886:     if ($response eq 'refused') {
                   3887:         $authchk = 'refused';
                   3888:     } else {
                   3889:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3890:     }
                   3891:     return ($authparam,$create_passwd,$authchk);
                   3892: }
                   3893: 
1.706     raeburn  3894: sub auto_photo_permission {
                   3895:     my ($cnum,$cdom,$students) = @_;
                   3896:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 3897:     my ($outcome,$perm_reqd,$conditions) = 
                   3898: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 3899:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3900: 	return (undef,undef);
                   3901:     }
1.706     raeburn  3902:     return ($outcome,$perm_reqd,$conditions);
                   3903: }
                   3904: 
                   3905: sub auto_checkphotos {
                   3906:     my ($uname,$udom,$pid) = @_;
                   3907:     my $homeserver = &homeserver($uname,$udom);
                   3908:     my ($result,$resulttype);
                   3909:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 3910: 				   &escape($uname).':'.&escape($pid),
                   3911: 				   $homeserver));
1.709     albertel 3912:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3913: 	return (undef,undef);
                   3914:     }
1.706     raeburn  3915:     if ($outcome) {
                   3916:         ($result,$resulttype) = split(/:/,$outcome);
                   3917:     } 
                   3918:     return ($result,$resulttype);
                   3919: }
                   3920: 
                   3921: sub auto_photochoice {
                   3922:     my ($cnum,$cdom) = @_;
                   3923:     my $homeserver = &homeserver($cnum,$cdom);
                   3924:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 3925: 						       &escape($cdom),
                   3926: 						       $homeserver)));
1.709     albertel 3927:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3928: 	return (undef,undef);
                   3929:     }
1.706     raeburn  3930:     return ($update,$comment);
                   3931: }
                   3932: 
                   3933: sub auto_photoupdate {
                   3934:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   3935:     my $homeserver = &homeserver($cnum,$dom);
                   3936:     my $host=$hostname{$homeserver};
                   3937:     my $cmd = '';
                   3938:     my $maxtries = 1;
                   3939:     foreach (keys %{$affiliatesref}) {
                   3940:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   3941:     }
                   3942:     $cmd =~ s/%%$//;
                   3943:     $cmd = &escape($cmd);
                   3944:     my $query = 'institutionalphotos';
                   3945:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   3946:     unless ($queryid=~/^\Q$host\E\_/) {
                   3947:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   3948:         return 'error: '.$queryid;
                   3949:     }
                   3950:     my $reply = &get_query_reply($queryid);
                   3951:     my $tries = 1;
                   3952:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3953:         $reply = &get_query_reply($queryid);
                   3954:         $tries ++;
                   3955:     }
                   3956:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   3957:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   3958:     } else {
                   3959:         my @responses = split(/:/,$reply);
                   3960:         my $outcome = shift(@responses); 
                   3961:         foreach my $item (@responses) {
                   3962:             my ($key,$value) = split(/=/,$item);
                   3963:             $$photo{$key} = $value;
                   3964:         }
                   3965:         return $outcome;
                   3966:     }
                   3967:     return 'error';
                   3968: }
                   3969: 
1.521     raeburn  3970: sub auto_instcode_format {
                   3971:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3972:     my $courses = '';
                   3973:     my $homeserver;
                   3974:     if ($caller eq 'global') {
1.584     raeburn  3975:         foreach my $tryserver (keys %libserv) {
                   3976:             if ($hostdom{$tryserver} eq $codedom) {
                   3977:                 $homeserver = $tryserver;
                   3978:                 last;
                   3979:             }
                   3980:         }
1.620     albertel 3981:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3982:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3983:         }
1.521     raeburn  3984:     } else {
                   3985:         $homeserver = &homeserver($caller,$codedom);
                   3986:     }
                   3987:     foreach (keys %{$instcodes}) {
                   3988:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3989:     }
                   3990:     chop($courses);
                   3991:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3992:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3993:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3994:         %{$codes} = &str2hash($codes_str);
                   3995:         @{$codetitles} = &str2array($codetitles_str);
                   3996:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3997:         %{$cat_order} = &str2hash($cat_order_str);
                   3998:         return 'ok';
                   3999:     }
                   4000:     return $response;
                   4001: }
                   4002: 
1.679     raeburn  4003: # ------------------------------------------------------- Course Group routines
                   4004: 
                   4005: sub get_coursegroups {
1.683     raeburn  4006:     my ($cdom,$cnum,$group) = @_;
                   4007:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4008: }
                   4009: 
                   4010: sub modify_coursegroup {
                   4011:     my ($cdom,$cnum,$groupsettings) = @_;
                   4012:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4013: }
                   4014: 
                   4015: sub modify_group_roles {
                   4016:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4017:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4018:     my $role = 'gr/'.&escape($userprivs);
                   4019:     my ($uname,$udom) = split(/:/,$user);
                   4020:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4021:     if ($result eq 'ok') {
                   4022:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4023:     }
1.679     raeburn  4024:     return $result;
                   4025: }
                   4026: 
                   4027: sub modify_coursegroup_membership {
                   4028:     my ($cdom,$cnum,$membership) = @_;
                   4029:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4030:     return $result;
                   4031: }
                   4032: 
1.682     raeburn  4033: sub get_active_groups {
                   4034:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4035:     my $now = time;
                   4036:     my %groups = ();
                   4037:     foreach my $key (keys(%env)) {
                   4038:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4039:             my ($start,$end) = split(/\./,$env{$key});
                   4040:             if (($end!=0) && ($end<$now)) { next; }
                   4041:             if (($start!=0) && ($start>$now)) { next; }
                   4042:             if ($1 eq $cdom && $2 eq $cnum) {
                   4043:                 $groups{$3} = $env{$key} ;
                   4044:             }
                   4045:         }
                   4046:     }
                   4047:     return %groups;
                   4048: }
                   4049: 
1.683     raeburn  4050: sub get_group_membership {
                   4051:     my ($cdom,$cnum,$group) = @_;
                   4052:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4053: }
                   4054: 
                   4055: sub get_users_groups {
                   4056:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4057:     my @usersgroups;
1.683     raeburn  4058:     my $cachetime=1800;
                   4059:     $courseid=~s/\_/\//g;
                   4060:     $courseid=~s/^(\w)/\/$1/;
                   4061: 
                   4062:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4063:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4064:     if (defined($cached)) {
1.734     albertel 4065:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4066:     } else {  
                   4067:         $grouplist = '';
                   4068:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4069:         my ($tmp) = keys(%roleshash);
                   4070:         if ($tmp=~/^error:/) {
                   4071:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4072:         } else {
                   4073:             my $access_end = $env{'course.'.$courseid.
                   4074:                                   '.default_enrollment_end_date'};
                   4075:             my $now = time;
1.734     albertel 4076:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4077:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4078:                     my $group = $1;
                   4079:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4080:                         my $start = $2;
                   4081:                         my $end = $1;
                   4082:                         if ($start == -1) { next; } # deleted from group
                   4083:                         if (($start!=0) && ($start>$now)) { next; }
                   4084:                         if (($end!=0) && ($end<$now)) {
                   4085:                             if ($access_end && $access_end < $now) {
                   4086:                                 if ($access_end - $end < 86400) {
                   4087:                                     push(@usersgroups,$group);
                   4088:                                 }
                   4089:                             }
                   4090:                             next;
                   4091:                         }
                   4092:                         push(@usersgroups,$group);
                   4093:                     }
1.683     raeburn  4094:                 }
                   4095:             }
1.733     raeburn  4096:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4097:             $grouplist = join(':',@usersgroups);
                   4098:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4099:         }
                   4100:     }
1.733     raeburn  4101:     return @usersgroups;
1.683     raeburn  4102: }
                   4103: 
                   4104: sub devalidate_getgroups_cache {
                   4105:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4106:     my $courseid = $cdom.'_'.$cnum;
                   4107:     $courseid=~s/\_/\//g;
                   4108:     $courseid=~s/^(\w)/\/$1/;
                   4109:     my $hashid="$udom:$uname:$courseid";
                   4110:     &devalidate_cache_new('getgroups',$hashid);
                   4111: }
                   4112: 
1.12      www      4113: # ------------------------------------------------------------------ Plain Text
                   4114: 
                   4115: sub plaintext {
1.742     raeburn  4116:     my ($short,$type,$cid) = @_;
                   4117:     if (!defined($cid)) {
                   4118:         $cid = $env{'request.course.id'};
                   4119:     }
                   4120:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4121:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4122:                                           '.plaintext'});
                   4123:     }
                   4124:     my %rolenames = (
                   4125:                       Course => 'std',
                   4126:                       Group => 'alt1',
                   4127:                     );
                   4128:     if (defined($type) && 
                   4129:          defined($rolenames{$type}) && 
                   4130:          defined($prp{$short}{$rolenames{$type}})) {
                   4131:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4132:     } else {
                   4133:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4134:     }
1.12      www      4135: }
                   4136: 
                   4137: # ----------------------------------------------------------------- Assign Role
                   4138: 
                   4139: sub assignrole {
1.357     www      4140:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4141:     my $mrole;
                   4142:     if ($role =~ /^cr\//) {
1.393     www      4143:         my $cwosec=$url;
                   4144:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4145: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4146:            &logthis('Refused custom assignrole: '.
                   4147:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4148: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4149:            return 'refused'; 
                   4150:         }
1.21      www      4151:         $mrole='cr';
1.678     raeburn  4152:     } elsif ($role =~ /^gr\//) {
                   4153:         my $cwogrp=$url;
                   4154:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4155:         unless (&allowed('mdg',$cwogrp)) {
                   4156:             &logthis('Refused group assignrole: '.
                   4157:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4158:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4159:             return 'refused';
                   4160:         }
                   4161:         $mrole='gr';
1.21      www      4162:     } else {
1.82      www      4163:         my $cwosec=$url;
1.83      www      4164:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4165:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4166:            &logthis('Refused assignrole: '.
                   4167:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4168: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4169:            return 'refused'; 
                   4170:         }
1.21      www      4171:         $mrole=$role;
                   4172:     }
1.620     albertel 4173:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4174:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4175:     if ($end) { $command.='_'.$end; }
1.21      www      4176:     if ($start) {
                   4177: 	if ($end) { 
1.81      www      4178:            $command.='_'.$start; 
1.21      www      4179:         } else {
1.81      www      4180:            $command.='_0_'.$start;
1.21      www      4181:         }
                   4182:     }
1.739     raeburn  4183:     my $origstart = $start;
                   4184:     my $origend = $end;
1.357     www      4185: # actually delete
                   4186:     if ($deleteflag) {
1.373     www      4187: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4188: # modify command to delete the role
1.620     albertel 4189:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4190:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4191: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4192: # set start and finish to negative values for userrolelog
                   4193:            $start=-1;
                   4194:            $end=-1;
                   4195:         }
                   4196:     }
                   4197: # send command
1.349     www      4198:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4199: # log new user role if status is ok
1.349     www      4200:     if ($answer eq 'ok') {
1.663     raeburn  4201: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4202: # for course roles, perform group memberships changes triggered by role change.
                   4203:         unless ($role =~ /^gr/) {
                   4204:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4205:                                              $origstart);
                   4206:         }
1.349     www      4207:     }
                   4208:     return $answer;
1.169     harris41 4209: }
                   4210: 
                   4211: # -------------------------------------------------- Modify user authentication
1.197     www      4212: # Overrides without validation
                   4213: 
1.169     harris41 4214: sub modifyuserauth {
                   4215:     my ($udom,$uname,$umode,$upass)=@_;
                   4216:     my $uhome=&homeserver($uname,$udom);
1.197     www      4217:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4218:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4219:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4220:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4221:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4222: 		     &escape($upass),$uhome);
1.620     albertel 4223:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4224:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4225:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4226:     &log($udom,,$uname,$uhome,
1.620     albertel 4227:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4228:                                      $env{'user.name'}.', '.$umode.
1.197     www      4229:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4230:     unless ($reply eq 'ok') {
1.197     www      4231:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4232: 	return 'error: '.$reply;
                   4233:     }   
1.170     harris41 4234:     return 'ok';
1.80      www      4235: }
                   4236: 
1.81      www      4237: # --------------------------------------------------------------- Modify a user
1.80      www      4238: 
1.81      www      4239: sub modifyuser {
1.206     matthew  4240:     my ($udom,    $uname, $uid,
                   4241:         $umode,   $upass, $first,
                   4242:         $middle,  $last,  $gene,
1.387     www      4243:         $forceid, $desiredhome, $email)=@_;
1.198     www      4244:     $udom=~s/\W//g;
                   4245:     $uname=~s/\W//g;
1.81      www      4246:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4247:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4248: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4249:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4250:                                      ' desiredhome not specified'). 
1.620     albertel 4251:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4252:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4253:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4254: # ----------------------------------------------------------------- Create User
1.406     albertel 4255:     if (($uhome eq 'no_host') && 
                   4256: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4257:         my $unhome='';
1.209     matthew  4258:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4259:             $unhome = $desiredhome;
1.620     albertel 4260: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4261: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4262:         } else { # load balancing routine for determining $unhome
1.80      www      4263:             my $tryserver;
1.81      www      4264:             my $loadm=10000000;
1.80      www      4265:             foreach $tryserver (keys %libserv) {
                   4266: 	       if ($hostdom{$tryserver} eq $udom) {
                   4267:                   my $answer=reply('load',$tryserver);
                   4268:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4269: 		      $loadm=$answer;
                   4270:                       $unhome=$tryserver;
                   4271:                   }
                   4272: 	       }
                   4273: 	    }
                   4274:         }
                   4275:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4276: 	    return 'error: unable to find a home server for '.$uname.
                   4277:                    ' in domain '.$udom;
1.80      www      4278:         }
                   4279:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4280:                          &escape($upass),$unhome);
                   4281: 	unless ($reply eq 'ok') {
                   4282:             return 'error: '.$reply;
                   4283:         }   
1.230     stredwic 4284:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4285:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4286: 	    return 'error: unable verify users home machine.';
1.80      www      4287:         }
1.209     matthew  4288:     }   # End of creation of new user
1.80      www      4289: # ---------------------------------------------------------------------- Add ID
                   4290:     if ($uid) {
                   4291:        $uid=~tr/A-Z/a-z/;
                   4292:        my %uidhash=&idrget($udom,$uname);
1.196     www      4293:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4294:          && (!$forceid)) {
1.80      www      4295: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4296: 	      return 'error: user id "'.$uid.'" does not match '.
                   4297:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4298:           }
                   4299:        } else {
                   4300: 	  &idput($udom,($uname => $uid));
                   4301:        }
                   4302:     }
                   4303: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4304:     my @tmp=&get('environment',
1.134     albertel 4305: 		   ['firstname','middlename','lastname','generation'],
                   4306: 		   $udom,$uname);
1.313     matthew  4307:     my %names;
                   4308:     if ($tmp[0] =~ m/^error:.*/) { 
                   4309:         %names=(); 
                   4310:     } else {
                   4311:         %names = @tmp;
                   4312:     }
1.388     www      4313: #
                   4314: # Make sure to not trash student environment if instructor does not bother
                   4315: # to supply name and email information
                   4316: #
                   4317:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4318:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4319:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4320:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4321:     if ($email) {
                   4322:        $email=~s/[^\w\@\.\-\,]//gs;
                   4323:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4324: 			   $names{'critnotification'} = $email;
                   4325: 			   $names{'permanentemail'} = $email; }
                   4326:     }
1.134     albertel 4327:     my $reply = &put('environment', \%names, $udom,$uname);
                   4328:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4329:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4330:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4331:              $umode.', '.$first.', '.$middle.', '.
                   4332: 	     $last.', '.$gene.' by '.
1.620     albertel 4333:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4334:     return 'ok';
1.80      www      4335: }
                   4336: 
1.81      www      4337: # -------------------------------------------------------------- Modify student
1.80      www      4338: 
1.81      www      4339: sub modifystudent {
                   4340:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4341:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4342:     if (!$cid) {
1.620     albertel 4343: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4344: 	    return 'not_in_class';
                   4345: 	}
1.80      www      4346:     }
                   4347: # --------------------------------------------------------------- Make the user
1.81      www      4348:     my $reply=&modifyuser
1.209     matthew  4349: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4350:          $desiredhome,$email);
1.80      www      4351:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4352:     # This will cause &modify_student_enrollment to get the uid from the
                   4353:     # students environment
                   4354:     $uid = undef if (!$forceid);
1.455     albertel 4355:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4356: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4357:     return $reply;
                   4358: }
                   4359: 
                   4360: sub modify_student_enrollment {
1.515     raeburn  4361:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4362:     my ($cdom,$cnum,$chome);
                   4363:     if (!$cid) {
1.620     albertel 4364: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4365: 	    return 'not_in_class';
                   4366: 	}
1.620     albertel 4367: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4368: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4369:     } else {
                   4370: 	($cdom,$cnum)=split(/_/,$cid);
                   4371:     }
1.620     albertel 4372:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4373:     if (!$chome) {
1.457     raeburn  4374: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4375:     }
1.455     albertel 4376:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4377:     # Make sure the user exists
1.81      www      4378:     my $uhome=&homeserver($uname,$udom);
                   4379:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4380: 	return 'error: no such user';
                   4381:     }
1.297     matthew  4382:     # Get student data if we were not given enough information
                   4383:     if (!defined($first)  || $first  eq '' || 
                   4384:         !defined($last)   || $last   eq '' || 
                   4385:         !defined($uid)    || $uid    eq '' || 
                   4386:         !defined($middle) || $middle eq '' || 
                   4387:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4388:         # They did not supply us with enough data to enroll the student, so
                   4389:         # we need to pick up more information.
1.297     matthew  4390:         my %tmp = &get('environment',
1.294     matthew  4391:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4392:                        ,$udom,$uname);
                   4393: 
1.455     albertel 4394:         #foreach (keys(%tmp)) {
                   4395:         #    &logthis("key $_ = ".$tmp{$_});
                   4396:         #}
1.294     matthew  4397:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4398:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4399:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4400:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4401:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4402:     }
1.556     albertel 4403:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4404:     my $reply=cput('classlist',
                   4405: 		   {"$uname:$udom" => 
1.515     raeburn  4406: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4407: 		   $cdom,$cnum);
1.81      www      4408:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4409: 	return 'error: '.$reply;
1.652     albertel 4410:     } else {
                   4411: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4412:     }
1.297     matthew  4413:     # Add student role to user
1.83      www      4414:     my $uurl='/'.$cid;
1.81      www      4415:     $uurl=~s/\_/\//g;
                   4416:     if ($usec) {
                   4417: 	$uurl.='/'.$usec;
                   4418:     }
                   4419:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4420: }
                   4421: 
1.556     albertel 4422: sub format_name {
                   4423:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4424:     my $name;
                   4425:     if ($first ne 'lastname') {
                   4426: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4427:     } else {
                   4428: 	if ($lastname=~/\S/) {
                   4429: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4430: 	    $name=~s/\s+,/,/;
                   4431: 	} else {
                   4432: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4433: 	}
                   4434:     }
                   4435:     $name=~s/^\s+//;
                   4436:     $name=~s/\s+$//;
                   4437:     $name=~s/\s+/ /g;
                   4438:     return $name;
                   4439: }
                   4440: 
1.84      www      4441: # ------------------------------------------------- Write to course preferences
                   4442: 
                   4443: sub writecoursepref {
                   4444:     my ($courseid,%prefs)=@_;
                   4445:     $courseid=~s/^\///;
                   4446:     $courseid=~s/\_/\//g;
                   4447:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4448:     my $chome=homeserver($cnum,$cdomain);
                   4449:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4450: 	return 'error: no such course';
                   4451:     }
                   4452:     my $cstring='';
1.191     harris41 4453:     foreach (keys %prefs) {
1.84      www      4454: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4455:     }
1.84      www      4456:     $cstring=~s/\&$//;
                   4457:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4458: }
                   4459: 
                   4460: # ---------------------------------------------------------- Make/modify course
                   4461: 
                   4462: sub createcourse {
1.741     raeburn  4463:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4464:         $course_owner,$crstype)=@_;
1.84      www      4465:     $url=&declutter($url);
                   4466:     my $cid='';
1.264     matthew  4467:     unless (&allowed('ccc',$udom)) {
1.84      www      4468:         return 'refused';
                   4469:     }
                   4470: # ------------------------------------------------------------------- Create ID
1.674     www      4471:    my $uname=int(1+rand(9)).
                   4472:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4473:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4474:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4475: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4476:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4477:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4478:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4479:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4480:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4481:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4482:            return 'error: unable to generate unique course-ID';
                   4483:        } 
                   4484:    }
1.264     matthew  4485: # ------------------------------------------------ Check supplied server name
1.620     albertel 4486:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4487:     if (! exists($libserv{$course_server})) {
                   4488:         return 'error:bad server name '.$course_server;
                   4489:     }
1.84      www      4490: # ------------------------------------------------------------- Make the course
                   4491:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4492:                       $course_server);
1.84      www      4493:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4494:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4495:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4496: 	return 'error: no such course';
                   4497:     }
1.271     www      4498: # ----------------------------------------------------------------- Course made
1.516     raeburn  4499: # log existence
                   4500:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4501:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4502:                   &escape($crstype),$uhome);
1.358     www      4503:     &flushcourselogs();
                   4504: # set toplevel url
1.271     www      4505:     my $topurl=$url;
                   4506:     unless ($nonstandard) {
                   4507: # ------------------------------------------ For standard courses, make top url
                   4508:         my $mapurl=&clutter($url);
1.278     www      4509:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4510:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4511: <map>
                   4512: <resource id="1" type="start"></resource>
                   4513: <resource id="2" src="$mapurl"></resource>
                   4514: <resource id="3" type="finish"></resource>
                   4515: <link index="1" from="1" to="2"></link>
                   4516: <link index="2" from="2" to="3"></link>
                   4517: </map>
                   4518: ENDINITMAP
                   4519:         $topurl=&declutter(
1.638     albertel 4520:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4521:                           );
                   4522:     }
                   4523: # ----------------------------------------------------------- Write preferences
1.84      www      4524:     &writecoursepref($udom.'_'.$uname,
                   4525:                      ('description' => $description,
1.271     www      4526:                       'url'         => $topurl));
1.84      www      4527:     return '/'.$udom.'/'.$uname;
                   4528: }
                   4529: 
1.21      www      4530: # ---------------------------------------------------------- Assign Custom Role
                   4531: 
                   4532: sub assigncustomrole {
1.357     www      4533:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4534:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4535:                        $end,$start,$deleteflag);
1.21      www      4536: }
                   4537: 
                   4538: # ----------------------------------------------------------------- Revoke Role
                   4539: 
                   4540: sub revokerole {
1.357     www      4541:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4542:     my $now=time;
1.357     www      4543:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4544: }
                   4545: 
                   4546: # ---------------------------------------------------------- Revoke Custom Role
                   4547: 
                   4548: sub revokecustomrole {
1.357     www      4549:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4550:     my $now=time;
1.357     www      4551:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4552:            $deleteflag);
1.17      www      4553: }
                   4554: 
1.533     banghart 4555: # ------------------------------------------------------------ Disk usage
1.535     albertel 4556: sub diskusage {
1.533     banghart 4557:     my ($udom,$uname,$directoryRoot)=@_;
                   4558:     $directoryRoot =~ s/\/$//;
1.535     albertel 4559:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4560:     return $listing;
1.512     banghart 4561: }
                   4562: 
1.566     banghart 4563: sub is_locked {
                   4564:     my ($file_name, $domain, $user) = @_;
                   4565:     my @check;
                   4566:     my $is_locked;
                   4567:     push @check, $file_name;
1.613     albertel 4568:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4569: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4570:     my ($tmp)=keys(%locked);
                   4571:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4572:     
1.566     banghart 4573:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4574:         $is_locked = 'false';
                   4575:         foreach my $entry (@{$locked{$file_name}}) {
                   4576:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4577:                $is_locked = 'true';
                   4578:                last;
1.745     raeburn  4579:            }
                   4580:        }
1.566     banghart 4581:     } else {
                   4582:         $is_locked = 'false';
                   4583:     }
                   4584: }
                   4585: 
1.559     banghart 4586: # ------------------------------------------------------------- Mark as Read Only
                   4587: 
                   4588: sub mark_as_readonly {
                   4589:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4590:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4591:     my ($tmp)=keys(%current_permissions);
                   4592:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4593:     foreach my $file (@{$files}) {
1.561     banghart 4594:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4595:     }
1.613     albertel 4596:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4597:     return;
                   4598: }
                   4599: 
1.572     banghart 4600: # ------------------------------------------------------------Save Selected Files
                   4601: 
                   4602: sub save_selected_files {
                   4603:     my ($user, $path, @files) = @_;
                   4604:     my $filename = $user."savedfiles";
1.573     banghart 4605:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4606:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4607:     foreach my $file (@files) {
1.620     albertel 4608:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4609:     }
                   4610:     foreach my $file (@other_files) {
1.574     banghart 4611:         print (OUT $file."\n");
1.572     banghart 4612:     }
1.574     banghart 4613:     close (OUT);
1.572     banghart 4614:     return 'ok';
                   4615: }
                   4616: 
1.574     banghart 4617: sub clear_selected_files {
                   4618:     my ($user) = @_;
                   4619:     my $filename = $user."savedfiles";
                   4620:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4621:     print (OUT undef);
                   4622:     close (OUT);
                   4623:     return ("ok");    
                   4624: }
                   4625: 
1.572     banghart 4626: sub files_in_path {
                   4627:     my ($user, $path) = @_;
                   4628:     my $filename = $user."savedfiles";
                   4629:     my %return_files;
1.574     banghart 4630:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4631:     while (my $line_in = <IN>) {
1.574     banghart 4632:         chomp ($line_in);
                   4633:         my @paths_and_file = split (m!/!, $line_in);
                   4634:         my $file_part = pop (@paths_and_file);
                   4635:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4636:         $path_part.='/';
                   4637:         my $path_and_file = $path_part.$file_part;
                   4638:         if ($path_part eq $path) {
                   4639:             $return_files{$file_part}= 'selected';
                   4640:         }
                   4641:     }
1.574     banghart 4642:     close (IN);
                   4643:     return (\%return_files);
1.572     banghart 4644: }
                   4645: 
                   4646: # called in portfolio select mode, to show files selected NOT in current directory
                   4647: sub files_not_in_path {
                   4648:     my ($user, $path) = @_;
                   4649:     my $filename = $user."savedfiles";
                   4650:     my @return_files;
                   4651:     my $path_part;
1.574     banghart 4652:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4653:     while (<IN>) {
                   4654:         #ok, I know it's clunky, but I want it to work
                   4655:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4656:         my $file_part = pop (@paths_and_file);
                   4657:         chomp ($file_part);
                   4658:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4659:         $path_part .= '/';
                   4660:         my $path_and_file = $path_part.$file_part;
                   4661:         if ($path_part ne $path) {
1.574     banghart 4662:             push (@return_files, ($path_and_file));
1.572     banghart 4663:         }
                   4664:     }
1.574     banghart 4665:     close (OUT);
                   4666:     return (@return_files);
1.572     banghart 4667: }
                   4668: 
1.745     raeburn  4669: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4670: 
1.745     raeburn  4671: sub get_portfile_permissions {
                   4672:     my ($domain,$user) = @_;
1.613     albertel 4673:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4674:     my ($tmp)=keys(%current_permissions);
                   4675:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4676:     return \%current_permissions;
                   4677: }
                   4678: 
                   4679: #---------------------------------------------Get portfolio file access controls
                   4680: 
1.749     raeburn  4681: sub get_access_controls {
1.745     raeburn  4682:     my ($current_permissions,$group,$file) = @_;
                   4683:     my %access; 
                   4684:     if (defined($file)) {
1.749     raeburn  4685:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4686:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
                   4687:                 $access{$file}{$control} = $$current_permissions{$file."\0".$control};
                   4688:             }
                   4689:         }
1.745     raeburn  4690:     } else {
1.749     raeburn  4691:         foreach my $key (keys(%{$current_permissions})) {
                   4692:             if ($key =~ /\0accesscontrol$/) {
                   4693:                 if (defined($group)) {
                   4694:                     if ($key !~ m-^\Q$group\E/-) {
                   4695:                         next;
                   4696:                     }
                   4697:                 }
                   4698:                 my ($fullpath) = split(/\0/,$key);
                   4699:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4700:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4701:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4702:                     }
                   4703:                 }
                   4704:             }
                   4705:         }
                   4706:     }
                   4707:     return %access;
                   4708: }
                   4709: 
                   4710: sub parse_access_controls {
                   4711:     my ($access_item) = @_;
                   4712:     my %content;
1.752     raeburn  4713:     my $role_id;
                   4714:     my $user;
                   4715:     my $usercount;
1.749     raeburn  4716:     my $token;
                   4717:     my $parser=HTML::TokeParser->new(\$access_item);
                   4718:     while ($token=$parser->get_token) {
                   4719:         if ($token->[0] eq 'S')  {
                   4720:             my $entry=$token->[1];
                   4721:             if ($entry eq 'scope') {
                   4722:                 my $type = $token->[2]{'type'};
1.752     raeburn  4723:                 if (($type eq 'course') || ($type eq 'group')) {
1.753     albertel 4724:                     $content{'roles'} = {};
1.752     raeburn  4725:                 }
                   4726:             } elsif ($entry eq 'roles') {
                   4727:                 $role_id = $token->[2]{id};
1.754     albertel 4728: 		$content{$entry}{$role_id} = {
1.753     albertel 4729: 		                                 role => [],
1.752     raeburn  4730:                                                  access => [],
                   4731:                                                  section => [],
                   4732:                                                  group => [],
1.754     albertel 4733:                                              };
1.752     raeburn  4734:             } elsif ($entry eq 'users') {
1.753     albertel 4735:                 $content{'users'} = {};
1.752     raeburn  4736:                 $usercount = 0;
                   4737:             } elsif ($entry eq 'user') {
                   4738:                 $user = '';
1.749     raeburn  4739:             } else {
                   4740:                 my $value=$parser->get_text('/'.$entry);
1.752     raeburn  4741:                 if ($entry eq 'uname') {
                   4742:                     $user = $value;
                   4743:                 } elsif ($entry eq 'udom') {
                   4744:                     $user .= ':'.$value;
                   4745:                     $content{'users'}{$user} = $usercount;
                   4746:                 } elsif ($entry eq 'role' ||
                   4747:                     $entry eq 'access' ||
                   4748:                     $entry eq 'section' ||
                   4749:                     $entry eq 'group') {
                   4750:                     if ($role_id ne '') {
                   4751:                         push(@{$content{'roles'}{$role_id}{$entry}},$value);
                   4752:                     }
                   4753:                 } elsif ($entry eq 'dom') {
                   4754:                     push(@{$content{$entry}},$value);
                   4755:                 } else {
                   4756:                     $content{$entry}=$value;
                   4757:                 }
                   4758:             }
                   4759:         } elsif ($token->[0] eq 'E') {
                   4760:             if ($token->[1] eq 'user') {
                   4761:                 $user = '';
                   4762:                 $usercount ++;
                   4763:             } elsif ($token->[1] eq 'roles') {
                   4764:                 $role_id = '';
1.749     raeburn  4765:             }
                   4766:         }
1.745     raeburn  4767:     }
1.749     raeburn  4768:     return %content;
                   4769: }
                   4770: 
                   4771: sub modify_access_controls {
                   4772:     my ($file_name,$changes,$domain,$user)=@_;
                   4773:     my ($outcome,$deloutcome);
                   4774:     my %store_permissions;
                   4775:     my %new_values;
                   4776:     my %new_control;
                   4777:     my %translation;
                   4778:     my @deletions = ();
                   4779:     my $now = time;
                   4780:     if (exists($$changes{'activate'})) {
                   4781:         if (ref($$changes{'activate'}) eq 'HASH') {
                   4782:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   4783:             my $numnew = scalar(@newitems);
                   4784:             for (my $i=0; $i<$numnew; $i++) {
                   4785:                 my $newkey = $newitems[$i];
                   4786:                 my $newid = &Apache::loncommon::get_cgi_id();
                   4787:                 $newkey =~ s/^(\d+)/$newid/;
                   4788:                 $translation{$1} = $newid;
                   4789:                 $new_values{$file_name."\0".$newkey} = 
                   4790:                                           $$changes{'activate'}{$newitems[$i]};
                   4791:                 $new_control{$newkey} = $now;
                   4792:             }
                   4793:         }
                   4794:     }
                   4795:     my %todelete;
                   4796:     my %changed_items;
                   4797:     foreach my $action ('delete','update') {
                   4798:         if (exists($$changes{$action})) {
                   4799:             if (ref($$changes{$action}) eq 'HASH') {
                   4800:                 foreach my $key (keys(%{$$changes{$action}})) {
                   4801:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   4802:                     if ($action eq 'delete') { 
                   4803:                         $todelete{$itemnum} = 1;
                   4804:                     } else {
                   4805:                         $changed_items{$itemnum} = $key;
                   4806:                     }
                   4807:                 }
1.745     raeburn  4808:             }
                   4809:         }
1.749     raeburn  4810:     }
                   4811:     # get lock on access controls for file.
                   4812:     my $lockhash = {
                   4813:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   4814:                                                        ':'.$env{'user.domain'},
                   4815:                    }; 
                   4816:     my $tries = 0;
                   4817:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   4818:    
                   4819:     while (($gotlock ne 'ok') && $tries <3) {
                   4820:         $tries ++;
                   4821:         sleep 1;
                   4822:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   4823:     }
                   4824:     if ($gotlock eq 'ok') {
                   4825:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   4826:         my ($tmp)=keys(%curr_permissions);
                   4827:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   4828:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   4829:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   4830:             if (ref($curr_controls) eq 'HASH') {
                   4831:                 foreach my $control_item (keys(%{$curr_controls})) {
                   4832:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   4833:                     if (defined($todelete{$itemnum})) {
                   4834:                         push(@deletions,$file_name."\0".$control_item);
                   4835:                     } else {
                   4836:                         if (defined($changed_items{$itemnum})) {
                   4837:                             $new_control{$changed_items{$itemnum}} = $now;
                   4838:                             push(@deletions,$file_name."\0".$control_item);
                   4839:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   4840:                         } else {
                   4841:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   4842:                         }
                   4843:                     }
1.745     raeburn  4844:                 }
                   4845:             }
                   4846:         }
1.749     raeburn  4847:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   4848:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   4849:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   4850:         #  remove lock
                   4851:         my @del_lock = ($file_name."\0".'locked_access_records');
                   4852:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   4853:     } else {
                   4854:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  4855:     }
1.749     raeburn  4856:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  4857: }
                   4858: 
                   4859: #------------------------------------------------------Get Marked as Read Only
                   4860: 
                   4861: sub get_marked_as_readonly {
                   4862:     my ($domain,$user,$what,$group) = @_;
                   4863:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 4864:     my @readonly_files;
1.629     banghart 4865:     my $cmp1=$what;
                   4866:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  4867:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   4868:         if (defined($group)) {
                   4869:             if ($file_name !~ m-^\Q$group\E/-) {
                   4870:                 next;
                   4871:             }
                   4872:         }
1.561     banghart 4873:         if (ref($value) eq "ARRAY"){
                   4874:             foreach my $stored_what (@{$value}) {
1.629     banghart 4875:                 my $cmp2=$stored_what;
1.749     raeburn  4876:                 if (ref($stored_what eq 'ARRAY')) {
1.746     raeburn  4877:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  4878:                 }
1.629     banghart 4879:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4880:                     push(@readonly_files, $file_name);
1.745     raeburn  4881:                     last;
1.563     banghart 4882:                 } elsif (!defined($what)) {
                   4883:                     push(@readonly_files, $file_name);
1.745     raeburn  4884:                     last;
1.561     banghart 4885:                 }
                   4886:             }
1.745     raeburn  4887:         }
1.561     banghart 4888:     }
                   4889:     return @readonly_files;
                   4890: }
1.577     banghart 4891: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4892: 
1.577     banghart 4893: sub get_marked_as_readonly_hash {
1.745     raeburn  4894:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 4895:     my %readonly_files;
1.745     raeburn  4896:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   4897:         if (defined($group)) {
                   4898:             if ($file_name !~ m-^\Q$group\E/-) {
                   4899:                 next;
                   4900:             }
                   4901:         }
1.577     banghart 4902:         if (ref($value) eq "ARRAY"){
                   4903:             foreach my $stored_what (@{$value}) {
1.745     raeburn  4904:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 4905:                     foreach my $lock_descriptor(@{$stored_what}) {
                   4906:                         if ($lock_descriptor eq 'graded') {
                   4907:                             $readonly_files{$file_name} = 'graded';
                   4908:                         } elsif ($lock_descriptor eq 'handback') {
                   4909:                             $readonly_files{$file_name} = 'handback';
                   4910:                         } else {
                   4911:                             if (!exists($readonly_files{$file_name})) {
                   4912:                                 $readonly_files{$file_name} = 'locked';
                   4913:                             }
                   4914:                         }
1.745     raeburn  4915:                     }
1.750     banghart 4916:                 } 
1.577     banghart 4917:             }
                   4918:         } 
                   4919:     }
                   4920:     return %readonly_files;
                   4921: }
1.559     banghart 4922: # ------------------------------------------------------------ Unmark as Read Only
                   4923: 
                   4924: sub unmark_as_readonly {
1.629     banghart 4925:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4926:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  4927:     my ($domain,$user,$what,$file_name,$group) = @_;
1.634     albertel 4928:     my $symb_crs = $what;
                   4929:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  4930:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 4931:     my ($tmp)=keys(%current_permissions);
                   4932:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4933:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 4934:     foreach my $file (@readonly_files) {
                   4935: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4936: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4937:         my @new_locks;
                   4938:         my @del_keys;
                   4939:         if (ref($current_locks) eq "ARRAY"){
                   4940:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4941:                 my $compare=$locker;
1.749     raeburn  4942:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  4943:                     $compare=join('',@{$locker});
1.746     raeburn  4944:                     if ($compare ne $symb_crs) {
                   4945:                         push(@new_locks, $locker);
                   4946:                     }
1.563     banghart 4947:                 }
                   4948:             }
1.650     albertel 4949:             if (scalar(@new_locks) > 0) {
1.563     banghart 4950:                 $current_permissions{$file} = \@new_locks;
                   4951:             } else {
                   4952:                 push(@del_keys, $file);
1.613     albertel 4953:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4954:                 delete($current_permissions{$file});
1.563     banghart 4955:             }
                   4956:         }
1.561     banghart 4957:     }
1.613     albertel 4958:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4959:     return;
                   4960: }
1.512     banghart 4961: 
1.17      www      4962: # ------------------------------------------------------------ Directory lister
                   4963: 
                   4964: sub dirlist {
1.253     stredwic 4965:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4966: 
1.18      www      4967:     $uri=~s/^\///;
                   4968:     $uri=~s/\/$//;
1.253     stredwic 4969:     my ($udom, $uname);
                   4970:     (undef,$udom,$uname)=split(/\//,$uri);
                   4971:     if(defined($userdomain)) {
                   4972:         $udom = $userdomain;
                   4973:     }
                   4974:     if(defined($username)) {
                   4975:         $uname = $username;
                   4976:     }
                   4977: 
                   4978:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4979:     if(defined($alternateDirectoryRoot)) {
                   4980:         $dirRoot = $alternateDirectoryRoot;
                   4981:         $dirRoot =~ s/\/$//;
1.751     banghart 4982:     }
1.253     stredwic 4983: 
                   4984:     if($udom) {
                   4985:         if($uname) {
1.605     matthew  4986:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4987:                               homeserver($uname,$udom));
1.605     matthew  4988:             my @listing_results;
                   4989:             if ($listing eq 'unknown_cmd') {
                   4990:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4991:                                homeserver($uname,$udom));
                   4992:                 @listing_results = split(/:/,$listing);
                   4993:             } else {
                   4994:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4995:             }
                   4996:             return @listing_results;
1.253     stredwic 4997:         } elsif(!defined($alternateDirectoryRoot)) {
                   4998:             my $tryserver;
                   4999:             my %allusers=();
                   5000:             foreach $tryserver (keys %libserv) {
                   5001:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5002:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5003:                                       $udom, $tryserver);
1.605     matthew  5004:                     my @listing_results;
                   5005:                     if ($listing eq 'unknown_cmd') {
                   5006:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5007:                                        $udom, $tryserver);
                   5008:                         @listing_results = split(/:/,$listing);
                   5009:                     } else {
                   5010:                         @listing_results =
                   5011:                             map { &unescape($_); } split(/:/,$listing);
                   5012:                     }
                   5013:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5014:                         $listing_results[0] ne 'empty'       &&
                   5015:                         $listing_results[0] ne 'con_lost') {
                   5016:                         foreach (@listing_results) {
1.253     stredwic 5017:                             my ($entry,@stat)=split(/&/,$_);
                   5018:                             $allusers{$entry}=1;
                   5019:                         }
                   5020:                     }
1.191     harris41 5021:                 }
1.253     stredwic 5022:             }
                   5023:             my $alluserstr='';
                   5024:             foreach (sort keys %allusers) {
                   5025:                 $alluserstr.=$_.'&user:';
                   5026:             }
                   5027:             $alluserstr=~s/:$//;
                   5028:             return split(/:/,$alluserstr);
                   5029:         } else {
                   5030:             my @emptyResults = ();
                   5031:             push(@emptyResults, 'missing user name');
                   5032:             return split(':',@emptyResults);
                   5033:         }
                   5034:     } elsif(!defined($alternateDirectoryRoot)) {
                   5035:         my $tryserver;
                   5036:         my %alldom=();
                   5037:         foreach $tryserver (keys %libserv) {
                   5038:             $alldom{$hostdom{$tryserver}}=1;
                   5039:         }
                   5040:         my $alldomstr='';
                   5041:         foreach (sort keys %alldom) {
1.397     albertel 5042:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5043:         }
                   5044:         $alldomstr=~s/:$//;
                   5045:         return split(/:/,$alldomstr);       
                   5046:     } else {
                   5047:         my @emptyResults = ();
                   5048:         push(@emptyResults, 'missing domain');
                   5049:         return split(':',@emptyResults);
1.275     stredwic 5050:     }
                   5051: }
                   5052: 
                   5053: # --------------------------------------------- GetFileTimestamp
                   5054: # This function utilizes dirlist and returns the date stamp for
                   5055: # when it was last modified.  It will also return an error of -1
                   5056: # if an error occurs
                   5057: 
1.410     matthew  5058: ##
                   5059: ## FIXME: This subroutine assumes its caller knows something about the
                   5060: ## directory structure of the home server for the student ($root).
                   5061: ## Not a good assumption to make.  Since this is for looking up files
                   5062: ## in user directories, the full path should be constructed by lond, not
                   5063: ## whatever machine we request data from.
                   5064: ##
1.275     stredwic 5065: sub GetFileTimestamp {
                   5066:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5067:     $studentDomain=~s/\W//g;
                   5068:     $studentName=~s/\W//g;
                   5069:     my $subdir=$studentName.'__';
                   5070:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5071:     my $proname="$studentDomain/$subdir/$studentName";
                   5072:     $proname .= '/'.$filename;
1.375     matthew  5073:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5074:                                               $studentName, $root);
1.275     stredwic 5075:     my @stats = split('&', $fileStat);
                   5076:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5077:         # @stats contains first the filename, then the stat output
                   5078:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5079:     } else {
                   5080:         return -1;
1.253     stredwic 5081:     }
1.26      www      5082: }
                   5083: 
1.712     albertel 5084: sub stat_file {
                   5085:     my ($uri) = @_;
1.722     albertel 5086:     $uri = &clutter($uri);
                   5087: 
                   5088:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 5089:     if ($uri =~ m-^/adm/-) {
                   5090: 	$uri=~s-^/adm/wrapper/-/-;
                   5091: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 5092:     }
1.712     albertel 5093:     my ($udom,$uname,$file,$dir);
                   5094:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5095: 	($udom,$uname,$file) =
                   5096: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5097: 	$file = 'userfiles/'.$file;
1.740     www      5098: 	$dir = &propath($udom,$uname);
1.712     albertel 5099:     }
                   5100:     if ($uri =~ m-^/res/-) {
                   5101: 	($udom,$uname) = 
                   5102: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5103: 	$file = $uri;
                   5104:     }
                   5105: 
                   5106:     if (!$udom || !$uname || !$file) {
                   5107: 	# unable to handle the uri
                   5108: 	return ();
                   5109:     }
                   5110: 
                   5111:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5112:     my @stats = split('&', $result);
1.721     banghart 5113:     
1.712     albertel 5114:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5115: 	shift(@stats); #filename is first
                   5116: 	return @stats;
                   5117:     }
                   5118:     return ();
                   5119: }
                   5120: 
1.26      www      5121: # -------------------------------------------------------- Value of a Condition
                   5122: 
1.713     albertel 5123: # gets the value of a specific preevaluated condition
                   5124: #    stored in the string  $env{user.state.<cid>}
                   5125: # or looks up a condition reference in the bighash and if if hasn't
                   5126: # already been evaluated recurses into docondval to get the value of
                   5127: # the condition, then memoizing it to 
                   5128: #   $env{user.state.<cid>.<condition>}
1.40      www      5129: sub directcondval {
                   5130:     my $number=shift;
1.620     albertel 5131:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5132: 	&Apache::lonuserstate::evalstate();
                   5133:     }
1.713     albertel 5134:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5135: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5136:     } elsif ($number =~ /^_/) {
                   5137: 	my $sub_condition;
                   5138: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5139: 		&GDBM_READER(),0640)) {
                   5140: 	    $sub_condition=$bighash{'conditions'.$number};
                   5141: 	    untie(%bighash);
                   5142: 	}
                   5143: 	my $value = &docondval($sub_condition);
                   5144: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5145: 	return $value;
                   5146:     }
1.620     albertel 5147:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5148:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5149:     } else {
                   5150:        return 2;
                   5151:     }
                   5152: }
                   5153: 
1.713     albertel 5154: # get the collection of conditions for this resource
1.26      www      5155: sub condval {
                   5156:     my $condidx=shift;
1.54      www      5157:     my $allpathcond='';
1.713     albertel 5158:     foreach my $cond (split(/\|/,$condidx)) {
                   5159: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5160: 	    $allpathcond.=
                   5161: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5162: 	}
1.191     harris41 5163:     }
1.54      www      5164:     $allpathcond=~s/\|$//;
1.713     albertel 5165:     return &docondval($allpathcond);
                   5166: }
                   5167: 
                   5168: #evaluates an expression of conditions
                   5169: sub docondval {
                   5170:     my ($allpathcond) = @_;
                   5171:     my $result=0;
                   5172:     if ($env{'request.course.id'}
                   5173: 	&& defined($allpathcond)) {
                   5174: 	my $operand='|';
                   5175: 	my @stack;
                   5176: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5177: 	    if ($chunk eq '(') {
                   5178: 		push @stack,($operand,$result);
                   5179: 	    } elsif ($chunk eq ')') {
                   5180: 		my $before=pop @stack;
                   5181: 		if (pop @stack eq '&') {
                   5182: 		    $result=$result>$before?$before:$result;
                   5183: 		} else {
                   5184: 		    $result=$result>$before?$result:$before;
                   5185: 		}
                   5186: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5187: 		$operand=$chunk;
                   5188: 	    } else {
                   5189: 		my $new=directcondval($chunk);
                   5190: 		if ($operand eq '&') {
                   5191: 		    $result=$result>$new?$new:$result;
                   5192: 		} else {
                   5193: 		    $result=$result>$new?$result:$new;
                   5194: 		}
                   5195: 	    }
                   5196: 	}
1.26      www      5197:     }
                   5198:     return $result;
1.421     albertel 5199: }
                   5200: 
                   5201: # ---------------------------------------------------- Devalidate courseresdata
                   5202: 
                   5203: sub devalidatecourseresdata {
                   5204:     my ($coursenum,$coursedomain)=@_;
                   5205:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5206:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5207: }
                   5208: 
1.200     www      5209: # --------------------------------------------------- Course Resourcedata Query
                   5210: 
1.624     albertel 5211: sub get_courseresdata {
                   5212:     my ($coursenum,$coursedomain)=@_;
1.200     www      5213:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5214:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5215:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5216:     my %dumpreply;
1.417     albertel 5217:     unless (defined($cached)) {
1.624     albertel 5218: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5219: 	$result=\%dumpreply;
1.251     albertel 5220: 	my ($tmp) = keys(%dumpreply);
                   5221: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5222: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5223: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5224: 	    return $tmp;
1.416     albertel 5225: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5226: 	    $result=undef;
1.599     albertel 5227: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5228: 	}
                   5229:     }
1.624     albertel 5230:     return $result;
                   5231: }
                   5232: 
1.633     albertel 5233: sub devalidateuserresdata {
                   5234:     my ($uname,$udom)=@_;
                   5235:     my $hashid="$udom:$uname";
                   5236:     &devalidate_cache_new('userres',$hashid);
                   5237: }
                   5238: 
1.624     albertel 5239: sub get_userresdata {
                   5240:     my ($uname,$udom)=@_;
                   5241:     #most student don\'t have any data set, check if there is some data
                   5242:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5243: 
                   5244:     my $hashid="$udom:$uname";
                   5245:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5246:     if (!defined($cached)) {
                   5247: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5248: 	$result=\%resourcedata;
                   5249: 	&do_cache_new('userres',$hashid,$result,600);
                   5250:     }
                   5251:     my ($tmp)=keys(%$result);
                   5252:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5253: 	return $result;
                   5254:     }
                   5255:     #error 2 occurs when the .db doesn't exist
                   5256:     if ($tmp!~/error: 2 /) {
1.672     albertel 5257: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5258: 		 " Trying to get resource data for ".
                   5259: 		 $uname." at ".$udom.": ".
                   5260: 		 $tmp."</font>");
                   5261:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5262: 	#&EXT_cache_set($udom,$uname);
                   5263: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5264: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5265:     }
                   5266:     return $tmp;
                   5267: }
                   5268: 
                   5269: sub resdata {
                   5270:     my ($name,$domain,$type,@which)=@_;
                   5271:     my $result;
                   5272:     if ($type eq 'course') {
                   5273: 	$result=&get_courseresdata($name,$domain);
                   5274:     } elsif ($type eq 'user') {
                   5275: 	$result=&get_userresdata($name,$domain);
                   5276:     }
                   5277:     if (!ref($result)) { return $result; }    
1.251     albertel 5278:     foreach my $item (@which) {
1.417     albertel 5279: 	if (defined($result->{$item})) {
                   5280: 	    return $result->{$item};
1.251     albertel 5281: 	}
1.250     albertel 5282:     }
1.291     albertel 5283:     return undef;
1.200     www      5284: }
                   5285: 
1.379     matthew  5286: #
                   5287: # EXT resource caching routines
                   5288: #
                   5289: 
                   5290: sub clear_EXT_cache_status {
1.383     albertel 5291:     &delenv('cache.EXT.');
1.379     matthew  5292: }
                   5293: 
                   5294: sub EXT_cache_status {
                   5295:     my ($target_domain,$target_user) = @_;
1.383     albertel 5296:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5297:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5298:         # We know already the user has no data
                   5299:         return 1;
                   5300:     } else {
                   5301:         return 0;
                   5302:     }
                   5303: }
                   5304: 
                   5305: sub EXT_cache_set {
                   5306:     my ($target_domain,$target_user) = @_;
1.383     albertel 5307:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5308:     #&appenv($cachename => time);
1.379     matthew  5309: }
                   5310: 
1.28      www      5311: # --------------------------------------------------------- Value of a Variable
1.58      www      5312: sub EXT {
1.715     albertel 5313: 
1.395     albertel 5314:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5315:     unless ($varname) { return ''; }
1.218     albertel 5316:     #get real user name/domain, courseid and symb
                   5317:     my $courseid;
1.359     albertel 5318:     my $publicuser;
1.427     www      5319:     if ($symbparm) {
                   5320: 	$symbparm=&get_symb_from_alias($symbparm);
                   5321:     }
1.218     albertel 5322:     if (!($uname && $udom)) {
1.360     albertel 5323:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5324: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5325:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5326:     } else {
1.620     albertel 5327: 	$courseid=$env{'request.course.id'};
1.218     albertel 5328:     }
1.48      www      5329:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5330:     my $rest;
1.320     albertel 5331:     if (defined($therest[0])) {
1.48      www      5332:        $rest=join('.',@therest);
                   5333:     } else {
                   5334:        $rest='';
                   5335:     }
1.320     albertel 5336: 
1.57      www      5337:     my $qualifierrest=$qualifier;
                   5338:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5339:     my $spacequalifierrest=$space;
                   5340:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5341:     if ($realm eq 'user') {
1.48      www      5342: # --------------------------------------------------------------- user.resource
                   5343: 	if ($space eq 'resource') {
1.651     albertel 5344: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5345: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5346: 		 &&
1.744     albertel 5347: 		 ($symbparm eq &symbread()) ) {	
                   5348: 		# if we are in the middle of processing the resource the
                   5349: 		# get the value we are planning on committing
                   5350:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5351:                     return $Apache::lonhomework::results{$qualifierrest};
                   5352:                 } else {
                   5353:                     return $Apache::lonhomework::history{$qualifierrest};
                   5354:                 }
1.335     albertel 5355: 	    } else {
1.359     albertel 5356: 		my %restored;
1.620     albertel 5357: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5358: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5359: 		} else {
                   5360: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5361: 		}
1.335     albertel 5362: 		return $restored{$qualifierrest};
                   5363: 	    }
1.48      www      5364: # ----------------------------------------------------------------- user.access
                   5365:         } elsif ($space eq 'access') {
1.218     albertel 5366: 	    # FIXME - not supporting calls for a specific user
1.48      www      5367:             return &allowed($qualifier,$rest);
                   5368: # ------------------------------------------ user.preferences, user.environment
                   5369:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5370: 	    if (($uname eq $env{'user.name'}) &&
                   5371: 		($udom eq $env{'user.domain'})) {
                   5372: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5373: 	    } else {
1.359     albertel 5374: 		my %returnhash;
                   5375: 		if (!$publicuser) {
                   5376: 		    %returnhash=&userenvironment($udom,$uname,
                   5377: 						 $qualifierrest);
                   5378: 		}
1.218     albertel 5379: 		return $returnhash{$qualifierrest};
                   5380: 	    }
1.48      www      5381: # ----------------------------------------------------------------- user.course
                   5382:         } elsif ($space eq 'course') {
1.218     albertel 5383: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5384:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5385: # ------------------------------------------------------------------- user.role
                   5386:         } elsif ($space eq 'role') {
1.218     albertel 5387: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5388:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5389:             if ($qualifier eq 'value') {
                   5390: 		return $role;
                   5391:             } elsif ($qualifier eq 'extent') {
                   5392:                 return $where;
                   5393:             }
                   5394: # ----------------------------------------------------------------- user.domain
                   5395:         } elsif ($space eq 'domain') {
1.218     albertel 5396:             return $udom;
1.48      www      5397: # ------------------------------------------------------------------- user.name
                   5398:         } elsif ($space eq 'name') {
1.218     albertel 5399:             return $uname;
1.48      www      5400: # ---------------------------------------------------- Any other user namespace
1.29      www      5401:         } else {
1.359     albertel 5402: 	    my %reply;
                   5403: 	    if (!$publicuser) {
                   5404: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5405: 	    }
                   5406: 	    return $reply{$qualifierrest};
1.48      www      5407:         }
1.236     www      5408:     } elsif ($realm eq 'query') {
                   5409: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5410:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5411: 						[$spacequalifierrest]);
1.620     albertel 5412: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5413:    } elsif ($realm eq 'request') {
1.48      www      5414: # ------------------------------------------------------------- request.browser
                   5415:         if ($space eq 'browser') {
1.430     www      5416: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5417: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5418: 		    return 1;
                   5419: 		} else {
                   5420: 		    return 0;
                   5421: 		}
                   5422: 	    } else {
1.620     albertel 5423: 		return $env{'browser.'.$qualifier};
1.430     www      5424: 	    }
1.57      www      5425: # ------------------------------------------------------------ request.filename
                   5426:         } else {
1.620     albertel 5427:             return $env{'request.'.$spacequalifierrest};
1.29      www      5428:         }
1.28      www      5429:     } elsif ($realm eq 'course') {
1.48      www      5430: # ---------------------------------------------------------- course.description
1.620     albertel 5431:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5432:     } elsif ($realm eq 'resource') {
1.165     www      5433: 
1.620     albertel 5434: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5435: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5436: 	}
1.693     albertel 5437: 
                   5438: 	if ($space eq 'title') {
                   5439: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5440: 	    return &gettitle($symbparm);
                   5441: 	}
                   5442: 	
                   5443: 	if ($space eq 'map') {
                   5444: 	    my ($map) = &decode_symb($symbparm);
                   5445: 	    return &symbread($map);
                   5446: 	}
                   5447: 
                   5448: 	my ($section, $group, @groups);
1.593     albertel 5449: 	my ($courselevelm,$courselevel);
1.539     albertel 5450: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5451: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5452: 
1.218     albertel 5453: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5454: 
1.60      www      5455: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5456: 	    my $symbp=$symbparm;
1.735     albertel 5457: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5458: 
                   5459: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5460: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5461: 
1.620     albertel 5462: 	    if (($env{'user.name'} eq $uname) &&
                   5463: 		($env{'user.domain'} eq $udom)) {
                   5464: 		$section=$env{'request.course.sec'};
1.733     raeburn  5465:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5466:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5467: 	    } else {
1.539     albertel 5468: 		if (! defined($usection)) {
1.551     albertel 5469: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5470: 		} else {
                   5471: 		    $section = $usection;
                   5472: 		}
1.733     raeburn  5473:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5474: 	    }
                   5475: 
                   5476: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5477: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5478: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5479: 
1.593     albertel 5480: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5481: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5482: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5483: 
1.60      www      5484: # ----------------------------------------------------------- first, check user
1.624     albertel 5485: 
                   5486: 	    my $userreply=&resdata($uname,$udom,'user',
                   5487: 				       ($courselevelr,$courselevelm,
                   5488: 					$courselevel));
                   5489: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5490: 
1.594     albertel 5491: # ------------------------------------------------ second, check some of course
1.684     raeburn  5492:             my $coursereply;
1.691     raeburn  5493:             if (@groups > 0) {
                   5494:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5495:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5496:                 if (defined($coursereply)) { return $coursereply; }
                   5497:             }
1.96      www      5498: 
1.684     raeburn  5499: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5500: 				     $env{'course.'.$courseid.'.domain'},
                   5501: 				     'course',
                   5502: 				     ($seclevelr,$seclevelm,$seclevel,
                   5503: 				      $courselevelr));
1.287     albertel 5504: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5505: 
1.60      www      5506: # ------------------------------------------------------ third, check map parms
1.218     albertel 5507: 	    my %parmhash=();
                   5508: 	    my $thisparm='';
                   5509: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5510: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5511: 		    &GDBM_READER(),0640)) {
1.218     albertel 5512: 		$thisparm=$parmhash{$symbparm};
                   5513: 		untie(%parmhash);
                   5514: 	    }
                   5515: 	    if ($thisparm) { return $thisparm; }
                   5516: 	}
1.594     albertel 5517: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5518: 
1.218     albertel 5519: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5520: 	my $filename;
                   5521: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5522: 	if ($symbparm) {
1.409     www      5523: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5524: 	} else {
1.620     albertel 5525: 	    $filename=$env{'request.filename'};
1.282     albertel 5526: 	}
                   5527: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5528: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5529: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5530: 	if (defined($metadata)) { return $metadata; }
1.142     www      5531: 
1.594     albertel 5532: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5533: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5534: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5535: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5536: 				     $env{'course.'.$courseid.'.domain'},
                   5537: 				     'course',
                   5538: 				     ($courselevelm,$courselevel));
1.593     albertel 5539: 	    if (defined($coursereply)) { return $coursereply; }
                   5540: 	}
1.145     www      5541: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5542: 	unless ($space eq '0') {
1.336     albertel 5543: 	    my @parts=split(/_/,$space);
                   5544: 	    my $id=pop(@parts);
                   5545: 	    my $part=join('_',@parts);
                   5546: 	    if ($part eq '') { $part='0'; }
                   5547: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5548: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5549: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5550: 	}
1.395     albertel 5551: 	if ($recurse) { return undef; }
                   5552: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5553: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5554: 
1.48      www      5555: # ---------------------------------------------------- Any other user namespace
                   5556:     } elsif ($realm eq 'environment') {
                   5557: # ----------------------------------------------------------------- environment
1.620     albertel 5558: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5559: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5560: 	} else {
                   5561: 	    my %returnhash=&userenvironment($udom,$uname,
                   5562: 					    $spacequalifierrest);
                   5563: 	    return $returnhash{$spacequalifierrest};
                   5564: 	}
1.28      www      5565:     } elsif ($realm eq 'system') {
1.48      www      5566: # ----------------------------------------------------------------- system.time
                   5567: 	if ($space eq 'time') {
                   5568: 	    return time;
                   5569:         }
1.696     albertel 5570:     } elsif ($realm eq 'server') {
                   5571: # ----------------------------------------------------------------- system.time
                   5572: 	if ($space eq 'name') {
                   5573: 	    return $ENV{'SERVER_NAME'};
                   5574:         }
1.28      www      5575:     }
1.48      www      5576:     return '';
1.61      www      5577: }
                   5578: 
1.691     raeburn  5579: sub check_group_parms {
                   5580:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5581:     my @groupitems = ();
                   5582:     my $resultitem;
                   5583:     my @levels = ($symbparm,$mapparm,$what);
                   5584:     foreach my $group (@{$groups}) {
                   5585:         foreach my $level (@levels) {
                   5586:              my $item = $courseid.'.['.$group.'].'.$level;
                   5587:              push(@groupitems,$item);
                   5588:         }
                   5589:     }
                   5590:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5591:                             $env{'course.'.$courseid.'.domain'},
                   5592:                                      'course',@groupitems);
                   5593:     return $coursereply;
                   5594: }
                   5595: 
                   5596: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5597:     my ($courseid,@groups) = @_;
                   5598:     @groups = sort(@groups);
1.691     raeburn  5599:     return @groups;
                   5600: }
                   5601: 
1.395     albertel 5602: sub packages_tab_default {
                   5603:     my ($uri,$varname)=@_;
                   5604:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5605: 
                   5606:     my (@extension,@specifics,$do_default);
                   5607:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5608: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5609: 	if ($pack_type eq 'default') {
                   5610: 	    $do_default=1;
                   5611: 	} elsif ($pack_type eq 'extension') {
                   5612: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5613: 	} else {
                   5614: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5615: 	}
                   5616:     }
                   5617:     # first look for a package that matches the requested part id
                   5618:     foreach my $package (@specifics) {
                   5619: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5620: 	next if ($pack_part ne $part);
                   5621: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5622: 	    return $packagetab{"$pack_type&$name&default"};
                   5623: 	}
                   5624:     }
                   5625:     # look for any possible matching non extension_ package
                   5626:     foreach my $package (@specifics) {
                   5627: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5628: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5629: 	    return $packagetab{"$pack_type&$name&default"};
                   5630: 	}
1.585     albertel 5631: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5632: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5633: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5634: 	}
                   5635:     }
1.738     albertel 5636:     # look for any posible extension_ match
                   5637:     foreach my $package (@extension) {
                   5638: 	my ($package,$pack_type)=@{$package};
                   5639: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5640: 	    return $packagetab{"$pack_type&$name&default"};
                   5641: 	}
                   5642: 	if (defined($packagetab{$package."&$name&default"})) {
                   5643: 	    return $packagetab{$package."&$name&default"};
                   5644: 	}
                   5645:     }
                   5646:     # look for a global default setting
                   5647:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5648: 	return $packagetab{"default&$name&default"};
                   5649:     }
1.395     albertel 5650:     return undef;
                   5651: }
                   5652: 
1.334     albertel 5653: sub add_prefix_and_part {
                   5654:     my ($prefix,$part)=@_;
                   5655:     my $keyroot;
                   5656:     if (defined($prefix) && $prefix !~ /^__/) {
                   5657: 	# prefix that has a part already
                   5658: 	$keyroot=$prefix;
                   5659:     } elsif (defined($prefix)) {
                   5660: 	# prefix that is missing a part
                   5661: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5662:     } else {
                   5663: 	# no prefix at all
                   5664: 	if (defined($part)) { $keyroot='_'.$part; }
                   5665:     }
                   5666:     return $keyroot;
                   5667: }
                   5668: 
1.71      www      5669: # ---------------------------------------------------------------- Get metadata
                   5670: 
1.599     albertel 5671: my %metaentry;
1.71      www      5672: sub metadata {
1.176     www      5673:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5674:     $uri=&declutter($uri);
1.288     albertel 5675:     # if it is a non metadata possible uri return quickly
1.529     albertel 5676:     if (($uri eq '') || 
                   5677: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5678: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5679:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5680: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5681: 	return undef;
1.288     albertel 5682:     }
1.73      www      5683:     my $filename=$uri;
                   5684:     $uri=~s/\.meta$//;
1.172     www      5685: #
                   5686: # Is the metadata already cached?
1.177     www      5687: # Look at timestamp of caching
1.172     www      5688: # Everything is cached by the main uri, libraries are never directly cached
                   5689: #
1.428     albertel 5690:     if (!defined($liburi)) {
1.599     albertel 5691: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5692: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5693:     }
                   5694:     {
1.172     www      5695: #
                   5696: # Is this a recursive call for a library?
                   5697: #
1.599     albertel 5698: #	if (! exists($metacache{$uri})) {
                   5699: #	    $metacache{$uri}={};
                   5700: #	}
1.171     www      5701:         if ($liburi) {
                   5702: 	    $liburi=&declutter($liburi);
                   5703:             $filename=$liburi;
1.401     bowersj2 5704:         } else {
1.599     albertel 5705: 	    &devalidate_cache_new('meta',$uri);
                   5706: 	    undef(%metaentry);
1.401     bowersj2 5707: 	}
1.140     www      5708:         my %metathesekeys=();
1.73      www      5709:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5710: 	my $metastring;
1.609     banghart 5711: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 5712: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5713: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5714: 	    $metastring=&getfile($file);
1.489     albertel 5715: 	}
1.208     albertel 5716:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5717:         my $token;
1.140     www      5718:         undef %metathesekeys;
1.71      www      5719:         while ($token=$parser->get_token) {
1.339     albertel 5720: 	    if ($token->[0] eq 'S') {
                   5721: 		if (defined($token->[2]->{'package'})) {
1.172     www      5722: #
                   5723: # This is a package - get package info
                   5724: #
1.339     albertel 5725: 		    my $package=$token->[2]->{'package'};
                   5726: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5727: 		    if (defined($token->[2]->{'id'})) { 
                   5728: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5729: 		    }
1.599     albertel 5730: 		    if ($metaentry{':packages'}) {
                   5731: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5732: 		    } else {
1.599     albertel 5733: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5734: 		    }
1.736     albertel 5735: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5736: 			my $part=$keyroot;
                   5737: 			$part=~s/^\_//;
1.736     albertel 5738: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5739: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5740: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5741: 			    # ignore package.tab specified default values
                   5742:                             # here &package_tab_default() will fetch those
                   5743: 			    if ($subp eq 'default') { next; }
1.736     albertel 5744: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5745: 			    my $unikey;
                   5746: 			    if ($pack =~ /_0$/) {
                   5747: 				$unikey='parameter_0_'.$name;
                   5748: 				$part=0;
                   5749: 			    } else {
                   5750: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5751: 			    }
1.339     albertel 5752: 			    if ($subp eq 'display') {
                   5753: 				$value.=' [Part: '.$part.']';
                   5754: 			    }
1.599     albertel 5755: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5756: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5757: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5758: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5759: 			    }
1.599     albertel 5760: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5761: 				$metaentry{':'.$unikey}=
                   5762: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5763: 			    }
1.339     albertel 5764: 			}
                   5765: 		    }
                   5766: 		} else {
1.172     www      5767: #
                   5768: # This is not a package - some other kind of start tag
1.339     albertel 5769: #
                   5770: 		    my $entry=$token->[1];
                   5771: 		    my $unikey;
                   5772: 		    if ($entry eq 'import') {
                   5773: 			$unikey='';
                   5774: 		    } else {
                   5775: 			$unikey=$entry;
                   5776: 		    }
                   5777: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5778: 
                   5779: 		    if (defined($token->[2]->{'id'})) { 
                   5780: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5781: 		    }
1.175     www      5782: 
1.339     albertel 5783: 		    if ($entry eq 'import') {
1.175     www      5784: #
                   5785: # Importing a library here
1.339     albertel 5786: #
                   5787: 			if ($depthcount<20) {
                   5788: 			    my $location=$parser->get_text('/import');
                   5789: 			    my $dir=$filename;
                   5790: 			    $dir=~s|[^/]*$||;
                   5791: 			    $location=&filelocation($dir,$location);
1.736     albertel 5792: 			    my $metadata = 
                   5793: 				&metadata($uri,'keys', $location,$unikey,
                   5794: 					  $depthcount+1);
                   5795: 			    foreach my $meta (split(',',$metadata)) {
                   5796: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   5797: 				$metathesekeys{$meta}=1;
1.339     albertel 5798: 			    }
                   5799: 			}
                   5800: 		    } else { 
                   5801: 			
                   5802: 			if (defined($token->[2]->{'name'})) { 
                   5803: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5804: 			}
                   5805: 			$metathesekeys{$unikey}=1;
1.736     albertel 5806: 			foreach my $param (@{$token->[3]}) {
                   5807: 			    $metaentry{':'.$unikey.'.'.$param} =
                   5808: 				$token->[2]->{$param};
1.339     albertel 5809: 			}
                   5810: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5811: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5812: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5813: 		 # only ws inside the tag, and not in default, so use default
                   5814: 		 # as value
1.599     albertel 5815: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5816: 			} else {
1.321     albertel 5817: 		  # either something interesting inside the tag or default
                   5818:                   # uninteresting
1.599     albertel 5819: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5820: 			}
1.172     www      5821: # end of not-a-package not-a-library import
1.339     albertel 5822: 		    }
1.172     www      5823: # end of not-a-package start tag
1.339     albertel 5824: 		}
1.172     www      5825: # the next is the end of "start tag"
1.339     albertel 5826: 	    }
                   5827: 	}
1.483     albertel 5828: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 5829: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 5830: 	    #no specific packages #how's our extension
                   5831: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5832: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5833: 					 \%metathesekeys);
                   5834: 	}
1.599     albertel 5835: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 5836: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 5837: 		#no specific packages well let's get default then
                   5838: 		if ($key!~/^default&/) { next; }
1.488     albertel 5839: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5840: 					     \%metathesekeys);
                   5841: 	    }
                   5842: 	}
1.338     www      5843: # are there custom rights to evaluate
1.599     albertel 5844: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5845: 
1.338     www      5846:     #
                   5847:     # Importing a rights file here
1.339     albertel 5848:     #
                   5849: 	    unless ($depthcount) {
1.599     albertel 5850: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5851: 		my $dir=$filename;
                   5852: 		$dir=~s|[^/]*$||;
                   5853: 		$location=&filelocation($dir,$location);
1.736     albertel 5854: 		my $rights_metadata =
                   5855: 		    &metadata($uri,'keys',$location,'_rights',
                   5856: 			      $depthcount+1);
                   5857: 		foreach my $rights (split(',',$rights_metadata)) {
                   5858: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   5859: 		    $metathesekeys{$rights}=1;
1.339     albertel 5860: 		}
                   5861: 	    }
                   5862: 	}
1.737     albertel 5863: 	# uniqifiy package listing
                   5864: 	my %seen;
                   5865: 	my @uniq_packages =
                   5866: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   5867: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   5868: 
                   5869: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 5870: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5871: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 5872: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      5873: # this is the end of "was not already recently cached
1.71      www      5874:     }
1.599     albertel 5875:     return $metaentry{':'.$what};
1.261     albertel 5876: }
                   5877: 
1.488     albertel 5878: sub metadata_create_package_def {
1.483     albertel 5879:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5880:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5881:     if ($subp eq 'default') { next; }
                   5882:     
1.599     albertel 5883:     if (defined($metaentry{':packages'})) {
                   5884: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5885:     } else {
1.599     albertel 5886: 	$metaentry{':packages'}=$package;
1.483     albertel 5887:     }
                   5888:     my $value=$packagetab{$key};
                   5889:     my $unikey;
                   5890:     $unikey='parameter_0_'.$name;
1.599     albertel 5891:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5892:     $$metathesekeys{$unikey}=1;
1.599     albertel 5893:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5894: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5895:     }
1.599     albertel 5896:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5897: 	$metaentry{':'.$unikey}=
                   5898: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5899:     }
                   5900: }
                   5901: 
1.261     albertel 5902: sub metadata_generate_part0 {
                   5903:     my ($metadata,$metacache,$uri) = @_;
                   5904:     my %allnames;
1.737     albertel 5905:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 5906: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5907: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5908: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5909: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5910: 	    $allnames{$name}=$part;
                   5911: 	  }
                   5912: 	}
                   5913:     }
                   5914:     foreach my $name (keys(%allnames)) {
                   5915:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5916:       my $key=":parameter_0_$name";
1.261     albertel 5917:       $$metacache{"$key.part"}='0';
                   5918:       $$metacache{"$key.name"}=$name;
1.428     albertel 5919:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5920: 					   $allnames{$name}.'_'.$name.
                   5921: 					   '.type'};
1.428     albertel 5922:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5923: 			     '.display'};
1.644     www      5924:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5925:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5926:       $$metacache{"$key.display"}=$olddis;
                   5927:     }
1.71      www      5928: }
                   5929: 
1.301     www      5930: # ------------------------------------------------- Get the title of a resource
                   5931: 
                   5932: sub gettitle {
                   5933:     my $urlsymb=shift;
                   5934:     my $symb=&symbread($urlsymb);
1.534     albertel 5935:     if ($symb) {
1.620     albertel 5936: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5937: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5938: 	if (defined($cached)) { 
                   5939: 	    return $result;
                   5940: 	}
1.534     albertel 5941: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5942: 	my $title='';
                   5943: 	my %bighash;
1.620     albertel 5944: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5945: 		&GDBM_READER(),0640)) {
                   5946: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5947: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5948: 	    untie %bighash;
                   5949: 	}
                   5950: 	$title=~s/\&colon\;/\:/gs;
                   5951: 	if ($title) {
1.599     albertel 5952: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5953: 	}
                   5954: 	$urlsymb=$url;
                   5955:     }
                   5956:     my $title=&metadata($urlsymb,'title');
                   5957:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5958:     return $title;
1.301     www      5959: }
1.613     albertel 5960: 
1.614     albertel 5961: sub get_slot {
                   5962:     my ($which,$cnum,$cdom)=@_;
                   5963:     if (!$cnum || !$cdom) {
                   5964: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5965: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5966: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5967:     }
1.703     albertel 5968:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   5969:     my %slotinfo;
                   5970:     if (exists($remembered{$key})) {
                   5971: 	$slotinfo{$which} = $remembered{$key};
                   5972:     } else {
                   5973: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5974: 	&Apache::lonhomework::showhash(%slotinfo);
                   5975: 	my ($tmp)=keys(%slotinfo);
                   5976: 	if ($tmp=~/^error:/) { return (); }
                   5977: 	$remembered{$key} = $slotinfo{$which};
                   5978:     }
1.616     albertel 5979:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5980: 	return %{$slotinfo{$which}};
                   5981:     }
                   5982:     return $slotinfo{$which};
1.614     albertel 5983: }
1.31      www      5984: # ------------------------------------------------- Update symbolic store links
                   5985: 
                   5986: sub symblist {
                   5987:     my ($mapname,%newhash)=@_;
1.438     www      5988:     $mapname=&deversion(&declutter($mapname));
1.31      www      5989:     my %hash;
1.620     albertel 5990:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5991:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5992:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 5993: 	    foreach my $url (keys %newhash) {
                   5994: 		next if ($url eq 'last_known'
                   5995: 			 && $env{'form.no_update_last_known'});
                   5996: 		$hash{declutter($url)}=&encode_symb($mapname,
                   5997: 						    $newhash{$url}->[1],
                   5998: 						    $newhash{$url}->[0]);
1.191     harris41 5999:             }
1.31      www      6000:             if (untie(%hash)) {
                   6001: 		return 'ok';
                   6002:             }
                   6003:         }
                   6004:     }
                   6005:     return 'error';
1.212     www      6006: }
                   6007: 
                   6008: # --------------------------------------------------------------- Verify a symb
                   6009: 
                   6010: sub symbverify {
1.510     www      6011:     my ($symb,$thisurl)=@_;
                   6012:     my $thisfn=$thisurl;
                   6013: # wrapper not part of symbs
                   6014:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 6015:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      6016:     $thisfn=&declutter($thisfn);
1.215     www      6017: # direct jump to resource in page or to a sequence - will construct own symbs
                   6018:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6019: # check URL part
1.409     www      6020:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6021: 
1.431     www      6022:     unless ($url eq $thisfn) { return 0; }
1.213     www      6023: 
1.216     www      6024:     $symb=&symbclean($symb);
1.510     www      6025:     $thisurl=&deversion($thisurl);
1.439     www      6026:     $thisfn=&deversion($thisfn);
1.213     www      6027: 
                   6028:     my %bighash;
                   6029:     my $okay=0;
1.431     www      6030: 
1.620     albertel 6031:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6032:                             &GDBM_READER(),0640)) {
1.510     www      6033:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6034:         unless ($ids) { 
1.510     www      6035:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6036:         }
                   6037:         if ($ids) {
                   6038: # ------------------------------------------------------------------- Has ID(s)
                   6039: 	    foreach (split(/\,/,$ids)) {
1.644     www      6040: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6041:                if (
                   6042:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6043:    eq $symb) { 
1.620     albertel 6044: 		   if (($env{'request.role.adv'}) ||
                   6045: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6046: 		       $okay=1; 
                   6047: 		   }
                   6048: 	       }
1.216     www      6049: 	   }
                   6050:         }
1.213     www      6051: 	untie(%bighash);
                   6052:     }
                   6053:     return $okay;
1.31      www      6054: }
                   6055: 
1.210     www      6056: # --------------------------------------------------------------- Clean-up symb
                   6057: 
                   6058: sub symbclean {
                   6059:     my $symb=shift;
1.568     albertel 6060:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6061: # remove version from map
                   6062:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6063: 
1.210     www      6064: # remove version from URL
                   6065:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6066: 
1.507     www      6067: # remove wrapper
                   6068: 
1.510     www      6069:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6070:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6071:     return $symb;
1.409     www      6072: }
                   6073: 
                   6074: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6075: 
                   6076: sub encode_symb {
                   6077:     my ($map,$resid,$url)=@_;
                   6078:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6079: }
1.409     www      6080: 
                   6081: sub decode_symb {
1.568     albertel 6082:     my $symb=shift;
                   6083:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6084:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6085:     return (&fixversion($map),$resid,&fixversion($url));
                   6086: }
                   6087: 
                   6088: sub fixversion {
                   6089:     my $fn=shift;
1.609     banghart 6090:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6091:     my %bighash;
                   6092:     my $uri=&clutter($fn);
1.620     albertel 6093:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6094: # is this cached?
1.599     albertel 6095:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6096:     if (defined($cached)) { return $result; }
                   6097: # unfortunately not cached, or expired
1.620     albertel 6098:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6099: 	    &GDBM_READER(),0640)) {
                   6100:  	if ($bighash{'version_'.$uri}) {
                   6101:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6102:  	    unless (($version eq 'mostrecent') || 
                   6103: 		    ($version==&getversion($uri))) {
1.440     www      6104:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6105:  	    }
                   6106:  	}
                   6107:  	untie %bighash;
1.413     www      6108:     }
1.599     albertel 6109:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6110: }
                   6111: 
                   6112: sub deversion {
                   6113:     my $url=shift;
                   6114:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6115:     return $url;
1.210     www      6116: }
                   6117: 
1.31      www      6118: # ------------------------------------------------------ Return symb list entry
                   6119: 
                   6120: sub symbread {
1.249     www      6121:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6122:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6123:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6124: # no filename provided? try from environment
1.44      www      6125:     unless ($thisfn) {
1.620     albertel 6126:         if ($env{'request.symb'}) {
                   6127: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6128: 	}
1.620     albertel 6129: 	$thisfn=$env{'request.filename'};
1.44      www      6130:     }
1.569     albertel 6131:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6132: # is that filename actually a symb? Verify, clean, and return
                   6133:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6134: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6135: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6136: 	}
1.242     www      6137:     }
1.44      www      6138:     $thisfn=declutter($thisfn);
1.31      www      6139:     my %hash;
1.37      www      6140:     my %bighash;
                   6141:     my $syval='';
1.620     albertel 6142:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6143:         my $targetfn = $thisfn;
1.609     banghart 6144:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6145:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6146:         }
1.687     albertel 6147: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6148: 	    $targetfn=$1;
                   6149: 	}
1.620     albertel 6150:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6151:                       &GDBM_READER(),0640)) {
1.481     raeburn  6152: 	    $syval=$hash{$targetfn};
1.37      www      6153:             untie(%hash);
                   6154:         }
                   6155: # ---------------------------------------------------------- There was an entry
                   6156:         if ($syval) {
1.601     albertel 6157: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6158: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6159: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6160: 		    #return $env{$cache_str}='';
1.601     albertel 6161: 		#}    
                   6162: 		#$syval.=$1;
                   6163: 	    #}
1.37      www      6164:         } else {
                   6165: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6166:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6167:                             &GDBM_READER(),0640)) {
1.37      www      6168: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6169:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6170:               unless ($ids) { 
                   6171:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6172:               }
                   6173:               unless ($ids) {
                   6174: # alias?
                   6175: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6176:               }
1.37      www      6177:               if ($ids) {
                   6178: # ------------------------------------------------------------------- Has ID(s)
                   6179:                  my @possibilities=split(/\,/,$ids);
1.39      www      6180:                  if ($#possibilities==0) {
                   6181: # ----------------------------------------------- There is only one possibility
1.37      www      6182: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6183: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6184: 						    $resid,$thisfn);
1.249     www      6185:                  } elsif (!$donotrecurse) {
1.39      www      6186: # ------------------------------------------ There is more than one possibility
                   6187:                      my $realpossible=0;
1.191     harris41 6188:                      foreach (@possibilities) {
1.39      www      6189: 			 my $file=$bighash{'src_'.$_};
                   6190:                          if (&allowed('bre',$file)) {
                   6191:          		    my ($mapid,$resid)=split(/\./,$_);
                   6192:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6193: 				$realpossible++;
1.626     albertel 6194:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6195: 						    $resid,$thisfn);
1.39      www      6196:                             }
                   6197: 			 }
1.191     harris41 6198:                      }
1.39      www      6199: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6200:                  } else {
                   6201:                      $syval='';
1.37      www      6202:                  }
                   6203: 	      }
                   6204:               untie(%bighash)
1.481     raeburn  6205:            }
1.31      www      6206:         }
1.62      www      6207:         if ($syval) {
1.620     albertel 6208: 	    return $env{$cache_str}=$syval;
1.62      www      6209:         }
1.31      www      6210:     }
1.44      www      6211:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6212:     return $env{$cache_str}='';
1.31      www      6213: }
                   6214: 
                   6215: # ---------------------------------------------------------- Return random seed
                   6216: 
1.32      www      6217: sub numval {
                   6218:     my $txt=shift;
                   6219:     $txt=~tr/A-J/0-9/;
                   6220:     $txt=~tr/a-j/0-9/;
                   6221:     $txt=~tr/K-T/0-9/;
                   6222:     $txt=~tr/k-t/0-9/;
                   6223:     $txt=~tr/U-Z/0-5/;
                   6224:     $txt=~tr/u-z/0-5/;
                   6225:     $txt=~s/\D//g;
1.564     albertel 6226:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6227:     return int($txt);
1.368     albertel 6228: }
                   6229: 
1.484     albertel 6230: sub numval2 {
                   6231:     my $txt=shift;
                   6232:     $txt=~tr/A-J/0-9/;
                   6233:     $txt=~tr/a-j/0-9/;
                   6234:     $txt=~tr/K-T/0-9/;
                   6235:     $txt=~tr/k-t/0-9/;
                   6236:     $txt=~tr/U-Z/0-5/;
                   6237:     $txt=~tr/u-z/0-5/;
                   6238:     $txt=~s/\D//g;
                   6239:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6240:     my $total;
                   6241:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6242:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6243:     return int($total);
                   6244: }
                   6245: 
1.575     albertel 6246: sub numval3 {
                   6247:     use integer;
                   6248:     my $txt=shift;
                   6249:     $txt=~tr/A-J/0-9/;
                   6250:     $txt=~tr/a-j/0-9/;
                   6251:     $txt=~tr/K-T/0-9/;
                   6252:     $txt=~tr/k-t/0-9/;
                   6253:     $txt=~tr/U-Z/0-5/;
                   6254:     $txt=~tr/u-z/0-5/;
                   6255:     $txt=~s/\D//g;
                   6256:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6257:     my $total;
                   6258:     foreach my $val (@txts) { $total+=$val; }
                   6259:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6260:     return $total;
                   6261: }
                   6262: 
1.675     albertel 6263: sub digest {
                   6264:     my ($data)=@_;
                   6265:     my $digest=&Digest::MD5::md5($data);
                   6266:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6267:     my ($e,$f);
                   6268:     {
                   6269:         use integer;
                   6270:         $e=($a+$b);
                   6271:         $f=($c+$d);
                   6272:         if ($_64bit) {
                   6273:             $e=(($e<<32)>>32);
                   6274:             $f=(($f<<32)>>32);
                   6275:         }
                   6276:     }
                   6277:     if (wantarray) {
                   6278: 	return ($e,$f);
                   6279:     } else {
                   6280: 	my $g;
                   6281: 	{
                   6282: 	    use integer;
                   6283: 	    $g=($e+$f);
                   6284: 	    if ($_64bit) {
                   6285: 		$g=(($g<<32)>>32);
                   6286: 	    }
                   6287: 	}
                   6288: 	return $g;
                   6289:     }
                   6290: }
                   6291: 
1.368     albertel 6292: sub latest_rnd_algorithm_id {
1.675     albertel 6293:     return '64bit5';
1.366     albertel 6294: }
1.32      www      6295: 
1.503     albertel 6296: sub get_rand_alg {
                   6297:     my ($courseid)=@_;
                   6298:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6299:     if ($courseid) {
1.620     albertel 6300: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6301:     }
                   6302:     return &latest_rnd_algorithm_id();
                   6303: }
                   6304: 
1.562     albertel 6305: sub validCODE {
                   6306:     my ($CODE)=@_;
                   6307:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6308:     return 0;
                   6309: }
                   6310: 
1.491     albertel 6311: sub getCODE {
1.620     albertel 6312:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6313:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6314: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6315: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6316: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6317:     }
                   6318:     return undef;
                   6319: }
                   6320: 
1.31      www      6321: sub rndseed {
1.155     albertel 6322:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6323: 
                   6324:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6325:     if (!$symb) {
1.366     albertel 6326: 	unless ($symb=$wsymb) { return time; }
                   6327:     }
                   6328:     if (!$courseid) { $courseid=$wcourseid; }
                   6329:     if (!$domain) { $domain=$wdomain; }
                   6330:     if (!$username) { $username=$wusername }
1.503     albertel 6331:     my $which=&get_rand_alg();
1.491     albertel 6332:     if (defined(&getCODE())) {
1.675     albertel 6333: 	if ($which eq '64bit5') {
                   6334: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6335: 	} elsif ($which eq '64bit4') {
1.575     albertel 6336: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6337: 	} else {
                   6338: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6339: 	}
1.675     albertel 6340:     } elsif ($which eq '64bit5') {
                   6341: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6342:     } elsif ($which eq '64bit4') {
                   6343: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6344:     } elsif ($which eq '64bit3') {
                   6345: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6346:     } elsif ($which eq '64bit2') {
                   6347: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6348:     } elsif ($which eq '64bit') {
                   6349: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6350:     }
                   6351:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6352: }
                   6353: 
                   6354: sub rndseed_32bit {
                   6355:     my ($symb,$courseid,$domain,$username)=@_;
                   6356:     {
                   6357: 	use integer;
                   6358: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6359: 	my $symbseed=numval($symb) << 22;
                   6360: 	my $namechck=unpack("%32C*",$username) << 17;
                   6361: 	my $nameseed=numval($username) << 12;
                   6362: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6363: 	my $courseseed=unpack("%32C*",$courseid);
                   6364: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6365: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6366: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6367: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6368: 	return $num;
                   6369:     }
                   6370: }
                   6371: 
                   6372: sub rndseed_64bit {
                   6373:     my ($symb,$courseid,$domain,$username)=@_;
                   6374:     {
                   6375: 	use integer;
                   6376: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6377: 	my $symbseed=numval($symb) << 10;
                   6378: 	my $namechck=unpack("%32S*",$username);
                   6379: 	
                   6380: 	my $nameseed=numval($username) << 21;
                   6381: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6382: 	my $courseseed=unpack("%32S*",$courseid);
                   6383: 	
                   6384: 	my $num1=$symbchck+$symbseed+$namechck;
                   6385: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6386: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6387: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6388: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6389: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6390: 	return "$num1,$num2";
1.155     albertel 6391:     }
1.366     albertel 6392: }
                   6393: 
1.443     albertel 6394: sub rndseed_64bit2 {
                   6395:     my ($symb,$courseid,$domain,$username)=@_;
                   6396:     {
                   6397: 	use integer;
                   6398: 	# strings need to be an even # of cahracters long, it it is odd the
                   6399:         # last characters gets thrown away
                   6400: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6401: 	my $symbseed=numval($symb) << 10;
                   6402: 	my $namechck=unpack("%32S*",$username.' ');
                   6403: 	
                   6404: 	my $nameseed=numval($username) << 21;
1.501     albertel 6405: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6406: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6407: 	
                   6408: 	my $num1=$symbchck+$symbseed+$namechck;
                   6409: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6410: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6411: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6412: 	return "$num1,$num2";
                   6413:     }
                   6414: }
                   6415: 
                   6416: sub rndseed_64bit3 {
                   6417:     my ($symb,$courseid,$domain,$username)=@_;
                   6418:     {
                   6419: 	use integer;
                   6420: 	# strings need to be an even # of cahracters long, it it is odd the
                   6421:         # last characters gets thrown away
                   6422: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6423: 	my $symbseed=numval2($symb) << 10;
                   6424: 	my $namechck=unpack("%32S*",$username.' ');
                   6425: 	
                   6426: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6427: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6428: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6429: 	
                   6430: 	my $num1=$symbchck+$symbseed+$namechck;
                   6431: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6432: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6433: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6434: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6435: 	
1.503     albertel 6436: 	return "$num1:$num2";
1.443     albertel 6437:     }
                   6438: }
                   6439: 
1.575     albertel 6440: sub rndseed_64bit4 {
                   6441:     my ($symb,$courseid,$domain,$username)=@_;
                   6442:     {
                   6443: 	use integer;
                   6444: 	# strings need to be an even # of cahracters long, it it is odd the
                   6445:         # last characters gets thrown away
                   6446: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6447: 	my $symbseed=numval3($symb) << 10;
                   6448: 	my $namechck=unpack("%32S*",$username.' ');
                   6449: 	
                   6450: 	my $nameseed=numval3($username) << 21;
                   6451: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6452: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6453: 	
                   6454: 	my $num1=$symbchck+$symbseed+$namechck;
                   6455: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6456: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6457: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6458: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6459: 	
                   6460: 	return "$num1:$num2";
                   6461:     }
                   6462: }
                   6463: 
1.675     albertel 6464: sub rndseed_64bit5 {
                   6465:     my ($symb,$courseid,$domain,$username)=@_;
                   6466:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6467:     return "$num1:$num2";
                   6468: }
                   6469: 
1.366     albertel 6470: sub rndseed_CODE_64bit {
                   6471:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6472:     {
1.366     albertel 6473: 	use integer;
1.443     albertel 6474: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6475: 	my $symbseed=numval2($symb);
1.491     albertel 6476: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6477: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6478: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6479: 	my $num1=$symbseed+$CODEchck;
                   6480: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6481: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6482: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6483: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6484: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6485: 	return "$num1:$num2";
1.366     albertel 6486:     }
                   6487: }
                   6488: 
1.575     albertel 6489: sub rndseed_CODE_64bit4 {
                   6490:     my ($symb,$courseid,$domain,$username)=@_;
                   6491:     {
                   6492: 	use integer;
                   6493: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6494: 	my $symbseed=numval3($symb);
                   6495: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6496: 	my $CODEseed=numval3(&getCODE());
                   6497: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6498: 	my $num1=$symbseed+$CODEchck;
                   6499: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6500: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6501: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6502: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6503: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6504: 	return "$num1:$num2";
                   6505:     }
                   6506: }
                   6507: 
1.675     albertel 6508: sub rndseed_CODE_64bit5 {
                   6509:     my ($symb,$courseid,$domain,$username)=@_;
                   6510:     my $code = &getCODE();
                   6511:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6512:     return "$num1:$num2";
                   6513: }
                   6514: 
1.366     albertel 6515: sub setup_random_from_rndseed {
                   6516:     my ($rndseed)=@_;
1.503     albertel 6517:     if ($rndseed =~/([,:])/) {
                   6518: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6519: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6520:     } else {
                   6521: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6522:     }
1.36      albertel 6523: }
                   6524: 
1.474     albertel 6525: sub latest_receipt_algorithm_id {
                   6526:     return 'receipt2';
                   6527: }
                   6528: 
1.480     www      6529: sub recunique {
                   6530:     my $fucourseid=shift;
                   6531:     my $unique;
1.620     albertel 6532:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6533: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6534:     } else {
                   6535: 	$unique=$perlvar{'lonReceipt'};
                   6536:     }
                   6537:     return unpack("%32C*",$unique);
                   6538: }
                   6539: 
                   6540: sub recprefix {
                   6541:     my $fucourseid=shift;
                   6542:     my $prefix;
1.620     albertel 6543:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6544: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6545:     } else {
                   6546: 	$prefix=$perlvar{'lonHostID'};
                   6547:     }
                   6548:     return unpack("%32C*",$prefix);
                   6549: }
                   6550: 
1.76      www      6551: sub ireceipt {
1.474     albertel 6552:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6553:     my $cuname=unpack("%32C*",$funame);
                   6554:     my $cudom=unpack("%32C*",$fudom);
                   6555:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6556:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6557:     my $cunique=&recunique($fucourseid);
1.474     albertel 6558:     my $cpart=unpack("%32S*",$part);
1.480     www      6559:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6560:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6561: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6562: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6563: 			       " and ".($cpart%$cudom));
                   6564: 			       
                   6565: 	$return.= ($cunique%$cuname+
                   6566: 		   $cunique%$cudom+
                   6567: 		   $cusymb%$cuname+
                   6568: 		   $cusymb%$cudom+
                   6569: 		   $cucourseid%$cuname+
                   6570: 		   $cucourseid%$cudom+
                   6571: 		   $cpart%$cuname+
                   6572: 		   $cpart%$cudom);
                   6573:     } else {
                   6574: 	$return.= ($cunique%$cuname+
                   6575: 		   $cunique%$cudom+
                   6576: 		   $cusymb%$cuname+
                   6577: 		   $cusymb%$cudom+
                   6578: 		   $cucourseid%$cuname+
                   6579: 		   $cucourseid%$cudom);
                   6580:     }
                   6581:     return $return;
1.76      www      6582: }
                   6583: 
                   6584: sub receipt {
1.474     albertel 6585:     my ($part)=@_;
                   6586:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6587:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6588: }
1.260     ng       6589: 
1.36      albertel 6590: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6591: # returns either the contents of the file or 
                   6592: # -1 if the file doesn't exist
1.481     raeburn  6593: #
                   6594: # if the target is a file that was uploaded via DOCS, 
                   6595: # a check will be made to see if a current copy exists on the local server,
                   6596: # if it does this will be served, otherwise a copy will be retrieved from
                   6597: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6598: # the local server.   
1.472     albertel 6599: 
1.36      albertel 6600: sub getfile {
1.538     albertel 6601:     my ($file) = @_;
1.609     banghart 6602:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6603:     &repcopy($file);
                   6604:     return &readfile($file);
                   6605: }
                   6606: 
                   6607: sub repcopy_userfile {
                   6608:     my ($file)=@_;
1.609     banghart 6609:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6610:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6611:     my ($cdom,$cnum,$filename) = 
                   6612: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6613:     my ($info,$rtncode);
                   6614:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6615:     if (-e "$file") {
                   6616: 	my @fileinfo = stat($file);
                   6617: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6618: 	if ($lwpresp ne 'ok') {
                   6619: 	    if ($rtncode eq '404') {
1.538     albertel 6620: 		unlink($file);
1.482     albertel 6621: 	    }
1.517     albertel 6622: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6623: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6624: 	    #my $response=$ua->request($request);
                   6625: 	    #if ($response->is_success()) {
                   6626: 	#	return $response->content;
                   6627: 	#    } else {
                   6628: 	#	return -1;
                   6629: 	#    }
1.482     albertel 6630: 	    return -1;
                   6631: 	}
                   6632: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6633: 	    return 'ok';
1.482     albertel 6634: 	}
                   6635: 	$info = '';
1.538     albertel 6636: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6637: 	if ($lwpresp ne 'ok') {
                   6638: 	    return -1;
                   6639: 	}
                   6640:     } else {
1.538     albertel 6641: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6642: 	if ($lwpresp ne 'ok') {
1.517     albertel 6643: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6644: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6645: 	    my $response=$ua->request($request);
                   6646: 	    if ($response->is_success()) {
1.538     albertel 6647: 		$info=$response->content;
1.517     albertel 6648: 	    } else {
                   6649: 		return -1;
                   6650: 	    }
1.482     albertel 6651: 	}
                   6652: 	my @parts = ($cdom,$cnum); 
                   6653: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6654: 	    push @parts, split(/\//,$1);
1.518     albertel 6655: 	}
1.538     albertel 6656: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6657: 	foreach my $part (@parts) {
                   6658: 	    $path .= '/'.$part;
                   6659: 	    if (!-e $path) {
                   6660: 		mkdir($path,0770);
                   6661: 	    }
                   6662: 	}
                   6663:     }
1.538     albertel 6664:     open(FILE,">$file");
1.482     albertel 6665:     print FILE $info;
                   6666:     close(FILE);
1.607     raeburn  6667:     return 'ok';
1.481     raeburn  6668: }
                   6669: 
1.517     albertel 6670: sub tokenwrapper {
                   6671:     my $uri=shift;
1.552     albertel 6672:     $uri=~s|^http\://([^/]+)||;
                   6673:     $uri=~s|^/||;
1.620     albertel 6674:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6675:     my $token=$1;
1.552     albertel 6676:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6677:     if ($udom && $uname && $file) {
                   6678: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6679:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6680:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6681:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6682:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6683:     } else {
                   6684:         return '/adm/notfound.html';
                   6685:     }
                   6686: }
                   6687: 
1.481     raeburn  6688: sub getuploaded {
                   6689:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6690:     $uri=~s/^\///;
                   6691:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6692:     my $ua=new LWP::UserAgent;
                   6693:     my $request=new HTTP::Request($reqtype,$uri);
                   6694:     my $response=$ua->request($request);
                   6695:     $$rtncode = $response->code;
1.482     albertel 6696:     if (! $response->is_success()) {
                   6697: 	return 'failed';
                   6698:     }      
                   6699:     if ($reqtype eq 'HEAD') {
1.486     www      6700: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6701:     } elsif ($reqtype eq 'GET') {
                   6702: 	$$info = $response->content;
1.472     albertel 6703:     }
1.482     albertel 6704:     return 'ok';
1.36      albertel 6705: }
                   6706: 
1.481     raeburn  6707: sub readfile {
                   6708:     my $file = shift;
                   6709:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6710:     my $fh;
                   6711:     open($fh,"<$file");
                   6712:     my $a='';
                   6713:     while (<$fh>) { $a .=$_; }
                   6714:     return $a;
                   6715: }
                   6716: 
1.36      albertel 6717: sub filelocation {
1.590     banghart 6718:     my ($dir,$file) = @_;
                   6719:     my $location;
                   6720:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6721: 
                   6722:     if ($file =~ m-^/adm/-) {
                   6723: 	$file=~s-^/adm/wrapper/-/-;
                   6724: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6725:     }
1.590     banghart 6726:     if ($file=~m:^/~:) { # is a contruction space reference
                   6727:         $location = $file;
                   6728:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6729:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6730: 	# is a correct contruction space reference
                   6731:         $location = $file;
1.609     banghart 6732:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6733:         my ($udom,$uname,$filename)=
1.609     banghart 6734:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6735:         my $home=&homeserver($uname,$udom);
                   6736:         my $is_me=0;
                   6737:         my @ids=&current_machine_ids();
                   6738:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6739:         if ($is_me) {
1.740     www      6740:   	    $location=&propath($udom,$uname).
1.590     banghart 6741:   	      '/userfiles/'.$filename;
                   6742:         } else {
                   6743:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6744:   	      $udom.'/'.$uname.'/'.$filename;
                   6745:         }
                   6746:     } else {
                   6747:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6748:         $file=~s:^/res/:/:;
                   6749:         if ( !( $file =~ m:^/:) ) {
                   6750:             $location = $dir. '/'.$file;
                   6751:         } else {
                   6752:             $location = '/home/httpd/html/res'.$file;
                   6753:         }
1.59      albertel 6754:     }
1.590     banghart 6755:     $location=~s://+:/:g; # remove duplicate /
                   6756:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6757:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6758:     return $location;
1.46      www      6759: }
1.36      albertel 6760: 
1.46      www      6761: sub hreflocation {
                   6762:     my ($dir,$file)=@_;
1.460     albertel 6763:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6764: 	$file=filelocation($dir,$file);
1.700     albertel 6765:     } elsif ($file=~m-^/adm/-) {
                   6766: 	$file=~s-^/adm/wrapper/-/-;
                   6767: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6768:     }
                   6769:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6770: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6771:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6772: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6773:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6774: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6775: 	    -/uploaded/$1/$2/-x;
1.46      www      6776:     }
1.462     albertel 6777:     return $file;
1.465     albertel 6778: }
                   6779: 
                   6780: sub current_machine_domains {
                   6781:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6782:     my @domains;
                   6783:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6784: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6785: 	if ($hostname eq $name) {
                   6786: 	    push(@domains,$hostdom{$id});
                   6787: 	}
                   6788:     }
                   6789:     return @domains;
                   6790: }
                   6791: 
                   6792: sub current_machine_ids {
                   6793:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6794:     my @ids;
                   6795:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6796: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6797: 	if ($hostname eq $name) {
                   6798: 	    push(@ids,$id);
                   6799: 	}
                   6800:     }
                   6801:     return @ids;
1.31      www      6802: }
                   6803: 
                   6804: # ------------------------------------------------------------- Declutters URLs
                   6805: 
                   6806: sub declutter {
                   6807:     my $thisfn=shift;
1.569     albertel 6808:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6809:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6810:     $thisfn=~s/^\///;
1.697     albertel 6811:     $thisfn=~s|^adm/wrapper/||;
                   6812:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      6813:     $thisfn=~s/^res\///;
1.235     www      6814:     $thisfn=~s/\?.+$//;
1.268     www      6815:     return $thisfn;
                   6816: }
                   6817: 
                   6818: # ------------------------------------------------------------- Clutter up URLs
                   6819: 
                   6820: sub clutter {
                   6821:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6822:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6823:        $thisfn='/res'.$thisfn; 
                   6824:     }
1.694     albertel 6825:     if ($thisfn !~m|/adm|) {
1.695     albertel 6826: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 6827: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 6828: 	} else {
                   6829: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   6830: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 6831: 	    if ($embstyle eq 'ssi'
                   6832: 		|| ($embstyle eq 'hdn')
                   6833: 		|| ($embstyle eq 'rat')
                   6834: 		|| ($embstyle eq 'prv')
                   6835: 		|| ($embstyle eq 'ign')) {
                   6836: 		#do nothing with these
                   6837: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 6838: 		|| ($embstyle eq 'emb')
                   6839: 		|| ($embstyle eq 'wrp')) {
                   6840: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 6841: 	    } elsif ($embstyle eq 'unk'
                   6842: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 6843: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 6844: 	    } else {
1.718     www      6845: #		&logthis("Got a blank emb style");
1.695     albertel 6846: 	    }
1.694     albertel 6847: 	}
                   6848:     }
1.31      www      6849:     return $thisfn;
1.12      www      6850: }
                   6851: 
1.557     albertel 6852: sub freeze_escape {
                   6853:     my ($value)=@_;
                   6854:     if (ref($value)) {
                   6855: 	$value=&nfreeze($value);
                   6856: 	return '__FROZEN__'.&escape($value);
                   6857:     }
                   6858:     return &escape($value);
                   6859: }
                   6860: 
1.11      www      6861: 
1.557     albertel 6862: sub thaw_unescape {
                   6863:     my ($value)=@_;
                   6864:     if ($value =~ /^__FROZEN__/) {
                   6865: 	substr($value,0,10,undef);
                   6866: 	$value=&unescape($value);
                   6867: 	return &thaw($value);
                   6868:     }
                   6869:     return &unescape($value);
                   6870: }
                   6871: 
1.436     albertel 6872: sub correct_line_ends {
                   6873:     my ($result)=@_;
                   6874:     $$result =~s/\r\n/\n/mg;
                   6875:     $$result =~s/\r/\n/mg;
1.415     albertel 6876: }
1.1       albertel 6877: # ================================================================ Main Program
                   6878: 
1.184     www      6879: sub goodbye {
1.204     albertel 6880:    &logthis("Starting Shut down");
1.443     albertel 6881: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6882:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6883: #converted
1.599     albertel 6884: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6885:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6886: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6887: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6888: #1.1 only
1.599     albertel 6889: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6890: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6891: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6892: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6893:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6894:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6895:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6896:    &flushcourselogs();
                   6897:    &logthis("Shutting down");
                   6898: }
                   6899: 
1.179     www      6900: BEGIN {
1.228     harris41 6901: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6902:     unless ($readit) {
1.217     harris41 6903: {
1.581     matthew  6904:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6905:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6906: 
                   6907:     while (my $configline=<$config>) {
1.484     albertel 6908:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6909: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6910:            chomp($varvalue);
1.1       albertel 6911:            $perlvar{$varname}=$varvalue;
                   6912:         }
                   6913:     }
1.448     albertel 6914:     close($config);
1.1       albertel 6915: }
1.227     harris41 6916: {
1.448     albertel 6917:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6918: 
                   6919:     while (my $configline=<$config>) {
                   6920:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6921: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6922:            chomp($varvalue);
                   6923:            $perlvar{$varname}=$varvalue;
                   6924:         }
                   6925:     }
1.448     albertel 6926:     close($config);
1.227     harris41 6927: }
1.1       albertel 6928: 
1.327     albertel 6929: # ------------------------------------------------------------ Read domain file
                   6930: {
                   6931:     %domaindescription = ();
                   6932:     %domain_auth_def = ();
                   6933:     %domain_auth_arg_def = ();
1.448     albertel 6934:     my $fh;
                   6935:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6936:        while (<$fh>) {
1.390     matthew  6937:            next if (/^(\#|\s*$)/);
                   6938: #           next if /^\#/;
1.327     albertel 6939:            chomp;
1.403     www      6940:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  6941: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      6942: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6943:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6944: 	   $domaindescription{$domain}=$domain_description;
                   6945: 	   $domain_lang_def{$domain}=$def_lang;
                   6946: 	   $domain_city{$domain}=$city;
                   6947: 	   $domain_longi{$domain}=$longi;
                   6948: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  6949:            $domain_primary{$domain}=$primary;
1.403     www      6950: 
1.448     albertel 6951:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6952: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6953: 	}
1.327     albertel 6954:     }
1.448     albertel 6955:     close ($fh);
1.327     albertel 6956: }
                   6957: 
                   6958: 
1.1       albertel 6959: # ------------------------------------------------------------- Read hosts file
                   6960: {
1.448     albertel 6961:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6962: 
                   6963:     while (my $configline=<$config>) {
1.303     matthew  6964:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6965:        chomp($configline);
1.595     albertel 6966:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6967:        $name=~s/\s//g;
1.595     albertel 6968:        if ($id && $domain && $role && $name) {
1.252     albertel 6969: 	 $hostname{$id}=$name;
                   6970: 	 $hostdom{$id}=$domain;
                   6971: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6972:        }
1.1       albertel 6973:     }
1.448     albertel 6974:     close($config);
1.619     albertel 6975:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 6976:     #&get_iphost();
1.1       albertel 6977: }
                   6978: 
1.598     albertel 6979: sub get_iphost {
                   6980:     if (%iphost) { return %iphost; }
1.653     albertel 6981:     my %name_to_ip;
1.598     albertel 6982:     foreach my $id (keys(%hostname)) {
                   6983: 	my $name=$hostname{$id};
1.653     albertel 6984: 	my $ip;
                   6985: 	if (!exists($name_to_ip{$name})) {
                   6986: 	    $ip = gethostbyname($name);
                   6987: 	    if (!$ip || length($ip) ne 4) {
                   6988: 		&logthis("Skipping host $id name $name no IP found\n");
                   6989: 		next;
                   6990: 	    }
                   6991: 	    $ip=inet_ntoa($ip);
                   6992: 	    $name_to_ip{$name} = $ip;
                   6993: 	} else {
                   6994: 	    $ip = $name_to_ip{$name};
1.598     albertel 6995: 	}
                   6996: 	push(@{$iphost{$ip}},$id);
                   6997:     }
                   6998:     return %iphost;
                   6999: }
                   7000: 
1.1       albertel 7001: # ------------------------------------------------------ Read spare server file
                   7002: {
1.448     albertel 7003:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7004: 
                   7005:     while (my $configline=<$config>) {
                   7006:        chomp($configline);
1.284     matthew  7007:        if ($configline) {
1.1       albertel 7008:           $spareid{$configline}=1;
                   7009:        }
                   7010:     }
1.448     albertel 7011:     close($config);
1.1       albertel 7012: }
1.11      www      7013: # ------------------------------------------------------------ Read permissions
                   7014: {
1.448     albertel 7015:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7016: 
                   7017:     while (my $configline=<$config>) {
1.448     albertel 7018: 	chomp($configline);
                   7019: 	if ($configline) {
                   7020: 	    my ($role,$perm)=split(/ /,$configline);
                   7021: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7022: 	}
1.11      www      7023:     }
1.448     albertel 7024:     close($config);
1.11      www      7025: }
                   7026: 
                   7027: # -------------------------------------------- Read plain texts for permissions
                   7028: {
1.448     albertel 7029:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7030: 
                   7031:     while (my $configline=<$config>) {
1.448     albertel 7032: 	chomp($configline);
                   7033: 	if ($configline) {
1.742     raeburn  7034: 	    my ($short,@plain)=split(/:/,$configline);
                   7035:             %{$prp{$short}} = ();
                   7036: 	    if (@plain > 0) {
                   7037:                 $prp{$short}{'std'} = $plain[0];
                   7038:                 for (my $i=1; $i<@plain; $i++) {
                   7039:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7040:                 }
                   7041:             }
1.448     albertel 7042: 	}
1.135     www      7043:     }
1.448     albertel 7044:     close($config);
1.135     www      7045: }
                   7046: 
                   7047: # ---------------------------------------------------------- Read package table
                   7048: {
1.448     albertel 7049:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7050: 
                   7051:     while (my $configline=<$config>) {
1.483     albertel 7052: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7053: 	chomp($configline);
                   7054: 	my ($short,$plain)=split(/:/,$configline);
                   7055: 	my ($pack,$name)=split(/\&/,$short);
                   7056: 	if ($plain ne '') {
                   7057: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7058: 	    $packagetab{$short}=$plain; 
                   7059: 	}
1.11      www      7060:     }
1.448     albertel 7061:     close($config);
1.329     matthew  7062: }
                   7063: 
                   7064: # ------------- set up temporary directory
                   7065: {
                   7066:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7067: 
1.11      www      7068: }
                   7069: 
1.599     albertel 7070: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7071: 
1.281     www      7072: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7073: $dumpcount=0;
1.22      www      7074: 
1.163     harris41 7075: &logtouch();
1.672     albertel 7076: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7077: $readit=1;
1.564     albertel 7078:     {
                   7079: 	use integer;
                   7080: 	my $test=(2**32)+1;
1.568     albertel 7081: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7082: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7083:     }
1.195     www      7084: }
1.1       albertel 7085: }
1.179     www      7086: 
1.1       albertel 7087: 1;
1.191     harris41 7088: __END__
                   7089: 
1.243     albertel 7090: =pod
                   7091: 
1.191     harris41 7092: =head1 NAME
                   7093: 
1.243     albertel 7094: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7095: 
                   7096: =head1 SYNOPSIS
                   7097: 
1.243     albertel 7098: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7099: 
                   7100:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7101: 
1.243     albertel 7102: Common parameters:
                   7103: 
                   7104: =over 4
                   7105: 
                   7106: =item *
                   7107: 
                   7108: $uname : an internal username (if $cname expecting a course Id specifically)
                   7109: 
                   7110: =item *
                   7111: 
                   7112: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7113: 
                   7114: =item *
                   7115: 
                   7116: $symb : a resource instance identifier
                   7117: 
                   7118: =item *
                   7119: 
                   7120: $namespace : the name of a .db file that contains the data needed or
                   7121: being set.
                   7122: 
                   7123: =back
                   7124: 
1.394     bowersj2 7125: =head1 OVERVIEW
1.191     harris41 7126: 
1.394     bowersj2 7127: lonnet provides subroutines which interact with the
                   7128: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7129: about classes, users, and resources.
1.243     albertel 7130: 
                   7131: For many of these objects you can also use this to store data about
                   7132: them or modify them in various ways.
1.191     harris41 7133: 
1.394     bowersj2 7134: =head2 Symbs
1.191     harris41 7135: 
1.394     bowersj2 7136: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7137: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7138: map, the resource number of the resource in the map, and the URL of
                   7139: the resource itself. The latter is somewhat redundant, but might help
                   7140: if maps change.
                   7141: 
                   7142: An example is
                   7143: 
                   7144:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7145: 
                   7146: The respective map entry is
                   7147: 
                   7148:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7149:   title="Problem 2">
                   7150:  </resource>
                   7151: 
                   7152: Symbs are used by the random number generator, as well as to store and
                   7153: restore data specific to a certain instance of for example a problem.
                   7154: 
                   7155: =head2 Storing And Retrieving Data
                   7156: 
                   7157: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7158: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7159: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7160: is is the non-critical message twin of cstore. These functions are for
                   7161: handlers to store a perl hash to a user's permanent data space in an
                   7162: easy manner, and to retrieve it again on another call. It is expected
                   7163: that a handler would use this once at the beginning to retrieve data,
                   7164: and then again once at the end to send only the new data back.
                   7165: 
                   7166: The data is stored in the user's data directory on the user's
                   7167: homeserver under the ID of the course.
                   7168: 
                   7169: The hash that is returned by restore will have all of the previous
                   7170: value for all of the elements of the hash.
                   7171: 
                   7172: Example:
                   7173: 
                   7174:  #creating a hash
                   7175:  my %hash;
                   7176:  $hash{'foo'}='bar';
                   7177: 
                   7178:  #storing it
                   7179:  &Apache::lonnet::cstore(\%hash);
                   7180: 
                   7181:  #changing a value
                   7182:  $hash{'foo'}='notbar';
                   7183: 
                   7184:  #adding a new value
                   7185:  $hash{'bar'}='foo';
                   7186:  &Apache::lonnet::cstore(\%hash);
                   7187: 
                   7188:  #retrieving the hash
                   7189:  my %history=&Apache::lonnet::restore();
                   7190: 
                   7191:  #print the hash
                   7192:  foreach my $key (sort(keys(%history))) {
                   7193:    print("\%history{$key} = $history{$key}");
                   7194:  }
                   7195: 
                   7196: Will print out:
1.191     harris41 7197: 
1.394     bowersj2 7198:  %history{1:foo} = bar
                   7199:  %history{1:keys} = foo:timestamp
                   7200:  %history{1:timestamp} = 990455579
                   7201:  %history{2:bar} = foo
                   7202:  %history{2:foo} = notbar
                   7203:  %history{2:keys} = foo:bar:timestamp
                   7204:  %history{2:timestamp} = 990455580
                   7205:  %history{bar} = foo
                   7206:  %history{foo} = notbar
                   7207:  %history{timestamp} = 990455580
                   7208:  %history{version} = 2
                   7209: 
                   7210: Note that the special hash entries C<keys>, C<version> and
                   7211: C<timestamp> were added to the hash. C<version> will be equal to the
                   7212: total number of versions of the data that have been stored. The
                   7213: C<timestamp> attribute will be the UNIX time the hash was
                   7214: stored. C<keys> is available in every historical section to list which
                   7215: keys were added or changed at a specific historical revision of a
                   7216: hash.
                   7217: 
                   7218: B<Warning>: do not store the hash that restore returns directly. This
                   7219: will cause a mess since it will restore the historical keys as if the
                   7220: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7221: 
1.394     bowersj2 7222: Calling convention:
1.191     harris41 7223: 
1.394     bowersj2 7224:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7225:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7226: 
1.394     bowersj2 7227: For more detailed information, see lonnet specific documentation.
1.191     harris41 7228: 
1.394     bowersj2 7229: =head1 RETURN MESSAGES
1.191     harris41 7230: 
1.394     bowersj2 7231: =over 4
1.191     harris41 7232: 
1.394     bowersj2 7233: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7234: 
1.394     bowersj2 7235: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7236: when the connection is brought back up
1.191     harris41 7237: 
1.394     bowersj2 7238: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7239: for later delivery
1.191     harris41 7240: 
1.394     bowersj2 7241: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7242: 
1.394     bowersj2 7243: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7244: that was requested
1.191     harris41 7245: 
1.243     albertel 7246: =back
1.191     harris41 7247: 
1.243     albertel 7248: =head1 PUBLIC SUBROUTINES
1.191     harris41 7249: 
1.243     albertel 7250: =head2 Session Environment Functions
1.191     harris41 7251: 
1.243     albertel 7252: =over 4
1.191     harris41 7253: 
1.394     bowersj2 7254: =item * 
                   7255: X<appenv()>
                   7256: B<appenv(%hash)>: the value of %hash is written to
                   7257: the user envirnoment file, and will be restored for each access this
1.620     albertel 7258: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7259: process
1.191     harris41 7260: 
                   7261: =item *
1.394     bowersj2 7262: X<delenv()>
                   7263: B<delenv($regexp)>: removes all items from the session
                   7264: environment file that matches the regular expression in $regexp. The
1.620     albertel 7265: values are also delted from the current processes %env.
1.191     harris41 7266: 
1.243     albertel 7267: =back
                   7268: 
                   7269: =head2 User Information
1.191     harris41 7270: 
1.243     albertel 7271: =over 4
1.191     harris41 7272: 
                   7273: =item *
1.394     bowersj2 7274: X<queryauthenticate()>
                   7275: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7276: authentication scheme
                   7277: 
                   7278: =item *
1.394     bowersj2 7279: X<authenticate()>
                   7280: B<authenticate($uname,$upass,$udom)>: try to
                   7281: authenticate user from domain's lib servers (first use the current
                   7282: one). C<$upass> should be the users password.
1.191     harris41 7283: 
                   7284: =item *
1.394     bowersj2 7285: X<homeserver()>
                   7286: B<homeserver($uname,$udom)>: find the server which has
                   7287: the user's directory and files (there must be only one), this caches
                   7288: the answer, and also caches if there is a borken connection.
1.191     harris41 7289: 
                   7290: =item *
1.394     bowersj2 7291: X<idget()>
                   7292: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7293: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7294: username, and only 1 username per ID in a specific domain) (returns
                   7295: hash: id=>name,id=>name)
1.191     harris41 7296: 
                   7297: =item *
1.394     bowersj2 7298: X<idrget()>
                   7299: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7300: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7301: 
                   7302: =item *
1.394     bowersj2 7303: X<idput()>
                   7304: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7305: 
                   7306: =item *
1.394     bowersj2 7307: X<rolesinit()>
                   7308: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7309: 
                   7310: =item *
1.551     albertel 7311: X<getsection()>
                   7312: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7313: course $cname, return section name/number or '' for "not in course"
                   7314: and '-1' for "no section"
                   7315: 
                   7316: =item *
1.394     bowersj2 7317: X<userenvironment()>
                   7318: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7319: passed in @what from the requested user's environment, returns a hash
                   7320: 
                   7321: =back
                   7322: 
                   7323: =head2 User Roles
                   7324: 
                   7325: =over 4
                   7326: 
                   7327: =item *
                   7328: 
                   7329: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7330: actions
                   7331:  F: full access
                   7332:  U,I,K: authentication modes (cxx only)
                   7333:  '': forbidden
                   7334:  1: user needs to choose course
                   7335:  2: browse allowed
                   7336: 
                   7337: =item *
                   7338: 
                   7339: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7340: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7341: and course level
                   7342: 
                   7343: =item *
                   7344: 
                   7345: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7346: explanation of a user role term
                   7347: 
                   7348: =back
                   7349: 
                   7350: =head2 User Modification
                   7351: 
                   7352: =over 4
                   7353: 
                   7354: =item *
                   7355: 
                   7356: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7357: user for the level given by URL.  Optional start and end dates (leave empty
                   7358: string or zero for "no date")
1.191     harris41 7359: 
                   7360: =item *
                   7361: 
1.243     albertel 7362: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7363: change a users, password, possible return values are: ok,
                   7364: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7365: refused
1.191     harris41 7366: 
                   7367: =item *
                   7368: 
1.243     albertel 7369: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7370: 
                   7371: =item *
                   7372: 
1.243     albertel 7373: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7374: modify user
1.191     harris41 7375: 
                   7376: =item *
                   7377: 
1.286     matthew  7378: modifystudent
                   7379: 
                   7380: modify a students enrollment and identification information.
                   7381: The course id is resolved based on the current users environment.  
                   7382: This means the envoking user must be a course coordinator or otherwise
                   7383: associated with a course.
                   7384: 
1.297     matthew  7385: This call is essentially a wrapper for lonnet::modifyuser and
                   7386: lonnet::modify_student_enrollment
1.286     matthew  7387: 
                   7388: Inputs: 
                   7389: 
                   7390: =over 4
                   7391: 
                   7392: =item B<$udom> Students loncapa domain
                   7393: 
                   7394: =item B<$uname> Students loncapa login name
                   7395: 
                   7396: =item B<$uid> Students id/student number
                   7397: 
                   7398: =item B<$umode> Students authentication mode
                   7399: 
                   7400: =item B<$upass> Students password
                   7401: 
                   7402: =item B<$first> Students first name
                   7403: 
                   7404: =item B<$middle> Students middle name
                   7405: 
                   7406: =item B<$last> Students last name
                   7407: 
                   7408: =item B<$gene> Students generation
                   7409: 
                   7410: =item B<$usec> Students section in course
                   7411: 
                   7412: =item B<$end> Unix time of the roles expiration
                   7413: 
                   7414: =item B<$start> Unix time of the roles start date
                   7415: 
                   7416: =item B<$forceid> If defined, allow $uid to be changed
                   7417: 
                   7418: =item B<$desiredhome> server to use as home server for student
                   7419: 
                   7420: =back
1.297     matthew  7421: 
                   7422: =item *
                   7423: 
                   7424: modify_student_enrollment
                   7425: 
                   7426: Change a students enrollment status in a class.  The environment variable
                   7427: 'role.request.course' must be defined for this function to proceed.
                   7428: 
                   7429: Inputs:
                   7430: 
                   7431: =over 4
                   7432: 
                   7433: =item $udom, students domain
                   7434: 
                   7435: =item $uname, students name
                   7436: 
                   7437: =item $uid, students user id
                   7438: 
                   7439: =item $first, students first name
                   7440: 
                   7441: =item $middle
                   7442: 
                   7443: =item $last
                   7444: 
                   7445: =item $gene
                   7446: 
                   7447: =item $usec
                   7448: 
                   7449: =item $end
                   7450: 
                   7451: =item $start
                   7452: 
                   7453: =back
                   7454: 
1.191     harris41 7455: 
                   7456: =item *
                   7457: 
1.243     albertel 7458: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7459: custom role; give a custom role to a user for the level given by URL.  Specify
                   7460: name and domain of role author, and role name
1.191     harris41 7461: 
                   7462: =item *
                   7463: 
1.243     albertel 7464: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7465: 
                   7466: =item *
                   7467: 
1.243     albertel 7468: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7469: 
                   7470: =back
                   7471: 
                   7472: =head2 Course Infomation
                   7473: 
                   7474: =over 4
1.191     harris41 7475: 
                   7476: =item *
                   7477: 
1.631     albertel 7478: coursedescription($courseid) : returns a hash of information about the
                   7479: specified course id, including all environment settings for the
                   7480: course, the description of the course will be in the hash under the
                   7481: key 'description'
1.191     harris41 7482: 
                   7483: =item *
                   7484: 
1.624     albertel 7485: resdata($name,$domain,$type,@which) : request for current parameter
                   7486: setting for a specific $type, where $type is either 'course' or 'user',
                   7487: @what should be a list of parameters to ask about. This routine caches
                   7488: answers for 5 minutes.
1.243     albertel 7489: 
                   7490: =back
                   7491: 
                   7492: =head2 Course Modification
                   7493: 
                   7494: =over 4
1.191     harris41 7495: 
                   7496: =item *
                   7497: 
1.243     albertel 7498: writecoursepref($courseid,%prefs) : write preferences (environment
                   7499: database) for a course
1.191     harris41 7500: 
                   7501: =item *
                   7502: 
1.243     albertel 7503: createcourse($udom,$description,$url) : make/modify course
                   7504: 
                   7505: =back
                   7506: 
                   7507: =head2 Resource Subroutines
                   7508: 
                   7509: =over 4
1.191     harris41 7510: 
                   7511: =item *
                   7512: 
1.243     albertel 7513: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7514: 
                   7515: =item *
                   7516: 
1.243     albertel 7517: repcopy($filename) : subscribes to the requested file, and attempts to
                   7518: replicate from the owning library server, Might return
1.607     raeburn  7519: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7520: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7521: resource. Expects the local filesystem pathname
                   7522: (/home/httpd/html/res/....)
                   7523: 
                   7524: =back
                   7525: 
                   7526: =head2 Resource Information
                   7527: 
                   7528: =over 4
1.191     harris41 7529: 
                   7530: =item *
                   7531: 
1.243     albertel 7532: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7533: a vairety of different possible values, $varname should be a request
                   7534: string, and the other parameters can be used to specify who and what
                   7535: one is asking about.
                   7536: 
                   7537: Possible values for $varname are environment.lastname (or other item
                   7538: from the envirnment hash), user.name (or someother aspect about the
                   7539: user), resource.0.maxtries (or some other part and parameter of a
                   7540: resource)
1.204     albertel 7541: 
                   7542: =item *
                   7543: 
1.243     albertel 7544: directcondval($number) : get current value of a condition; reads from a state
                   7545: string
1.204     albertel 7546: 
                   7547: =item *
                   7548: 
1.243     albertel 7549: condval($condidx) : value of condition index based on state
1.204     albertel 7550: 
                   7551: =item *
                   7552: 
1.243     albertel 7553: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7554: resource's metadata, $what should be either a specific key, or either
                   7555: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7556: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7557: 
                   7558: this function automatically caches all requests
1.191     harris41 7559: 
                   7560: =item *
                   7561: 
1.243     albertel 7562: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7563: network of library servers; returns file handle of where SQL and regex results
                   7564: will be stored for query
1.191     harris41 7565: 
                   7566: =item *
                   7567: 
1.243     albertel 7568: symbread($filename) : return symbolic list entry (filename argument optional);
                   7569: returns the data handle
1.191     harris41 7570: 
                   7571: =item *
                   7572: 
1.243     albertel 7573: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7574: a possible symb for the URL in $thisfn, and if is an encryypted
                   7575: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7576: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7577: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7578: 
1.191     harris41 7579: 
                   7580: =item *
                   7581: 
1.243     albertel 7582: symbclean($symb) : removes versions numbers from a symb, returns the
                   7583: cleaned symb
1.191     harris41 7584: 
                   7585: =item *
                   7586: 
1.243     albertel 7587: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7588: course map, user must be in a course for it to work.
1.191     harris41 7589: 
                   7590: =item *
                   7591: 
1.243     albertel 7592: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7593: 
                   7594: =item *
                   7595: 
1.243     albertel 7596: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7597: a random seed, all arguments are optional, if they aren't sent it uses the
                   7598: environment to derive them. Note: if symb isn't sent and it can't get one
                   7599: from &symbread it will use the current time as its return value
1.191     harris41 7600: 
                   7601: =item *
                   7602: 
1.243     albertel 7603: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7604: unfakeable, receipt
1.191     harris41 7605: 
                   7606: =item *
                   7607: 
1.620     albertel 7608: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7609: 
                   7610: =item *
                   7611: 
1.243     albertel 7612: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7613: 
                   7614: =item *
                   7615: 
1.243     albertel 7616: 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 7617: 
                   7618: =item *
                   7619: 
1.243     albertel 7620: 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 7621: 
                   7622: =item *
                   7623: 
1.243     albertel 7624: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7625: 
                   7626: =item *
                   7627: 
1.243     albertel 7628: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7629: forcing spreadsheet to reevaluate the resource scores next time.
                   7630: 
                   7631: =back
                   7632: 
                   7633: =head2 Storing/Retreiving Data
                   7634: 
                   7635: =over 4
1.191     harris41 7636: 
                   7637: =item *
                   7638: 
1.243     albertel 7639: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7640: for this url; hashref needs to be given and should be a \%hashname; the
                   7641: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7642: be derived from the env
1.191     harris41 7643: 
                   7644: =item *
                   7645: 
1.243     albertel 7646: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7647: uses critical subroutine
1.191     harris41 7648: 
                   7649: =item *
                   7650: 
1.243     albertel 7651: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7652: all args are optional
1.191     harris41 7653: 
                   7654: =item *
                   7655: 
1.717     albertel 7656: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7657: dumps the complete (or key matching regexp) namespace into a hash
                   7658: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7659: normally &store()ed into
                   7660: 
                   7661: $range should be either an integer '100' (give me the first 100
                   7662:                                            matching records)
                   7663:               or be  two integers sperated by a - with no spaces
                   7664:                  '30-50' (give me the 30th through the 50th matching
                   7665:                           records)
                   7666: 
                   7667: 
                   7668: =item *
                   7669: 
                   7670: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7671: replaces a &store() version of data with a replacement set of data
                   7672: for a particular resource in a namespace passed in the $storehash hash 
                   7673: reference
                   7674: 
                   7675: =item *
                   7676: 
1.243     albertel 7677: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7678: works very similar to store/cstore, but all data is stored in a
                   7679: temporary location and can be reset using tmpreset, $storehash should
                   7680: be a hash reference, returns nothing on success
1.191     harris41 7681: 
                   7682: =item *
                   7683: 
1.243     albertel 7684: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7685: similar to restore, but all data is stored in a temporary location and
                   7686: can be reset using tmpreset. Returns a hash of values on success,
                   7687: error string otherwise.
1.191     harris41 7688: 
                   7689: =item *
                   7690: 
1.243     albertel 7691: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7692: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7693: 
                   7694: =item *
                   7695: 
1.243     albertel 7696: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7697: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7698: 
                   7699: =item *
                   7700: 
1.243     albertel 7701: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7702: namesp ($udom and $uname are optional)
1.191     harris41 7703: 
                   7704: =item *
                   7705: 
1.702     albertel 7706: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7707: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7708: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7709: 
1.702     albertel 7710: $range should be either an integer '100' (give me the first 100
                   7711:                                            matching records)
                   7712:               or be  two integers sperated by a - with no spaces
                   7713:                  '30-50' (give me the 30th through the 50th matching
                   7714:                           records)
1.449     matthew  7715: =item *
                   7716: 
                   7717: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7718: $store can be a scalar, an array reference, or if the amount to be 
                   7719: incremented is > 1, a hash reference.
                   7720: 
                   7721: ($udom and $uname are optional)
1.191     harris41 7722: 
                   7723: =item *
                   7724: 
1.243     albertel 7725: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7726: ($udom and $uname are optional)
1.191     harris41 7727: 
                   7728: =item *
                   7729: 
1.243     albertel 7730: cput($namespace,$storehash,$udom,$uname) : critical put
                   7731: ($udom and $uname are optional)
1.191     harris41 7732: 
                   7733: =item *
                   7734: 
1.748     albertel 7735: newput($namespace,$storehash,$udom,$uname) :
                   7736: 
                   7737: Attempts to store the items in the $storehash, but only if they don't
                   7738: currently exist, if this succeeds you can be certain that you have 
                   7739: successfully created a new key value pair in the $namespace db.
                   7740: 
                   7741: 
                   7742: Args:
                   7743:  $namespace: name of database to store values to
                   7744:  $storehash: hashref to store to the db
                   7745:  $udom: (optional) domain of user containing the db
                   7746:  $uname: (optional) name of user caontaining the db
                   7747: 
                   7748: Returns:
                   7749:  'ok' -> succeeded in storing all keys of $storehash
                   7750:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7751:                         least <key> already existed in the db (other
                   7752:                         requested keys may also already exist)
                   7753:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7754:  'con_lost' -> unable to contact request server
                   7755:  'refused' -> action was not allowed by remote machine
                   7756: 
                   7757: 
                   7758: =item *
                   7759: 
1.243     albertel 7760: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7761: reference filled in from namesp (encrypts the return communication)
                   7762: ($udom and $uname are optional)
1.191     harris41 7763: 
                   7764: =item *
                   7765: 
1.243     albertel 7766: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7767: critical subroutine
                   7768: 
                   7769: =back
                   7770: 
                   7771: =head2 Network Status Functions
                   7772: 
                   7773: =over 4
1.191     harris41 7774: 
                   7775: =item *
                   7776: 
                   7777: dirlist($uri) : return directory list based on URI
                   7778: 
                   7779: =item *
                   7780: 
1.243     albertel 7781: spareserver() : find server with least workload from spare.tab
                   7782: 
                   7783: =back
                   7784: 
                   7785: =head2 Apache Request
                   7786: 
                   7787: =over 4
1.191     harris41 7788: 
                   7789: =item *
                   7790: 
1.243     albertel 7791: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7792: localhost, posts hash
                   7793: 
                   7794: =back
                   7795: 
                   7796: =head2 Data to String to Data
                   7797: 
                   7798: =over 4
1.191     harris41 7799: 
                   7800: =item *
                   7801: 
1.243     albertel 7802: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7803: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7804: 
                   7805: =item *
                   7806: 
1.243     albertel 7807: hashref2str($hashref) : convert a hashref into a string complete with
                   7808: escaping and '=' and '&' separators, supports elements that are
                   7809: arrayrefs and hashrefs
1.191     harris41 7810: 
                   7811: =item *
                   7812: 
1.243     albertel 7813: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7814: with escaping and '&' separators, supports elements that are arrayrefs
                   7815: and hashrefs
1.191     harris41 7816: 
                   7817: =item *
                   7818: 
1.243     albertel 7819: str2hash($string) : convert string to hash using unescaping and
                   7820: splitting on '=' and '&', supports elements that are arrayrefs and
                   7821: hashrefs
1.191     harris41 7822: 
                   7823: =item *
                   7824: 
1.243     albertel 7825: str2array($string) : convert string to hash using unescaping and
                   7826: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7827: 
                   7828: =back
                   7829: 
                   7830: =head2 Logging Routines
                   7831: 
                   7832: =over 4
                   7833: 
                   7834: These routines allow one to make log messages in the lonnet.log and
                   7835: lonnet.perm logfiles.
1.191     harris41 7836: 
                   7837: =item *
                   7838: 
1.243     albertel 7839: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 7840: 
                   7841: =item *
                   7842: 
1.243     albertel 7843: logthis() : append message to the normal lonnet.log file, it gets
                   7844: preiodically rolled over and deleted.
1.191     harris41 7845: 
                   7846: =item *
                   7847: 
1.243     albertel 7848: logperm() : append a permanent message to lonnet.perm.log, this log
                   7849: file never gets deleted by any automated portion of the system, only
                   7850: messages of critical importance should go in here.
                   7851: 
                   7852: =back
                   7853: 
                   7854: =head2 General File Helper Routines
                   7855: 
                   7856: =over 4
1.191     harris41 7857: 
                   7858: =item *
                   7859: 
1.481     raeburn  7860: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7861: (a) files in /uploaded
                   7862:   (i) If a local copy of the file exists - 
                   7863:       compares modification date of local copy with last-modified date for 
                   7864:       definitive version stored on home server for course. If local copy is 
                   7865:       stale, requests a new version from the home server and stores it. 
                   7866:       If the original has been removed from the home server, then local copy 
                   7867:       is unlinked.
                   7868:   (ii) If local copy does not exist -
                   7869:       requests the file from the home server and stores it. 
                   7870:   
                   7871:   If $caller is 'uploadrep':  
                   7872:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7873:     for request for files originally uploaded via DOCS. 
                   7874:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7875:   
                   7876:   Otherwise:
                   7877:      This indicates a call from the content generation phase of the request.
                   7878:      -  returns the entire contents of the file or -1.
                   7879:      
                   7880: (b) files in /res
                   7881:    - returns the entire contents of a file or -1; 
                   7882:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7883: 
1.712     albertel 7884: 
                   7885: =item *
                   7886: 
                   7887: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   7888:                   reference
                   7889: 
                   7890: returns either a stat() list of data about the file or an empty list
                   7891: if the file doesn't exist or couldn't find out about it (connection
                   7892: problems or user unknown)
                   7893: 
1.191     harris41 7894: =item *
                   7895: 
1.243     albertel 7896: filelocation($dir,$file) : returns file system location of a file
                   7897: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7898: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7899: and a file of ../bob will become /a/bob)
1.191     harris41 7900: 
                   7901: =item *
                   7902: 
                   7903: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7904: filelocation except for hrefs
                   7905: 
                   7906: =item *
                   7907: 
                   7908: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7909: 
1.243     albertel 7910: =back
                   7911: 
1.608     albertel 7912: =head2 Usererfile file routines (/uploaded*)
                   7913: 
                   7914: =over 4
                   7915: 
                   7916: =item *
                   7917: 
                   7918: userfileupload(): main rotine for putting a file in a user or course's
                   7919:                   filespace, arguments are,
                   7920: 
1.620     albertel 7921:  formname - required - this is the name of the element in $env where the
1.608     albertel 7922:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7923:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7924:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7925:  coursedoc - if true, store the file in the course of the active role
                   7926:              of the current user
                   7927:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7928:          if undefined, it will be placed in "unknown"
                   7929: 
                   7930:  (This routine calls clean_filename() to remove any dangerous
                   7931:  characters from the filename, and then calls finuserfileupload() to
                   7932:  complete the transaction)
                   7933: 
                   7934:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7935:  and /adm/notfound.html if unsuccessful
                   7936: 
                   7937: =item *
                   7938: 
                   7939: clean_filename(): routine for cleaing a filename up for storage in
                   7940:                  userfile space, argument is:
                   7941: 
                   7942:  filename - proposed filename
                   7943: 
                   7944: returns: the new clean filename
                   7945: 
                   7946: =item *
                   7947: 
                   7948: finishuserfileupload(): routine that creaes and sends the file to
                   7949: userspace, probably shouldn't be called directly
                   7950: 
                   7951:   docuname: username or courseid of destination for the file
                   7952:   docudom: domain of user/course of destination for the file
                   7953:   formname: same as for userfileupload()
                   7954:   fname: filename (inculding subdirectories) for the file
                   7955: 
                   7956:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7957:  and /adm/notfound.html if unsuccessful
                   7958: 
                   7959: =item *
                   7960: 
                   7961: renameuserfile(): renames an existing userfile to a new name
                   7962: 
                   7963:   Args:
                   7964:    docuname: username or courseid of destination for the file
                   7965:    docudom: domain of user/course of destination for the file
                   7966:    old: current file name (including any subdirs under userfiles)
                   7967:    new: desired file name (including any subdirs under userfiles)
                   7968: 
                   7969: =item *
                   7970: 
                   7971: mkdiruserfile(): creates a directory is a userfiles dir
                   7972: 
                   7973:   Args:
                   7974:    docuname: username or courseid of destination for the file
                   7975:    docudom: domain of user/course of destination for the file
                   7976:    dir: dir to create (including any subdirs under userfiles)
                   7977: 
                   7978: =item *
                   7979: 
                   7980: removeuserfile(): removes a file that exists in userfiles
                   7981: 
                   7982:   Args:
                   7983:    docuname: username or courseid of destination for the file
                   7984:    docudom: domain of user/course of destination for the file
                   7985:    fname: filname to delete (including any subdirs under userfiles)
                   7986: 
                   7987: =item *
                   7988: 
                   7989: removeuploadedurl(): convience function for removeuserfile()
                   7990: 
                   7991:   Args:
                   7992:    url:  a full /uploaded/... url to delete
                   7993: 
1.747     albertel 7994: =item * 
                   7995: 
                   7996: get_portfile_permissions():
                   7997:   Args:
                   7998:     domain: domain of user or course contain the portfolio files
                   7999:     user: name of user or num of course contain the portfolio files
                   8000:   Returns:
                   8001:     hashref of a dump of the proper file_permissions.db
                   8002:    
                   8003: 
                   8004: =item * 
                   8005: 
                   8006: get_access_controls():
                   8007: 
                   8008: Args:
                   8009:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8010:   group: (optional) the group you want the files associated with
                   8011:   file: (optional) the file you want access info on
                   8012: 
                   8013: Returns:
1.749     raeburn  8014:     a hash (keys are file names) of hashes containing
                   8015:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8016:         values are XML containing access control settings (see below) 
1.747     albertel 8017: 
                   8018: Internal notes:
                   8019: 
1.749     raeburn  8020:  access controls are stored in file_permissions.db as key=value pairs.
                   8021:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8022:         where scope -> public,guest,course,group,domains or users.
                   8023:               end -> UNIX time for end of access (0 -> no end date)
                   8024:               start -> UNIX time for start of access
                   8025: 
                   8026:     value -> XML description of access control
                   8027:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8028:             <start></start>
                   8029:             <end></end>
                   8030: 
                   8031:             <password></password>  for scope type = guest
                   8032: 
                   8033:             <domain></domain>     for scope type = course or group
                   8034:             <number></number>
                   8035:             <roles id="">
                   8036:              <role></role>
                   8037:              <access></access>
                   8038:              <section></section>
                   8039:              <group></group>
                   8040:             </roles>
                   8041: 
                   8042:             <dom></dom>         for scope type = domains
                   8043: 
                   8044:             <users>             for scope type = users
                   8045:              <user>
                   8046:               <uname></uname>
                   8047:               <udom></udom>
                   8048:              </user>
                   8049:             </users>
                   8050:            </scope> 
                   8051:               
                   8052:  Access data is also aggregated for each file in an additional key=value pair:
                   8053:  key -> path to file/file_name\0accesscontrol 
                   8054:  value -> reference to hash
                   8055:           hash contains key = value pairs
                   8056:           where key = uniqueID:scope_end_start
                   8057:                 value = UNIX time record was last updated
                   8058: 
                   8059:           Used to improve speed of look-ups of access controls for each file.  
                   8060:  
                   8061:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8062: 
                   8063: parse_access_controls():
                   8064: 
                   8065: Parses XML of an access control record
                   8066: Args
                   8067: 1. Text string (XML) of access comtrol record
                   8068: 
                   8069: Returns:
                   8070: 1. Hash of access control settings. 
                   8071: 
                   8072: modify_access_controls():
                   8073: 
                   8074: Modifies access controls for a portfolio file
                   8075: Args
                   8076: 1. file name
                   8077: 2. reference to hash of required changes,
                   8078: 3. domain
                   8079: 4. username
                   8080:   where domain,username are the domain of the portfolio owner 
                   8081:   (either a user or a course) 
                   8082: 
                   8083: Returns:
                   8084: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8085: 2. result of deletions ('ok' or 'error', with error message).
                   8086: 3. reference to hash of any new or updated access controls.
                   8087: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8088:    key = integer (inbound ID)
                   8089:    value = uniqueID  
1.747     albertel 8090: 
1.608     albertel 8091: =back
                   8092: 
1.243     albertel 8093: =head2 HTTP Helper Routines
                   8094: 
                   8095: =over 4
                   8096: 
1.191     harris41 8097: =item *
                   8098: 
                   8099: escape() : unpack non-word characters into CGI-compatible hex codes
                   8100: 
                   8101: =item *
                   8102: 
                   8103: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8104: 
1.243     albertel 8105: =back
                   8106: 
                   8107: =head1 PRIVATE SUBROUTINES
                   8108: 
                   8109: =head2 Underlying communication routines (Shouldn't call)
                   8110: 
                   8111: =over 4
                   8112: 
                   8113: =item *
                   8114: 
                   8115: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8116: 
                   8117: =item *
                   8118: 
                   8119: reply() : uses subreply to send a message to remote machine, logs all failures
                   8120: 
                   8121: =item *
                   8122: 
                   8123: critical() : passes a critical message to another server; if cannot
                   8124: get through then place message in connection buffer directory and
                   8125: returns con_delayed, if incapable of saving message, returns
                   8126: con_failed
                   8127: 
                   8128: =item *
                   8129: 
                   8130: reconlonc() : tries to reconnect lonc client processes.
                   8131: 
                   8132: =back
                   8133: 
                   8134: =head2 Resource Access Logging
                   8135: 
                   8136: =over 4
                   8137: 
                   8138: =item *
                   8139: 
                   8140: flushcourselogs() : flush (save) buffer logs and access logs
                   8141: 
                   8142: =item *
                   8143: 
                   8144: courselog($what) : save message for course in hash
                   8145: 
                   8146: =item *
                   8147: 
                   8148: courseacclog($what) : save message for course using &courselog().  Perform
                   8149: special processing for specific resource types (problems, exams, quizzes, etc).
                   8150: 
1.191     harris41 8151: =item *
                   8152: 
                   8153: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8154: as a PerlChildExitHandler
1.243     albertel 8155: 
                   8156: =back
                   8157: 
                   8158: =head2 Other
                   8159: 
                   8160: =over 4
                   8161: 
                   8162: =item *
                   8163: 
                   8164: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8165: 
                   8166: =back
                   8167: 
                   8168: =cut

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