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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.757   ! albertel    4: # $Id: lonnet.pm,v 1.756 2006/06/22 14:48:40 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) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.374     www       295: # ------------------------------------------- Transfer profile into environment
                    296: 
                    297: sub transfer_profile_to_env {
                    298:     my ($lonidsdir,$handle)=@_;
1.720     albertel  299:     if (!defined($lonidsdir)) {
                    300: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    301:     }
                    302:     if (!defined($handle)) {
                    303:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    304:     }
                    305: 
1.374     www       306:     my @profile;
                    307:     {
1.448     albertel  308: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       309: 	flock($idf,LOCK_SH);
                    310: 	@profile=<$idf>;
1.448     albertel  311: 	close($idf);
1.374     www       312:     }
                    313:     my $envi;
1.433     matthew   314:     my %Remove;
1.374     www       315:     for ($envi=0;$envi<=$#profile;$envi++) {
                    316: 	chomp($profile[$envi]);
1.690     albertel  317: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  318: 	$envname=&unescape($envname);
                    319: 	$envvalue=&unescape($envvalue);
1.619     albertel  320: 	$env{$envname} = $envvalue;
1.433     matthew   321:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    322:             if ($time < time-300) {
                    323:                 $Remove{$key}++;
                    324:             }
                    325:         }
                    326:     }
1.619     albertel  327:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   328:     foreach my $expired_key (keys(%Remove)) {
                    329:         &delenv($expired_key);
1.374     www       330:     }
1.1       albertel  331: }
                    332: 
1.5       www       333: # ---------------------------------------------------------- Append Environment
                    334: 
                    335: sub appenv {
1.6       www       336:     my %newenv=@_;
1.692     albertel  337:     foreach my $key (keys(%newenv)) {
                    338: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  339:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  340:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       341:                 .'</font>');
1.692     albertel  342: 	    delete($newenv{$key});
1.35      www       343:         } else {
1.692     albertel  344:             $env{$key}=$newenv{$key};
1.35      www       345:         }
1.191     harris41  346:     }
1.95      www       347: 
                    348:     my $lockfh;
1.620     albertel  349:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  350: 	return 'error: '.$!;
1.95      www       351:     }
                    352:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  353:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       354:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  355:          close($lockfh);
1.95      www       356:          return 'error: '.$!;
                    357:     }
                    358: 
1.6       www       359:     my @oldenv;
                    360:     {
1.448     albertel  361: 	my $fh;
1.620     albertel  362: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  363: 	    return 'error: '.$!;
                    364: 	}
                    365: 	@oldenv=<$fh>;
                    366: 	close($fh);
1.6       www       367:     }
                    368:     for (my $i=0; $i<=$#oldenv; $i++) {
                    369:         chomp($oldenv[$i]);
1.9       www       370:         if ($oldenv[$i] ne '') {
1.690     albertel  371: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.726     albertel  372: 	    $name=&unescape($name);
                    373: 	    $value=&unescape($value);
1.448     albertel  374: 	    unless (defined($newenv{$name})) {
                    375: 		$newenv{$name}=$value;
                    376: 	    }
1.9       www       377:         }
1.6       www       378:     }
                    379:     {
1.448     albertel  380: 	my $fh;
1.620     albertel  381: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  382: 	    return 'error';
                    383: 	}
                    384: 	my $newname;
                    385: 	foreach $newname (keys %newenv) {
1.726     albertel  386: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
1.448     albertel  387: 	}
                    388: 	close($fh);
1.56      www       389:     }
1.448     albertel  390: 	
                    391:     close($lockfh);
1.56      www       392:     return 'ok';
                    393: }
                    394: # ----------------------------------------------------- Delete from Environment
                    395: 
                    396: sub delenv {
                    397:     my $delthis=shift;
                    398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  399:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       400:                 "Attempt to delete from environment ".$delthis);
                    401:         return 'error';
                    402:     }
                    403:     my @oldenv;
                    404:     {
1.448     albertel  405: 	my $fh;
1.620     albertel  406: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  407: 	    return 'error';
                    408: 	}
                    409: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  410: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  411: 		     'Could not obtain shared lock in delenv: '.$!);
                    412: 	    close($fh);
                    413: 	    return 'error: '.$!;
                    414: 	}
                    415: 	@oldenv=<$fh>;
                    416: 	close($fh);
1.56      www       417:     }
                    418:     {
1.448     albertel  419: 	my $fh;
1.620     albertel  420: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  421: 	    return 'error';
                    422: 	}
                    423: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  424: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  425: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    426: 	    close($fh);
                    427: 	    return 'error: '.$!;
                    428: 	}
1.692     albertel  429: 	foreach my $cur_key (@oldenv) {
1.726     albertel  430: 	    my $unescaped_cur_key = &unescape($cur_key);
                    431: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    432:                 my ($key) = split('=',$cur_key,2);
                    433: 		$key = &unescape($key);
1.619     albertel  434:                 delete($env{$key});
1.473     matthew   435:             } else {
1.692     albertel  436:                 print $fh $cur_key; 
1.473     matthew   437:             }
1.448     albertel  438: 	}
                    439: 	close($fh);
1.5       www       440:     }
                    441:     return 'ok';
1.369     albertel  442: }
                    443: 
                    444: # ------------------------------------------ Find out current server userload
                    445: # there is a copy in lond
                    446: sub userload {
                    447:     my $numusers=0;
                    448:     {
                    449: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    450: 	my $filename;
                    451: 	my $curtime=time;
                    452: 	while ($filename=readdir(LONIDS)) {
                    453: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  454: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  455: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  456: 	}
                    457: 	closedir(LONIDS);
                    458:     }
                    459:     my $userloadpercent=0;
                    460:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    461:     if ($maxuserload) {
1.371     albertel  462: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  463:     }
1.372     albertel  464:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  465:     return $userloadpercent;
1.283     www       466: }
                    467: 
                    468: # ------------------------------------------ Fight off request when overloaded
                    469: 
                    470: sub overloaderror {
                    471:     my ($r,$checkserver)=@_;
                    472:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    473:     my $loadavg;
                    474:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  475:        open(my $loadfile,'/proc/loadavg');
1.283     www       476:        $loadavg=<$loadfile>;
                    477:        $loadavg =~ s/\s.*//g;
1.285     matthew   478:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  479:        close($loadfile);
1.283     www       480:     } else {
                    481:        $loadavg=&reply('load',$checkserver);
                    482:     }
1.285     matthew   483:     my $overload=$loadavg-100;
1.283     www       484:     if ($overload>0) {
1.285     matthew   485: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       486:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       487:         return 413;
1.283     www       488:     }    
                    489:     return '';
1.5       www       490: }
1.1       albertel  491: 
                    492: # ------------------------------ Find server with least workload from spare.tab
1.11      www       493: 
1.1       albertel  494: sub spareserver {
1.670     albertel  495:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  496:     my $tryserver;
                    497:     my $spareserver='';
1.370     albertel  498:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    499:     my $lowestserver=$loadpercent > $userloadpercent?
                    500: 	             $loadpercent :  $userloadpercent;
1.670     albertel  501:     foreach $tryserver (keys(%spareid)) {
                    502: 	my $loadans=&reply('load',$tryserver);
                    503: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  504: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    505: 	    next; #didn't get a number from the server
                    506: 	}
                    507: 	my $answer;
                    508: 	if ($loadans =~ /\d/) {
                    509: 	    if ($userloadans =~ /\d/) {
                    510: 		#both are numbers, pick the bigger one
                    511: 		$answer=$loadans > $userloadans?
                    512: 		    $loadans :  $userloadans;
                    513: 	    } else {
                    514: 		$answer = $loadans;
                    515: 	    }
                    516: 	} else {
                    517: 	    $answer = $userloadans;
                    518: 	}
                    519: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  520: 	    if ($want_server_name) {
                    521: 		$spareserver=$tryserver;
                    522: 	    } else {
                    523: 		$spareserver="http://$hostname{$tryserver}";
                    524: 	    }
1.411     albertel  525: 	    $lowestserver=$answer;
                    526: 	}
1.370     albertel  527:     }
1.1       albertel  528:     return $spareserver;
1.202     matthew   529: }
                    530: 
                    531: # --------------------------------------------- Try to change a user's password
                    532: 
                    533: sub changepass {
                    534:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    535:     $currentpass = &escape($currentpass);
                    536:     $newpass     = &escape($newpass);
                    537:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    538: 		       $server);
                    539:     if (! $answer) {
                    540: 	&logthis("No reply on password change request to $server ".
                    541: 		 "by $uname in domain $udom.");
                    542:     } elsif ($answer =~ "^ok") {
                    543:         &logthis("$uname in $udom successfully changed their password ".
                    544: 		 "on $server.");
                    545:     } elsif ($answer =~ "^pwchange_failure") {
                    546: 	&logthis("$uname in $udom was unable to change their password ".
                    547: 		 "on $server.  The action was blocked by either lcpasswd ".
                    548: 		 "or pwchange");
                    549:     } elsif ($answer =~ "^non_authorized") {
                    550:         &logthis("$uname in $udom did not get their password correct when ".
                    551: 		 "attempting to change it on $server.");
                    552:     } elsif ($answer =~ "^auth_mode_error") {
                    553:         &logthis("$uname in $udom attempted to change their password despite ".
                    554: 		 "not being locally or internally authenticated on $server.");
                    555:     } elsif ($answer =~ "^unknown_user") {
                    556:         &logthis("$uname in $udom attempted to change their password ".
                    557: 		 "on $server but were unable to because $server is not ".
                    558: 		 "their home server.");
                    559:     } elsif ($answer =~ "^refused") {
                    560: 	&logthis("$server refused to change $uname in $udom password because ".
                    561: 		 "it was sent an unencrypted request to change the password.");
                    562:     }
                    563:     return $answer;
1.1       albertel  564: }
                    565: 
1.169     harris41  566: # ----------------------- Try to determine user's current authentication scheme
                    567: 
                    568: sub queryauthenticate {
                    569:     my ($uname,$udom)=@_;
1.456     albertel  570:     my $uhome=&homeserver($uname,$udom);
                    571:     if (!$uhome) {
                    572: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    573: 	return 'no_host';
                    574:     }
                    575:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    576:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    577: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  578:     }
1.456     albertel  579:     return $answer;
1.169     harris41  580: }
                    581: 
1.1       albertel  582: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       583: 
1.1       albertel  584: sub authenticate {
                    585:     my ($uname,$upass,$udom)=@_;
1.12      www       586:     $upass=escape($upass);
1.199     www       587:     $uname=~s/\W//g;
1.471     albertel  588:     my $uhome=&homeserver($uname,$udom);
                    589:     if (!$uhome) {
                    590: 	&logthis("User $uname at $udom is unknown in authenticate");
                    591: 	return 'no_host';
1.1       albertel  592:     }
1.471     albertel  593:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    594:     if ($answer eq 'authorized') {
                    595: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    596: 	return $uhome; 
                    597:     }
                    598:     if ($answer eq 'non_authorized') {
                    599: 	&logthis("User $uname at $udom rejected by $uhome");
                    600: 	return 'no_host'; 
1.9       www       601:     }
1.471     albertel  602:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  603:     return 'no_host';
                    604: }
                    605: 
                    606: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       607: 
1.599     albertel  608: my %homecache;
1.1       albertel  609: sub homeserver {
1.230     stredwic  610:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  611:     my $index="$uname:$udom";
1.426     albertel  612: 
1.599     albertel  613:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  614:     my $tryserver;
                    615:     foreach $tryserver (keys %libserv) {
1.230     stredwic  616:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  617: 		 exists($badServerCache{$tryserver}));
1.1       albertel  618: 	if ($hostdom{$tryserver} eq $udom) {
                    619:            my $answer=reply("home:$udom:$uname",$tryserver);
                    620:            if ($answer eq 'found') { 
1.599     albertel  621: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  622:            } elsif ($answer eq 'no_host') {
                    623: 	       $badServerCache{$tryserver}=1;
1.221     matthew   624:            }
1.1       albertel  625:        }
                    626:     }    
                    627:     return 'no_host';
1.70      www       628: }
                    629: 
                    630: # ------------------------------------- Find the usernames behind a list of IDs
                    631: 
                    632: sub idget {
                    633:     my ($udom,@ids)=@_;
                    634:     my %returnhash=();
                    635:     
                    636:     my $tryserver;
                    637:     foreach $tryserver (keys %libserv) {
                    638:        if ($hostdom{$tryserver} eq $udom) {
                    639: 	  my $idlist=join('&',@ids);
                    640:           $idlist=~tr/A-Z/a-z/; 
                    641: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    642:           my @answer=();
1.76      www       643:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       644: 	      @answer=split(/\&/,$reply);
                    645:           }                    ;
                    646:           my $i;
                    647:           for ($i=0;$i<=$#ids;$i++) {
                    648:               if ($answer[$i]) {
                    649: 		  $returnhash{$ids[$i]}=$answer[$i];
                    650:               } 
                    651:           }
                    652:        }
                    653:     }    
                    654:     return %returnhash;
                    655: }
                    656: 
                    657: # ------------------------------------- Find the IDs behind a list of usernames
                    658: 
                    659: sub idrget {
                    660:     my ($udom,@unames)=@_;
                    661:     my %returnhash=();
1.191     harris41  662:     foreach (@unames) {
1.70      www       663:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  664:     }
1.70      www       665:     return %returnhash;
                    666: }
                    667: 
                    668: # ------------------------------- Store away a list of names and associated IDs
                    669: 
                    670: sub idput {
                    671:     my ($udom,%ids)=@_;
                    672:     my %servers=();
1.191     harris41  673:     foreach (keys %ids) {
1.487     albertel  674: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       675:         my $uhom=&homeserver($_,$udom);
                    676:         if ($uhom ne 'no_host') {
                    677:             my $id=&escape($ids{$_});
                    678:             $id=~tr/A-Z/a-z/;
                    679:             my $unam=&escape($_);
                    680: 	    if ($servers{$uhom}) {
                    681: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    682:             } else {
                    683:                 $servers{$uhom}=$id.'='.$unam;
                    684:             }
                    685:         }
1.191     harris41  686:     }
                    687:     foreach (keys %servers) {
1.70      www       688:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  689:     }
1.344     www       690: }
                    691: 
                    692: # --------------------------------------------------- Assign a key to a student
                    693: 
                    694: sub assign_access_key {
1.364     www       695: #
                    696: # a valid key looks like uname:udom#comments
                    697: # comments are being appended
                    698: #
1.498     www       699:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    700:     $kdom=
1.620     albertel  701:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       702:     $knum=
1.620     albertel  703:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       704:     $cdom=
1.620     albertel  705:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       706:     $cnum=
1.620     albertel  707:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    708:     $udom=$env{'user.name'} unless (defined($udom));
                    709:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       710:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       711:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  712:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       713:                                                   # assigned to this person
                    714:                                                   # - this should not happen,
1.345     www       715:                                                   # unless something went wrong
                    716:                                                   # the first time around
                    717: # ready to assign
1.364     www       718:         $logentry=$1.'; '.$logentry;
1.496     www       719:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       720:                                                  $kdom,$knum) eq 'ok') {
1.345     www       721: # key now belongs to user
1.346     www       722: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       723:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    724:                 &appenv('environment.'.$envkey => $ckey);
                    725:                 return 'ok';
                    726:             } else {
                    727:                 return 
                    728:   'error: Count not permanently assign key, will need to be re-entered later.';
                    729: 	    }
                    730:         } else {
                    731:             return 'error: Could not assign key, try again later.';
                    732:         }
1.364     www       733:     } elsif (!$existing{$ckey}) {
1.345     www       734: # the key does not exist
                    735: 	return 'error: The key does not exist';
                    736:     } else {
                    737: # the key is somebody else's
                    738: 	return 'error: The key is already in use';
                    739:     }
1.344     www       740: }
                    741: 
1.364     www       742: # ------------------------------------------ put an additional comment on a key
                    743: 
                    744: sub comment_access_key {
                    745: #
                    746: # a valid key looks like uname:udom#comments
                    747: # comments are being appended
                    748: #
                    749:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    750:     $cdom=
1.620     albertel  751:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       752:     $cnum=
1.620     albertel  753:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       754:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    755:     if ($existing{$ckey}) {
                    756:         $existing{$ckey}.='; '.$logentry;
                    757: # ready to assign
1.367     www       758:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       759:                                                  $cdom,$cnum) eq 'ok') {
                    760: 	    return 'ok';
                    761:         } else {
                    762: 	    return 'error: Count not store comment.';
                    763:         }
                    764:     } else {
                    765: # the key does not exist
                    766: 	return 'error: The key does not exist';
                    767:     }
                    768: }
                    769: 
1.344     www       770: # ------------------------------------------------------ Generate a set of keys
                    771: 
                    772: sub generate_access_keys {
1.364     www       773:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       774:     $cdom=
1.620     albertel  775:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       776:     $cnum=
1.620     albertel  777:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       778:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       779:     unless (($cdom) && ($cnum)) { return 0; }
                    780:     if ($number>10000) { return 0; }
                    781:     sleep(2); # make sure don't get same seed twice
                    782:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    783:     my $total=0;
                    784:     for (my $i=1;$i<=$number;$i++) {
                    785:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    786:                   sprintf("%lx",int(100000*rand)).'-'.
                    787:                   sprintf("%lx",int(100000*rand));
                    788:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    789:        $newkey=~s/0/h/g; # and also 0 and O
                    790:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    791:        if ($existing{$newkey}) {
                    792:            $i--;
                    793:        } else {
1.364     www       794: 	  if (&put('accesskeys',
                    795:               { $newkey => '# generated '.localtime().
1.620     albertel  796:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       797:                            '; '.$logentry },
                    798: 		   $cdom,$cnum) eq 'ok') {
1.344     www       799:               $total++;
                    800: 	  }
                    801:        }
                    802:     }
1.620     albertel  803:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       804:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    805:     return $total;
                    806: }
                    807: 
                    808: # ------------------------------------------------------- Validate an accesskey
                    809: 
                    810: sub validate_access_key {
                    811:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    812:     $cdom=
1.620     albertel  813:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       814:     $cnum=
1.620     albertel  815:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    816:     $udom=$env{'user.domain'} unless (defined($udom));
                    817:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       818:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  819:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       820: }
                    821: 
                    822: # ------------------------------------- Find the section of student in a course
1.652     albertel  823: sub devalidate_getsection_cache {
                    824:     my ($udom,$unam,$courseid)=@_;
                    825:     $courseid=~s/\_/\//g;
                    826:     $courseid=~s/^(\w)/\/$1/;
                    827:     my $hashid="$udom:$unam:$courseid";
                    828:     &devalidate_cache_new('getsection',$hashid);
                    829: }
1.298     matthew   830: 
                    831: sub getsection {
                    832:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  833:     my $cachetime=1800;
1.298     matthew   834:     $courseid=~s/\_/\//g;
                    835:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  836: 
                    837:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  838:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  839:     if (defined($cached)) { return $result; }
                    840: 
1.298     matthew   841:     my %Pending; 
                    842:     my %Expired;
                    843:     #
                    844:     # Each role can either have not started yet (pending), be active, 
                    845:     #    or have expired.
                    846:     #
                    847:     # If there is an active role, we are done.
                    848:     #
                    849:     # If there is more than one role which has not started yet, 
                    850:     #     choose the one which will start sooner
                    851:     # If there is one role which has not started yet, return it.
                    852:     #
                    853:     # If there is more than one expired role, choose the one which ended last.
                    854:     # If there is a role which has expired, return it.
                    855:     #
                    856:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    857:                         &homeserver($unam,$udom)))) {
                    858:         my ($key,$value)=split(/\=/,$_);
                    859:         $key=&unescape($key);
1.479     albertel  860:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   861:         my $section=$1;
                    862:         if ($key eq $courseid.'_st') { $section=''; }
                    863:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    864:         my $now=time;
1.548     albertel  865:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   866:             $Expired{$end}=$section;
                    867:             next;
                    868:         }
1.548     albertel  869:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   870:             $Pending{$start}=$section;
                    871:             next;
                    872:         }
1.599     albertel  873:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   874:     }
                    875:     #
                    876:     # Presumedly there will be few matching roles from the above
                    877:     # loop and the sorting time will be negligible.
                    878:     if (scalar(keys(%Pending))) {
                    879:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  880:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   881:     } 
                    882:     if (scalar(keys(%Expired))) {
                    883:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    884:         my $time = pop(@sorted);
1.599     albertel  885:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   886:     }
1.599     albertel  887:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   888: }
1.70      www       889: 
1.599     albertel  890: sub save_cache {
                    891:     &purge_remembered();
1.722     albertel  892:     #&Apache::loncommon::validate_page();
1.620     albertel  893:     undef(%env);
1.599     albertel  894: }
1.452     albertel  895: 
1.599     albertel  896: my $to_remember=-1;
                    897: my %remembered;
                    898: my %accessed;
                    899: my $kicks=0;
                    900: my $hits=0;
                    901: sub devalidate_cache_new {
                    902:     my ($name,$id,$debug) = @_;
                    903:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    904:     $id=&escape($name.':'.$id);
                    905:     $memcache->delete($id);
                    906:     delete($remembered{$id});
                    907:     delete($accessed{$id});
                    908: }
                    909: 
                    910: sub is_cached_new {
                    911:     my ($name,$id,$debug) = @_;
                    912:     $id=&escape($name.':'.$id);
                    913:     if (exists($remembered{$id})) {
                    914: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    915: 	$accessed{$id}=[&gettimeofday()];
                    916: 	$hits++;
                    917: 	return ($remembered{$id},1);
                    918:     }
                    919:     my $value = $memcache->get($id);
                    920:     if (!(defined($value))) {
                    921: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  922: 	return (undef,undef);
1.416     albertel  923:     }
1.599     albertel  924:     if ($value eq '__undef__') {
                    925: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    926: 	$value=undef;
                    927:     }
                    928:     &make_room($id,$value,$debug);
                    929:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    930:     return ($value,1);
                    931: }
                    932: 
                    933: sub do_cache_new {
                    934:     my ($name,$id,$value,$time,$debug) = @_;
                    935:     $id=&escape($name.':'.$id);
                    936:     my $setvalue=$value;
                    937:     if (!defined($setvalue)) {
                    938: 	$setvalue='__undef__';
                    939:     }
1.623     albertel  940:     if (!defined($time) ) {
                    941: 	$time=600;
                    942:     }
1.599     albertel  943:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  944:     $memcache->set($id,$setvalue,$time);
                    945:     # need to make a copy of $value
                    946:     #&make_room($id,$value,$debug);
1.599     albertel  947:     return $value;
                    948: }
                    949: 
                    950: sub make_room {
                    951:     my ($id,$value,$debug)=@_;
                    952:     $remembered{$id}=$value;
                    953:     if ($to_remember<0) { return; }
                    954:     $accessed{$id}=[&gettimeofday()];
                    955:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    956:     my $to_kick;
                    957:     my $max_time=0;
                    958:     foreach my $other (keys(%accessed)) {
                    959: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    960: 	    $to_kick=$other;
                    961: 	    $max_time=&tv_interval($accessed{$other});
                    962: 	}
                    963:     }
                    964:     delete($remembered{$to_kick});
                    965:     delete($accessed{$to_kick});
                    966:     $kicks++;
                    967:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  968:     return;
                    969: }
                    970: 
1.599     albertel  971: sub purge_remembered {
1.604     albertel  972:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    973:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  974:     undef(%remembered);
                    975:     undef(%accessed);
1.428     albertel  976: }
1.70      www       977: # ------------------------------------- Read an entry from a user's environment
                    978: 
                    979: sub userenvironment {
                    980:     my ($udom,$unam,@what)=@_;
                    981:     my %returnhash=();
                    982:     my @answer=split(/\&/,
                    983:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    984:                       &homeserver($unam,$udom)));
                    985:     my $i;
                    986:     for ($i=0;$i<=$#what;$i++) {
                    987: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    988:     }
                    989:     return %returnhash;
1.1       albertel  990: }
                    991: 
1.617     albertel  992: # ---------------------------------------------------------- Get a studentphoto
                    993: sub studentphoto {
                    994:     my ($udom,$unam,$ext) = @_;
                    995:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   996:     if (defined($env{'request.course.id'})) {
1.708     raeburn   997:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   998:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    999:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1000:             } else {
                   1001:                 my ($result,$perm_reqd)=
1.707     albertel 1002: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1003:                 if ($result eq 'ok') {
                   1004:                     if (!($perm_reqd eq 'yes')) {
                   1005:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1006:                     }
                   1007:                 }
                   1008:             }
                   1009:         }
                   1010:     } else {
                   1011:         my ($result,$perm_reqd) = 
1.707     albertel 1012: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1013:         if ($result eq 'ok') {
                   1014:             if (!($perm_reqd eq 'yes')) {
                   1015:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1016:             }
                   1017:         }
                   1018:     }
                   1019:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1020: }
                   1021: 
                   1022: sub retrievestudentphoto {
                   1023:     my ($udom,$unam,$ext,$type) = @_;
                   1024:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1025:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1026:     if ($ret eq 'ok') {
                   1027:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1028:         if ($type eq 'thumbnail') {
                   1029:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1030:         }
                   1031:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1032:         return $tokenurl;
                   1033:     } else {
                   1034:         if ($type eq 'thumbnail') {
                   1035:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1036:         } else { 
                   1037:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1038:         }
1.617     albertel 1039:     }
                   1040: }
                   1041: 
1.263     www      1042: # -------------------------------------------------------------------- New chat
                   1043: 
                   1044: sub chatsend {
1.724     raeburn  1045:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1046:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1047:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1048:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1049:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1050: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1051: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1052: }
                   1053: 
                   1054: # ------------------------------------------ Find current version of a resource
                   1055: 
                   1056: sub getversion {
                   1057:     my $fname=&clutter(shift);
                   1058:     unless ($fname=~/^\/res\//) { return -1; }
                   1059:     return &currentversion(&filelocation('',$fname));
                   1060: }
                   1061: 
                   1062: sub currentversion {
                   1063:     my $fname=shift;
1.599     albertel 1064:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1065:     if (defined($cached)) { return $result; }
1.292     www      1066:     my $author=$fname;
                   1067:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1068:     my ($udom,$uname)=split(/\//,$author);
                   1069:     my $home=homeserver($uname,$udom);
                   1070:     if ($home eq 'no_host') { 
                   1071:         return -1; 
                   1072:     }
                   1073:     my $answer=reply("currentversion:$fname",$home);
                   1074:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1075: 	return -1;
                   1076:     }
1.599     albertel 1077:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1078: }
                   1079: 
1.1       albertel 1080: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1081: 
1.1       albertel 1082: sub subscribe {
                   1083:     my $fname=shift;
1.312     www      1084:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1085:     $fname=~s/[\n\r]//g;
1.1       albertel 1086:     my $author=$fname;
                   1087:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1088:     my ($udom,$uname)=split(/\//,$author);
                   1089:     my $home=homeserver($uname,$udom);
1.335     albertel 1090:     if ($home eq 'no_host') {
                   1091:         return 'not_found';
1.1       albertel 1092:     }
                   1093:     my $answer=reply("sub:$fname",$home);
1.64      www      1094:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1095: 	$answer.=' by '.$home;
                   1096:     }
1.1       albertel 1097:     return $answer;
                   1098: }
                   1099:     
1.8       www      1100: # -------------------------------------------------------------- Replicate file
                   1101: 
                   1102: sub repcopy {
                   1103:     my $filename=shift;
1.23      www      1104:     $filename=~s/\/+/\//g;
1.607     raeburn  1105:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1106:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1107:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1108: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1109: 	return &repcopy_userfile($filename);
                   1110:     }
1.532     albertel 1111:     $filename=~s/[\n\r]//g;
1.8       www      1112:     my $transname="$filename.in.transfer";
1.607     raeburn  1113:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1114:     my $remoteurl=subscribe($filename);
1.64      www      1115:     if ($remoteurl =~ /^con_lost by/) {
                   1116: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1117:            return 'unavailable';
1.8       www      1118:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1119: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1120: 	   return 'not_found';
1.64      www      1121:     } elsif ($remoteurl =~ /^rejected by/) {
                   1122: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1123:            return 'forbidden';
1.20      www      1124:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1125:            return 'ok';
1.8       www      1126:     } else {
1.290     www      1127:         my $author=$filename;
                   1128:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1129:         my ($udom,$uname)=split(/\//,$author);
                   1130:         my $home=homeserver($uname,$udom);
                   1131:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1132:            my @parts=split(/\//,$filename);
                   1133:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1134:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1135:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1136: 	       return 'bad_request';
1.8       www      1137:            }
                   1138:            my $count;
                   1139:            for ($count=5;$count<$#parts;$count++) {
                   1140:                $path.="/$parts[$count]";
                   1141:                if ((-e $path)!=1) {
                   1142: 		   mkdir($path,0777);
                   1143:                }
                   1144:            }
                   1145:            my $ua=new LWP::UserAgent;
                   1146:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1147:            my $response=$ua->request($request,$transname);
                   1148:            if ($response->is_error()) {
                   1149: 	       unlink($transname);
                   1150:                my $message=$response->status_line;
1.672     albertel 1151:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1152:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1153:                return 'unavailable';
1.8       www      1154:            } else {
1.16      www      1155: 	       if ($remoteurl!~/\.meta$/) {
                   1156:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1157:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1158:                   if ($mresponse->is_error()) {
                   1159: 		      unlink($filename.'.meta');
                   1160:                       &logthis(
1.672     albertel 1161:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1162:                   }
                   1163: 	       }
1.8       www      1164:                rename($transname,$filename);
1.607     raeburn  1165:                return 'ok';
1.8       www      1166:            }
1.290     www      1167:        }
1.8       www      1168:     }
1.330     www      1169: }
                   1170: 
                   1171: # ------------------------------------------------ Get server side include body
                   1172: sub ssi_body {
1.381     albertel 1173:     my ($filelink,%form)=@_;
1.606     matthew  1174:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1175:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1176:     }
1.330     www      1177:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1178:                                      &ssi($filelink,%form));
1.565     albertel 1179:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1180:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1181:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1182:     return $output;
1.8       www      1183: }
                   1184: 
1.15      www      1185: # --------------------------------------------------------- Server Side Include
                   1186: 
                   1187: sub ssi {
                   1188: 
1.23      www      1189:     my ($fn,%form)=@_;
1.15      www      1190: 
                   1191:     my $ua=new LWP::UserAgent;
1.23      www      1192:     
                   1193:     my $request;
1.711     albertel 1194: 
                   1195:     $form{'no_update_last_known'}=1;
                   1196: 
1.23      www      1197:     if (%form) {
                   1198:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1199:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1200:     } else {
                   1201:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1202:     }
                   1203: 
1.15      www      1204:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1205:     my $response=$ua->request($request);
                   1206: 
1.324     www      1207:     return $response->content;
                   1208: }
                   1209: 
                   1210: sub externalssi {
                   1211:     my ($url)=@_;
                   1212:     my $ua=new LWP::UserAgent;
                   1213:     my $request=new HTTP::Request('GET',$url);
                   1214:     my $response=$ua->request($request);
1.15      www      1215:     return $response->content;
                   1216: }
1.254     www      1217: 
1.492     albertel 1218: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1219: 
                   1220: sub allowuploaded {
                   1221:     my ($srcurl,$url)=@_;
                   1222:     $url=&clutter(&declutter($url));
                   1223:     my $dir=$url;
                   1224:     $dir=~s/\/[^\/]+$//;
                   1225:     my %httpref=();
                   1226:     my $httpurl=&hreflocation('',$url);
                   1227:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1228:     &Apache::lonnet::appenv(%httpref);
1.254     www      1229: }
1.477     raeburn  1230: 
1.478     albertel 1231: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1232: # input: action, courseID, current domain, intended
1.637     raeburn  1233: #        path to file, source of file, instruction to parse file for objects,
                   1234: #        ref to hash for embedded objects,
                   1235: #        ref to hash for codebase of java objects.
                   1236: #
1.485     raeburn  1237: # output: url to file (if action was uploaddoc), 
                   1238: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1239: #
1.478     albertel 1240: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1241: # course.
1.477     raeburn  1242: #
1.478     albertel 1243: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1244: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1245: #          course's home server.
1.477     raeburn  1246: #
1.478     albertel 1247: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1248: #          be copied from $source (current location) to 
                   1249: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1250: #         and will then be copied to
                   1251: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1252: #         course's home server.
1.485     raeburn  1253: #
1.481     raeburn  1254: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1255: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1256: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1257: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1258: #         in course's home server.
1.637     raeburn  1259: #
1.477     raeburn  1260: 
                   1261: sub process_coursefile {
1.638     albertel 1262:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1263:     my $fetchresult;
1.638     albertel 1264:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1265:     if ($action eq 'propagate') {
1.638     albertel 1266:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1267: 			     $home);
1.481     raeburn  1268:     } else {
1.477     raeburn  1269:         my $fpath = '';
                   1270:         my $fname = $file;
1.478     albertel 1271:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1272:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1273:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1274:         if ($action eq 'copy') {
                   1275:             if ($source eq '') {
                   1276:                 $fetchresult = 'no source file';
                   1277:                 return $fetchresult;
                   1278:             } else {
                   1279:                 my $destination = $filepath.'/'.$fname;
                   1280:                 rename($source,$destination);
                   1281:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1282:                                  $home);
1.481     raeburn  1283:             }
                   1284:         } elsif ($action eq 'uploaddoc') {
                   1285:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1286:             print $fh $env{'form.'.$source};
1.481     raeburn  1287:             close($fh);
1.637     raeburn  1288:             if ($parser eq 'parse') {
                   1289:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1290:                 unless ($parse_result eq 'ok') {
                   1291:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1292:                 }
                   1293:             }
1.477     raeburn  1294:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1295:                                  $home);
1.481     raeburn  1296:             if ($fetchresult eq 'ok') {
                   1297:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1298:             } else {
                   1299:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1300:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1301:                 return '/adm/notfound.html';
                   1302:             }
1.477     raeburn  1303:         }
                   1304:     }
1.485     raeburn  1305:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1306:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1307:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1308:     }
                   1309:     return $fetchresult;
                   1310: }
                   1311: 
1.637     raeburn  1312: sub build_filepath {
                   1313:     my ($fpath) = @_;
                   1314:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1315:     unless ($fpath eq '') {
                   1316:         my @parts=split('/',$fpath);
                   1317:         foreach my $part (@parts) {
                   1318:             $filepath.= '/'.$part;
                   1319:             if ((-e $filepath)!=1) {
                   1320:                 mkdir($filepath,0777);
                   1321:             }
                   1322:         }
                   1323:     }
                   1324:     return $filepath;
                   1325: }
                   1326: 
                   1327: sub store_edited_file {
1.638     albertel 1328:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1329:     my $file = $primary_url;
                   1330:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1331:     my $fpath = '';
                   1332:     my $fname = $file;
                   1333:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1334:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1335:     my $filepath = &build_filepath($fpath);
                   1336:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1337:     print $fh $content;
                   1338:     close($fh);
1.638     albertel 1339:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1340:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1341: 			  $home);
1.637     raeburn  1342:     if ($$fetchresult eq 'ok') {
                   1343:         return '/uploaded/'.$fpath.'/'.$fname;
                   1344:     } else {
1.638     albertel 1345:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1346: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1347:         return '/adm/notfound.html';
                   1348:     }
                   1349: }
                   1350: 
1.531     albertel 1351: sub clean_filename {
                   1352:     my ($fname)=@_;
1.315     www      1353: # Replace Windows backslashes by forward slashes
1.257     www      1354:     $fname=~s/\\/\//g;
1.315     www      1355: # Get rid of everything but the actual filename
1.257     www      1356:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1357: # Replace spaces by underscores
                   1358:     $fname=~s/\s+/\_/g;
                   1359: # Replace all other weird characters by nothing
1.317     www      1360:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1361: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1362: # numbers
                   1363:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1364:     return $fname;
                   1365: }
                   1366: 
1.608     albertel 1367: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1368: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1369: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1370: #        $coursedoc - if true up to the current course
                   1371: #                     if false
                   1372: #        $subdir - directory in userfile to store the file into
                   1373: #        $parser, $allfiles, $codebase - unknown
                   1374: #
                   1375: # output: url of file in userspace, or error: <message> 
                   1376: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1377: 
                   1378: 
1.531     albertel 1379: sub userfileupload {
1.719     banghart 1380:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1381:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1382:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1383:     $fname=&clean_filename($fname);
1.315     www      1384: # See if there is anything left
1.257     www      1385:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1386:     chop($env{'form.'.$formname});
1.523     raeburn  1387:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1388:         my $now = time;
                   1389:         my $filepath = 'tmp/helprequests/'.$now;
                   1390:         my @parts=split(/\//,$filepath);
                   1391:         my $fullpath = $perlvar{'lonDaemons'};
                   1392:         for (my $i=0;$i<@parts;$i++) {
                   1393:             $fullpath .= '/'.$parts[$i];
                   1394:             if ((-e $fullpath)!=1) {
                   1395:                 mkdir($fullpath,0777);
                   1396:             }
                   1397:         }
                   1398:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1399:         print $fh $env{'form.'.$formname};
1.523     raeburn  1400:         close($fh);
1.741     raeburn  1401:         return $fullpath.'/'.$fname;
                   1402:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1403:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1404:                        '_'.$env{'user.domain'}.'/pending';
                   1405:         my @parts=split(/\//,$filepath);
                   1406:         my $fullpath = $perlvar{'lonDaemons'};
                   1407:         for (my $i=0;$i<@parts;$i++) {
                   1408:             $fullpath .= '/'.$parts[$i];
                   1409:             if ((-e $fullpath)!=1) {
                   1410:                 mkdir($fullpath,0777);
                   1411:             }
                   1412:         }
                   1413:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1414:         print $fh $env{'form.'.$formname};
                   1415:         close($fh);
                   1416:         return $fullpath.'/'.$fname;
1.523     raeburn  1417:     }
1.719     banghart 1418:     
1.258     www      1419: # Create the directory if not present
1.493     albertel 1420:     $fname="$subdir/$fname";
1.259     www      1421:     if ($coursedoc) {
1.638     albertel 1422: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1423: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1424:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1425:             return &finishuserfileupload($docuname,$docudom,
                   1426: 					 $formname,$fname,$parser,$allfiles,
                   1427: 					 $codebase);
1.481     raeburn  1428:         } else {
1.620     albertel 1429:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1430:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1431: 				       $fname,$formname,$parser,
                   1432: 				       $allfiles,$codebase);
1.481     raeburn  1433:         }
1.719     banghart 1434:     } elsif (defined($destuname)) {
                   1435:         my $docuname=$destuname;
                   1436:         my $docudom=$destudom;
                   1437: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1438: 				     $fname,$parser,$allfiles,$codebase);
                   1439:         
1.259     www      1440:     } else {
1.638     albertel 1441:         my $docuname=$env{'user.name'};
                   1442:         my $docudom=$env{'user.domain'};
1.714     raeburn  1443:         if (exists($env{'form.group'})) {
                   1444:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1445:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1446:         }
1.638     albertel 1447: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1448: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1449:     }
1.271     www      1450: }
                   1451: 
                   1452: sub finishuserfileupload {
1.638     albertel 1453:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1454:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1455:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1456:     my ($fnamepath,$file);
                   1457:     $file=$fname;
                   1458:     if ($fname=~m|/|) {
                   1459:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1460: 	$path.=$fnamepath.'/';
                   1461:     }
1.259     www      1462:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1463:     my $count;
                   1464:     for ($count=4;$count<=$#parts;$count++) {
                   1465:         $filepath.="/$parts[$count]";
                   1466:         if ((-e $filepath)!=1) {
                   1467: 	    mkdir($filepath,0777);
                   1468:         }
                   1469:     }
                   1470: # Save the file
                   1471:     {
1.701     albertel 1472: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1473: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1474: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1475: 	    return '/adm/notfound.html';
                   1476: 	}
                   1477: 	if (!print FH ($env{'form.'.$formname})) {
                   1478: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1479: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1480: 	    return '/adm/notfound.html';
                   1481: 	}
1.570     albertel 1482: 	close(FH);
1.258     www      1483:     }
1.637     raeburn  1484:     if ($parser eq 'parse') {
1.638     albertel 1485:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1486: 						   $codebase);
1.637     raeburn  1487:         unless ($parse_result eq 'ok') {
1.638     albertel 1488:             &logthis('Failed to parse '.$filepath.$file.
                   1489: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1490:         }
                   1491:     }
1.259     www      1492: # Notify homeserver to grep it
                   1493: #
1.638     albertel 1494:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1495:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1496:     if ($fetchresult eq 'ok') {
1.259     www      1497: #
1.258     www      1498: # Return the URL to it
1.494     albertel 1499:         return '/uploaded/'.$path.$file;
1.263     www      1500:     } else {
1.494     albertel 1501:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1502: 		 ': '.$fetchresult);
1.263     www      1503:         return '/adm/notfound.html';
                   1504:     }    
1.493     albertel 1505: }
                   1506: 
1.637     raeburn  1507: sub extract_embedded_items {
1.648     raeburn  1508:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1509:     my @state = ();
                   1510:     my %javafiles = (
                   1511:                       codebase => '',
                   1512:                       code => '',
                   1513:                       archive => ''
                   1514:                     );
                   1515:     my %mediafiles = (
                   1516:                       src => '',
                   1517:                       movie => '',
                   1518:                      );
1.648     raeburn  1519:     my $p;
                   1520:     if ($content) {
                   1521:         $p = HTML::LCParser->new($content);
                   1522:     } else {
                   1523:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1524:     }
1.641     albertel 1525:     while (my $t=$p->get_token()) {
1.640     albertel 1526: 	if ($t->[0] eq 'S') {
                   1527: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1528: 	    push (@state, $tagname);
1.648     raeburn  1529:             if (lc($tagname) eq 'allow') {
                   1530:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1531:             }
1.640     albertel 1532: 	    if (lc($tagname) eq 'img') {
                   1533: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1534: 	    }
1.645     raeburn  1535:             if (lc($tagname) eq 'script') {
                   1536:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1537:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1538:                 } else {
                   1539:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1540:                 }
                   1541:             }
                   1542:             if (lc($tagname) eq 'link') {
                   1543:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1544:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1545:                 }
                   1546:             }
1.640     albertel 1547: 	    if (lc($tagname) eq 'object' ||
                   1548: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1549: 		foreach my $item (keys(%javafiles)) {
                   1550: 		    $javafiles{$item} = '';
                   1551: 		}
                   1552: 	    }
                   1553: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1554: 		my $name = lc($attr->{'name'});
                   1555: 		foreach my $item (keys(%javafiles)) {
                   1556: 		    if ($name eq $item) {
                   1557: 			$javafiles{$item} = $attr->{'value'};
                   1558: 			last;
                   1559: 		    }
                   1560: 		}
                   1561: 		foreach my $item (keys(%mediafiles)) {
                   1562: 		    if ($name eq $item) {
                   1563: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1564: 			last;
                   1565: 		    }
                   1566: 		}
                   1567: 	    }
                   1568: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1569: 		foreach my $item (keys(%javafiles)) {
                   1570: 		    if ($attr->{$item}) {
                   1571: 			$javafiles{$item} = $attr->{$item};
                   1572: 			last;
                   1573: 		    }
                   1574: 		}
                   1575: 		foreach my $item (keys(%mediafiles)) {
                   1576: 		    if ($attr->{$item}) {
                   1577: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1578: 			last;
                   1579: 		    }
                   1580: 		}
                   1581: 	    }
                   1582: 	} elsif ($t->[0] eq 'E') {
                   1583: 	    my ($tagname) = ($t->[1]);
                   1584: 	    if ($javafiles{'codebase'} ne '') {
                   1585: 		$javafiles{'codebase'} .= '/';
                   1586: 	    }  
                   1587: 	    if (lc($tagname) eq 'applet' ||
                   1588: 		lc($tagname) eq 'object' ||
                   1589: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1590: 		) {
                   1591: 		foreach my $item (keys(%javafiles)) {
                   1592: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1593: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1594: 			&add_filetype($allfiles,$file,$item);
                   1595: 		    }
                   1596: 		}
                   1597: 	    } 
                   1598: 	    pop @state;
                   1599: 	}
                   1600:     }
1.637     raeburn  1601:     return 'ok';
                   1602: }
                   1603: 
1.639     albertel 1604: sub add_filetype {
                   1605:     my ($allfiles,$file,$type)=@_;
                   1606:     if (exists($allfiles->{$file})) {
                   1607: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1608: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1609: 	}
                   1610:     } else {
                   1611: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1612:     }
                   1613: }
                   1614: 
1.493     albertel 1615: sub removeuploadedurl {
                   1616:     my ($url)=@_;
                   1617:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1618:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1619: }
                   1620: 
                   1621: sub removeuserfile {
                   1622:     my ($docuname,$docudom,$fname)=@_;
                   1623:     my $home=&homeserver($docuname,$docudom);
                   1624:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1625: }
1.15      www      1626: 
1.530     albertel 1627: sub mkdiruserfile {
                   1628:     my ($docuname,$docudom,$dir)=@_;
                   1629:     my $home=&homeserver($docuname,$docudom);
                   1630:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1631: }
                   1632: 
1.531     albertel 1633: sub renameuserfile {
                   1634:     my ($docuname,$docudom,$old,$new)=@_;
                   1635:     my $home=&homeserver($docuname,$docudom);
                   1636:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1637: 		  &escape("$new"),$home);
                   1638: }
                   1639: 
1.14      www      1640: # ------------------------------------------------------------------------- Log
                   1641: 
                   1642: sub log {
                   1643:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1644:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1645: }
                   1646: 
                   1647: # ------------------------------------------------------------------ Course Log
1.352     www      1648: #
                   1649: # This routine flushes several buffers of non-mission-critical nature
                   1650: #
1.157     www      1651: 
                   1652: sub flushcourselogs {
1.352     www      1653:     &logthis('Flushing log buffers');
                   1654: #
                   1655: # course logs
                   1656: # This is a log of all transactions in a course, which can be used
                   1657: # for data mining purposes
                   1658: #
                   1659: # It also collects the courseid database, which lists last transaction
                   1660: # times and course titles for all courseids
                   1661: #
                   1662:     my %courseidbuffer=();
1.191     harris41 1663:     foreach (keys %courselogs) {
1.157     www      1664:         my $crsid=$_;
1.352     www      1665:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1666: 		          &escape($courselogs{$crsid}),
                   1667: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1668: 	    delete $courselogs{$crsid};
                   1669:         } else {
                   1670:             &logthis('Failed to flush log buffer for '.$crsid);
                   1671:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1672:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1673:                         " exceeded maximum size, deleting.</font>");
                   1674:                delete $courselogs{$crsid};
                   1675:             }
1.352     www      1676:         }
                   1677:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1678:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1679: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1680:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1681:         } else {
                   1682:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1683: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1684:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1685:         }
1.191     harris41 1686:     }
1.352     www      1687: #
                   1688: # Write course id database (reverse lookup) to homeserver of courses 
                   1689: # Is used in pickcourse
                   1690: #
                   1691:     foreach (keys %courseidbuffer) {
1.353     www      1692:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1693:     }
                   1694: #
                   1695: # File accesses
                   1696: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1697: #
1.449     matthew  1698:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1699:         if ($entry =~ /___count$/) {
                   1700:             my ($dom,$name);
                   1701:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1702:             if (! defined($dom) || $dom eq '' || 
                   1703:                 ! defined($name) || $name eq '') {
1.620     albertel 1704:                 my $cid = $env{'request.course.id'};
                   1705:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1706:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1707:             }
1.450     matthew  1708:             my $value = $accesshash{$entry};
                   1709:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1710:             my %temphash=($url => $value);
1.449     matthew  1711:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1712:             if ($result eq 'ok') {
                   1713:                 delete $accesshash{$entry};
                   1714:             } elsif ($result eq 'unknown_cmd') {
                   1715:                 # Target server has old code running on it.
1.450     matthew  1716:                 my %temphash=($entry => $value);
1.449     matthew  1717:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1718:                     delete $accesshash{$entry};
                   1719:                 }
                   1720:             }
                   1721:         } else {
1.458     matthew  1722:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1723:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1724:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1725:                 delete $accesshash{$entry};
                   1726:             }
1.185     www      1727:         }
1.191     harris41 1728:     }
1.352     www      1729: #
                   1730: # Roles
                   1731: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1732: #
1.349     www      1733:     foreach (keys %userrolehash) {
                   1734:         my $entry=$_;
1.351     www      1735:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1736: 	    split(/\:/,$entry);
                   1737:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1738:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1739:                 $rudom,$runame) eq 'ok') {
                   1740: 	    delete $userrolehash{$entry};
                   1741:         }
                   1742:     }
1.662     raeburn  1743: #
                   1744: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1745: #
                   1746:     my %domrolebuffer = ();
                   1747:     foreach my $entry (keys %domainrolehash) {
                   1748:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1749:         if ($domrolebuffer{$rudom}) {
                   1750:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1751:                       '='.&escape($domainrolehash{$entry});
                   1752:         } else {
                   1753:             $domrolebuffer{$rudom}.=&escape($entry).
                   1754:                       '='.&escape($domainrolehash{$entry});
                   1755:         }
                   1756:         delete $domainrolehash{$entry};
                   1757:     }
                   1758:     foreach my $dom (keys(%domrolebuffer)) {
                   1759:         foreach my $tryserver (keys %libserv) {
                   1760:             if ($hostdom{$tryserver} eq $dom) {
                   1761:                 unless (&reply('domroleput:'.$dom.':'.
                   1762:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1763:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1764:                 }
                   1765:             }
                   1766:         }
                   1767:     }
1.186     www      1768:     $dumpcount++;
1.157     www      1769: }
                   1770: 
                   1771: sub courselog {
                   1772:     my $what=shift;
1.158     www      1773:     $what=time.':'.$what;
1.620     albertel 1774:     unless ($env{'request.course.id'}) { return ''; }
                   1775:     $coursedombuf{$env{'request.course.id'}}=
                   1776:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1777:     $coursenumbuf{$env{'request.course.id'}}=
                   1778:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1779:     $coursehombuf{$env{'request.course.id'}}=
                   1780:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1781:     $coursedescrbuf{$env{'request.course.id'}}=
                   1782:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1783:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1784:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1785:     $courseownerbuf{$env{'request.course.id'}}=
                   1786:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1787:     $coursetypebuf{$env{'request.course.id'}}=
                   1788:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1789:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1790: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1791:     } else {
1.620     albertel 1792: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1793:     }
1.620     albertel 1794:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1795: 	&flushcourselogs();
                   1796:     }
1.158     www      1797: }
                   1798: 
                   1799: sub courseacclog {
                   1800:     my $fnsymb=shift;
1.620     albertel 1801:     unless ($env{'request.course.id'}) { return ''; }
                   1802:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1803:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1804:         $what.=':POST';
1.583     matthew  1805:         # FIXME: Probably ought to escape things....
1.620     albertel 1806: 	foreach (keys %env) {
1.158     www      1807:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1808: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1809:             }
1.191     harris41 1810:         }
1.583     matthew  1811:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1812:         # FIXME: We should not be depending on a form parameter that someone
                   1813:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1814:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1815:             $what.= ':POST';
                   1816:             # FIXME: Probably ought to escape things....
                   1817:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1818:                                  'crsdiscuss') {
1.620     albertel 1819:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1820:             }
                   1821:         }
1.158     www      1822:     }
                   1823:     &courselog($what);
1.149     www      1824: }
                   1825: 
1.185     www      1826: sub countacc {
                   1827:     my $url=&declutter(shift);
1.458     matthew  1828:     return if (! defined($url) || $url eq '');
1.620     albertel 1829:     unless ($env{'request.course.id'}) { return ''; }
                   1830:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1831:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1832:     $accesshash{$key}++;
1.185     www      1833: }
1.349     www      1834: 
1.361     www      1835: sub linklog {
                   1836:     my ($from,$to)=@_;
                   1837:     $from=&declutter($from);
                   1838:     $to=&declutter($to);
                   1839:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1840:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1841: }
                   1842:   
1.349     www      1843: sub userrolelog {
                   1844:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1845:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1846:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1847:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1848:         ($trole=~/^ta/)) {
1.350     www      1849:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1850:        $userrolehash
                   1851:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1852:                     =$tend.':'.$tstart;
1.662     raeburn  1853:     }
                   1854:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1855:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1856:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1857:         ($trole=~/^sc/)) {
                   1858:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1859:        $domainrolehash
                   1860:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1861:                     = $tend.':'.$tstart;
                   1862:     }
1.351     www      1863: }
                   1864: 
                   1865: sub get_course_adv_roles {
                   1866:     my $cid=shift;
1.620     albertel 1867:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1868:     my %coursehash=&coursedescription($cid);
1.470     www      1869:     my %nothide=();
                   1870:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1871: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1872:     }
1.351     www      1873:     my %returnhash=();
                   1874:     my %dumphash=
                   1875:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1876:     my $now=time;
                   1877:     foreach (keys %dumphash) {
                   1878: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1879:         if (($tstart) && ($tstart<0)) { next; }
                   1880:         if (($tend) && ($tend<$now)) { next; }
                   1881:         if (($tstart) && ($now<$tstart)) { next; }
                   1882:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1883: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1884: 	if ((&privileged($username,$domain)) && 
                   1885: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1886: 	if ($role eq 'cr') { next; }
1.351     www      1887:         my $key=&plaintext($role);
1.656     albertel 1888: 	if ($role =~ /^cr/) {
                   1889: 	    $key=(split('/',$role))[3];
                   1890: 	}
1.351     www      1891:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1892:         if ($returnhash{$key}) {
                   1893: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1894:         } else {
                   1895:             $returnhash{$key}=$username.':'.$domain;
                   1896:         }
1.400     www      1897:      }
                   1898:     return %returnhash;
                   1899: }
                   1900: 
                   1901: sub get_my_roles {
                   1902:     my ($uname,$udom)=@_;
1.620     albertel 1903:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1904:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1905:     my %dumphash=
                   1906:             &dump('nohist_userroles',$udom,$uname);
                   1907:     my %returnhash=();
                   1908:     my $now=time;
                   1909:     foreach (keys %dumphash) {
                   1910: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1911:         if (($tstart) && ($tstart<0)) { next; }
                   1912:         if (($tend) && ($tend<$now)) { next; }
                   1913:         if (($tstart) && ($now<$tstart)) { next; }
                   1914:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1915: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1916:      }
                   1917:     return %returnhash;
1.399     www      1918: }
                   1919: 
                   1920: # ----------------------------------------------------- Frontpage Announcements
                   1921: #
                   1922: #
                   1923: 
                   1924: sub postannounce {
                   1925:     my ($server,$text)=@_;
                   1926:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1927:     unless ($text=~/\w/) { $text=''; }
                   1928:     return &reply('setannounce:'.&escape($text),$server);
                   1929: }
                   1930: 
                   1931: sub getannounce {
1.448     albertel 1932: 
                   1933:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1934: 	my $announcement='';
                   1935: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1936: 	close($fh);
1.399     www      1937: 	if ($announcement=~/\w/) { 
                   1938: 	    return 
                   1939:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1940:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1941: 	} else {
                   1942: 	    return '';
                   1943: 	}
                   1944:     } else {
                   1945: 	return '';
                   1946:     }
1.351     www      1947: }
1.353     www      1948: 
                   1949: # ---------------------------------------------------------- Course ID routines
                   1950: # Deal with domain's nohist_courseid.db files
                   1951: #
                   1952: 
                   1953: sub courseidput {
                   1954:     my ($domain,$what,$coursehome)=@_;
                   1955:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1956: }
                   1957: 
                   1958: sub courseiddump {
1.741     raeburn  1959:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1960:     my %returnhash=();
1.355     www      1961:     unless ($domfilter) { $domfilter=''; }
1.353     www      1962:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1963:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1964: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1965: 	        foreach (
                   1966:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1967: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1968:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1969:                                $tryserver))) {
1.506     raeburn  1970: 		    my ($key,$value)=split(/\=/,$_);
                   1971:                     if (($key) && ($value)) {
1.516     raeburn  1972: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1973:                     }
1.353     www      1974:                 }
                   1975:             }
                   1976:         }
                   1977:     }
                   1978:     return %returnhash;
                   1979: }
                   1980: 
1.658     raeburn  1981: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1982: 
                   1983: sub dcmailput {
1.685     raeburn  1984:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1985:     my $status = &Apache::lonnet::critical(
1.740     www      1986:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1987:        &escape($message),$server);
1.662     raeburn  1988:     return $status;
                   1989: }
                   1990: 
1.658     raeburn  1991: sub dcmaildump {
                   1992:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1993:     my %returnhash=();
                   1994:     if (exists($domain_primary{$dom})) {
                   1995:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1996:                                                          &escape($enddate).':';
                   1997: 	my @esc_senders=map { &escape($_)} @$senders;
                   1998: 	$cmd.=&escape(join('&',@esc_senders));
                   1999: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2000:             my ($key,$value) = split(/\=/,$_);
                   2001:             if (($key) && ($value)) {
                   2002:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2003:             }
                   2004:         }
                   2005:     }
                   2006:     return %returnhash;
                   2007: }
1.662     raeburn  2008: # ---------------------------------------------------------- Domain roles
                   2009: 
                   2010: sub get_domain_roles {
                   2011:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2012:     if (undef($startdate) || $startdate eq '') {
                   2013:         $startdate = '.';
                   2014:     }
                   2015:     if (undef($enddate) || $enddate eq '') {
                   2016:         $enddate = '.';
                   2017:     }
                   2018:     my $rolelist = join(':',@{$roles});
                   2019:     my %personnel = ();
                   2020:     foreach my $tryserver (keys(%libserv)) {
                   2021:         if ($hostdom{$tryserver} eq $dom) {
                   2022:             %{$personnel{$tryserver}}=();
                   2023:             foreach (
                   2024:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2025:                    &escape($startdate).':'.&escape($enddate).':'.
                   2026:                    &escape($rolelist), $tryserver))) {
                   2027:                 my($key,$value) = split(/\=/,$_);
                   2028:                 if (($key) && ($value)) {
                   2029:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2030:                 }
                   2031:             }
                   2032:         }
                   2033:     }
                   2034:     return %personnel;
                   2035: }
1.658     raeburn  2036: 
1.149     www      2037: # ----------------------------------------------------------- Check out an item
                   2038: 
1.504     albertel 2039: sub get_first_access {
                   2040:     my ($type,$argsymb)=@_;
                   2041:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2042:     if ($argsymb) { $symb=$argsymb; }
                   2043:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2044:     if ($type eq 'map') {
                   2045: 	$res=&symbread($map);
                   2046:     } else {
                   2047: 	$res=$symb;
                   2048:     }
                   2049:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2050:     return $times{"$courseid\0$res"};
1.504     albertel 2051: }
                   2052: 
                   2053: sub set_first_access {
                   2054:     my ($type)=@_;
                   2055:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2056:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2057:     if ($type eq 'map') {
                   2058: 	$res=&symbread($map);
                   2059:     } else {
                   2060: 	$res=$symb;
                   2061:     }
                   2062:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2063:     if (!$firstaccess) {
1.588     albertel 2064: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2065:     }
                   2066:     return 'already_set';
1.504     albertel 2067: }
                   2068: 
1.149     www      2069: sub checkout {
                   2070:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2071:     my $now=time;
                   2072:     my $lonhost=$perlvar{'lonHostID'};
                   2073:     my $infostr=&escape(
1.234     www      2074:                  'CHECKOUTTOKEN&'.
1.149     www      2075:                  $tuname.'&'.
                   2076:                  $tudom.'&'.
                   2077:                  $tcrsid.'&'.
                   2078:                  $symb.'&'.
                   2079: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2080:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2081:     if ($token=~/^error\:/) { 
1.672     albertel 2082:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2083:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2084:                  "</font>");
                   2085:         return ''; 
                   2086:     }
                   2087: 
1.149     www      2088:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2089:     $token=~tr/a-z/A-Z/;
                   2090: 
1.153     www      2091:     my %infohash=('resource.0.outtoken' => $token,
                   2092:                   'resource.0.checkouttime' => $now,
                   2093:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2094: 
                   2095:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2096:        return '';
1.151     www      2097:     } else {
1.672     albertel 2098:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2099:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2100:                  "</font>");
1.149     www      2101:     }    
                   2102: 
                   2103:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2104:                          &escape('Checkout '.$infostr.' - '.
                   2105:                                                  $token)) ne 'ok') {
                   2106: 	return '';
1.151     www      2107:     } else {
1.672     albertel 2108:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2109:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2110:                  "</font>");
1.149     www      2111:     }
1.151     www      2112:     return $token;
1.149     www      2113: }
                   2114: 
                   2115: # ------------------------------------------------------------ Check in an item
                   2116: 
                   2117: sub checkin {
                   2118:     my $token=shift;
1.150     www      2119:     my $now=time;
                   2120:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2121:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2122:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2123:     $dtoken=~s/\W/\_/g;
1.234     www      2124:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2125:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2126: 
1.154     www      2127:     unless (($tuname) && ($tudom)) {
                   2128:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2129:         return '';
                   2130:     }
                   2131:     
                   2132:     unless (&allowed('mgr',$tcrsid)) {
                   2133:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2134:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2135:         return '';
                   2136:     }
                   2137: 
1.153     www      2138:     my %infohash=('resource.0.intoken' => $token,
                   2139:                   'resource.0.checkintime' => $now,
                   2140:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2141: 
                   2142:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2143:        return '';
                   2144:     }    
                   2145: 
                   2146:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2147:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2148: 	return '';
                   2149:     }
                   2150: 
                   2151:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2152: }
                   2153: 
                   2154: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2155: 
                   2156: sub expirespread {
                   2157:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2158:     my $cid=$env{'request.course.id'}; 
1.110     www      2159:     if ($cid) {
                   2160:        my $now=time;
                   2161:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2162:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2163:                             $env{'course.'.$cid.'.num'}.
1.110     www      2164: 	        	    ':nohist_expirationdates:'.
                   2165:                             &escape($key).'='.$now,
1.620     albertel 2166:                             $env{'course.'.$cid.'.home'})
1.110     www      2167:     }
                   2168:     return 'ok';
1.14      www      2169: }
                   2170: 
1.109     www      2171: # ----------------------------------------------------- Devalidate Spreadsheets
                   2172: 
                   2173: sub devalidate {
1.325     www      2174:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2175:     my $cid=$env{'request.course.id'}; 
1.109     www      2176:     if ($cid) {
1.391     matthew  2177:         # delete the stored spreadsheets for
                   2178:         # - the student level sheet of this user in course's homespace
                   2179:         # - the assessment level sheet for this resource 
                   2180:         #   for this user in user's homespace
1.553     albertel 2181: 	# - current conditional state info
1.325     www      2182: 	my $key=$uname.':'.$udom.':';
1.109     www      2183:         my $status=
1.299     matthew  2184: 	    &del('nohist_calculatedsheets',
1.391     matthew  2185: 		 [$key.'studentcalc:'],
1.620     albertel 2186: 		 $env{'course.'.$cid.'.domain'},
                   2187: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2188: 		.' '.
                   2189: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2190: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2191:         unless ($status eq 'ok ok') {
                   2192:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2193:                     $uname.' at '.$udom.' for '.
1.109     www      2194: 		    $symb.': '.$status);
1.133     albertel 2195:         }
1.553     albertel 2196: 	&delenv('user.state.'.$cid);
1.109     www      2197:     }
                   2198: }
                   2199: 
1.265     albertel 2200: sub get_scalar {
                   2201:     my ($string,$end) = @_;
                   2202:     my $value;
                   2203:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2204: 	$value = $1;
                   2205:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2206: 	$value = $1;
                   2207:     }
                   2208:     return &unescape($value);
                   2209: }
                   2210: 
                   2211: sub array2str {
                   2212:   my (@array) = @_;
                   2213:   my $result=&arrayref2str(\@array);
                   2214:   $result=~s/^__ARRAY_REF__//;
                   2215:   $result=~s/__END_ARRAY_REF__$//;
                   2216:   return $result;
                   2217: }
                   2218: 
1.204     albertel 2219: sub arrayref2str {
                   2220:   my ($arrayref) = @_;
1.265     albertel 2221:   my $result='__ARRAY_REF__';
1.204     albertel 2222:   foreach my $elem (@$arrayref) {
1.265     albertel 2223:     if(ref($elem) eq 'ARRAY') {
                   2224:       $result.=&arrayref2str($elem).'&';
                   2225:     } elsif(ref($elem) eq 'HASH') {
                   2226:       $result.=&hashref2str($elem).'&';
                   2227:     } elsif(ref($elem)) {
                   2228:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2229:     } else {
                   2230:       $result.=&escape($elem).'&';
                   2231:     }
                   2232:   }
                   2233:   $result=~s/\&$//;
1.265     albertel 2234:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2235:   return $result;
                   2236: }
                   2237: 
1.168     albertel 2238: sub hash2str {
1.204     albertel 2239:   my (%hash) = @_;
                   2240:   my $result=&hashref2str(\%hash);
1.265     albertel 2241:   $result=~s/^__HASH_REF__//;
                   2242:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2243:   return $result;
                   2244: }
                   2245: 
                   2246: sub hashref2str {
                   2247:   my ($hashref)=@_;
1.265     albertel 2248:   my $result='__HASH_REF__';
1.495     albertel 2249:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2250:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2251:       $result.=&arrayref2str($_).'=';
1.204     albertel 2252:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2253:       $result.=&hashref2str($_).'=';
1.204     albertel 2254:     } elsif (ref($_)) {
1.265     albertel 2255:       $result.='=';
                   2256:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2257:     } else {
1.265     albertel 2258: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2259:     }
                   2260: 
1.265     albertel 2261:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2262:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2263:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2264:       $result.=&hashref2str($hashref->{$_}).'&';
                   2265:     } elsif(ref($hashref->{$_})) {
                   2266:        $result.='&';
                   2267:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2268:     } else {
1.265     albertel 2269:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2270:     }
                   2271:   }
1.168     albertel 2272:   $result=~s/\&$//;
1.265     albertel 2273:   $result .= '__END_HASH_REF__';
1.168     albertel 2274:   return $result;
                   2275: }
                   2276: 
                   2277: sub str2hash {
1.265     albertel 2278:     my ($string)=@_;
                   2279:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2280:     return %$hash;
                   2281: }
                   2282: 
                   2283: sub str2hashref {
1.168     albertel 2284:   my ($string) = @_;
1.265     albertel 2285: 
                   2286:   my %hash;
                   2287: 
                   2288:   if($string !~ /^__HASH_REF__/) {
                   2289:       if (! ($string eq '' || !defined($string))) {
                   2290: 	  $hash{'error'}='Not hash reference';
                   2291:       }
                   2292:       return (\%hash, $string);
                   2293:   }
                   2294: 
                   2295:   $string =~ s/^__HASH_REF__//;
                   2296: 
                   2297:   while($string !~ /^__END_HASH_REF__/) {
                   2298:       #key
                   2299:       my $key='';
                   2300:       if($string =~ /^__HASH_REF__/) {
                   2301:           ($key, $string)=&str2hashref($string);
                   2302:           if(defined($key->{'error'})) {
                   2303:               $hash{'error'}='Bad data';
                   2304:               return (\%hash, $string);
                   2305:           }
                   2306:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2307:           ($key, $string)=&str2arrayref($string);
                   2308:           if($key->[0] eq 'Array reference error') {
                   2309:               $hash{'error'}='Bad data';
                   2310:               return (\%hash, $string);
                   2311:           }
                   2312:       } else {
                   2313:           $string =~ s/^(.*?)=//;
1.267     albertel 2314: 	  $key=&unescape($1);
1.265     albertel 2315:       }
                   2316:       $string =~ s/^=//;
                   2317: 
                   2318:       #value
                   2319:       my $value='';
                   2320:       if($string =~ /^__HASH_REF__/) {
                   2321:           ($value, $string)=&str2hashref($string);
                   2322:           if(defined($value->{'error'})) {
                   2323:               $hash{'error'}='Bad data';
                   2324:               return (\%hash, $string);
                   2325:           }
                   2326:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2327:           ($value, $string)=&str2arrayref($string);
                   2328:           if($value->[0] eq 'Array reference error') {
                   2329:               $hash{'error'}='Bad data';
                   2330:               return (\%hash, $string);
                   2331:           }
                   2332:       } else {
                   2333: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2334:       }
                   2335:       $string =~ s/^&//;
                   2336: 
                   2337:       $hash{$key}=$value;
1.204     albertel 2338:   }
1.265     albertel 2339: 
                   2340:   $string =~ s/^__END_HASH_REF__//;
                   2341: 
                   2342:   return (\%hash, $string);
1.204     albertel 2343: }
                   2344: 
                   2345: sub str2array {
1.265     albertel 2346:     my ($string)=@_;
                   2347:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2348:     return @$array;
                   2349: }
                   2350: 
                   2351: sub str2arrayref {
1.204     albertel 2352:   my ($string) = @_;
1.265     albertel 2353:   my @array;
                   2354: 
                   2355:   if($string !~ /^__ARRAY_REF__/) {
                   2356:       if (! ($string eq '' || !defined($string))) {
                   2357: 	  $array[0]='Array reference error';
                   2358:       }
                   2359:       return (\@array, $string);
                   2360:   }
                   2361: 
                   2362:   $string =~ s/^__ARRAY_REF__//;
                   2363: 
                   2364:   while($string !~ /^__END_ARRAY_REF__/) {
                   2365:       my $value='';
                   2366:       if($string =~ /^__HASH_REF__/) {
                   2367:           ($value, $string)=&str2hashref($string);
                   2368:           if(defined($value->{'error'})) {
                   2369:               $array[0] ='Array reference error';
                   2370:               return (\@array, $string);
                   2371:           }
                   2372:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2373:           ($value, $string)=&str2arrayref($string);
                   2374:           if($value->[0] eq 'Array reference error') {
                   2375:               $array[0] ='Array reference error';
                   2376:               return (\@array, $string);
                   2377:           }
                   2378:       } else {
                   2379: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2380:       }
                   2381:       $string =~ s/^&//;
                   2382: 
                   2383:       push(@array, $value);
1.191     harris41 2384:   }
1.265     albertel 2385: 
                   2386:   $string =~ s/^__END_ARRAY_REF__//;
                   2387: 
                   2388:   return (\@array, $string);
1.168     albertel 2389: }
                   2390: 
1.167     albertel 2391: # -------------------------------------------------------------------Temp Store
                   2392: 
1.168     albertel 2393: sub tmpreset {
                   2394:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2395:   if (!$symb) {
                   2396:     $symb=&symbread();
1.620     albertel 2397:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2398:   }
                   2399:   $symb=escape($symb);
                   2400: 
1.620     albertel 2401:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2402:   $namespace=~s/\//\_/g;
                   2403:   $namespace=~s/\W//g;
                   2404: 
1.620     albertel 2405:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2406:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2407:   if ($domain eq 'public' && $stuname eq 'public') {
                   2408:       $stuname=$ENV{'REMOTE_ADDR'};
                   2409:   }
1.168     albertel 2410:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2411:   my %hash;
                   2412:   if (tie(%hash,'GDBM_File',
                   2413: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2414: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2415:     foreach my $key (keys %hash) {
1.180     albertel 2416:       if ($key=~ /:$symb/) {
1.168     albertel 2417: 	delete($hash{$key});
                   2418:       }
                   2419:     }
                   2420:   }
                   2421: }
                   2422: 
1.167     albertel 2423: sub tmpstore {
1.168     albertel 2424:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2425: 
                   2426:   if (!$symb) {
                   2427:     $symb=&symbread();
1.620     albertel 2428:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2429:   }
                   2430:   $symb=escape($symb);
                   2431: 
                   2432:   if (!$namespace) {
                   2433:     # I don't think we would ever want to store this for a course.
                   2434:     # it seems this will only be used if we don't have a course.
1.620     albertel 2435:     #$namespace=$env{'request.course.id'};
1.168     albertel 2436:     #if (!$namespace) {
1.620     albertel 2437:       $namespace=$env{'request.state'};
1.168     albertel 2438:     #}
                   2439:   }
                   2440:   $namespace=~s/\//\_/g;
                   2441:   $namespace=~s/\W//g;
1.620     albertel 2442:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2443:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2444:   if ($domain eq 'public' && $stuname eq 'public') {
                   2445:       $stuname=$ENV{'REMOTE_ADDR'};
                   2446:   }
1.168     albertel 2447:   my $now=time;
                   2448:   my %hash;
                   2449:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2450:   if (tie(%hash,'GDBM_File',
                   2451: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2452: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2453:     $hash{"version:$symb"}++;
                   2454:     my $version=$hash{"version:$symb"};
                   2455:     my $allkeys=''; 
                   2456:     foreach my $key (keys(%$storehash)) {
                   2457:       $allkeys.=$key.':';
1.591     albertel 2458:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2459:     }
                   2460:     $hash{"$version:$symb:timestamp"}=$now;
                   2461:     $allkeys.='timestamp';
                   2462:     $hash{"$version:keys:$symb"}=$allkeys;
                   2463:     if (untie(%hash)) {
                   2464:       return 'ok';
                   2465:     } else {
                   2466:       return "error:$!";
                   2467:     }
                   2468:   } else {
                   2469:     return "error:$!";
                   2470:   }
                   2471: }
1.167     albertel 2472: 
1.168     albertel 2473: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2474: 
1.168     albertel 2475: sub tmprestore {
                   2476:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2477: 
1.168     albertel 2478:   if (!$symb) {
                   2479:     $symb=&symbread();
1.620     albertel 2480:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2481:   }
                   2482:   $symb=escape($symb);
                   2483: 
1.620     albertel 2484:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2485: 
1.620     albertel 2486:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2487:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2488:   if ($domain eq 'public' && $stuname eq 'public') {
                   2489:       $stuname=$ENV{'REMOTE_ADDR'};
                   2490:   }
1.168     albertel 2491:   my %returnhash;
                   2492:   $namespace=~s/\//\_/g;
                   2493:   $namespace=~s/\W//g;
                   2494:   my %hash;
                   2495:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2496:   if (tie(%hash,'GDBM_File',
                   2497: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2498: 	  &GDBM_READER(),0640)) {
1.168     albertel 2499:     my $version=$hash{"version:$symb"};
                   2500:     $returnhash{'version'}=$version;
                   2501:     my $scope;
                   2502:     for ($scope=1;$scope<=$version;$scope++) {
                   2503:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2504:       my @keys=split(/:/,$vkeys);
                   2505:       my $key;
                   2506:       $returnhash{"$scope:keys"}=$vkeys;
                   2507:       foreach $key (@keys) {
1.591     albertel 2508: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2509: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2510:       }
                   2511:     }
1.168     albertel 2512:     if (!(untie(%hash))) {
                   2513:       return "error:$!";
                   2514:     }
                   2515:   } else {
                   2516:     return "error:$!";
                   2517:   }
                   2518:   return %returnhash;
1.167     albertel 2519: }
                   2520: 
1.9       www      2521: # ----------------------------------------------------------------------- Store
                   2522: 
                   2523: sub store {
1.124     www      2524:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2525:     my $home='';
                   2526: 
1.168     albertel 2527:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2528: 
1.213     www      2529:     $symb=&symbclean($symb);
1.122     albertel 2530:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2531: 
1.620     albertel 2532:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2533:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2534: 
                   2535:     &devalidate($symb,$stuname,$domain);
1.109     www      2536: 
                   2537:     $symb=escape($symb);
1.187     www      2538:     if (!$namespace) { 
1.620     albertel 2539:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2540:           return ''; 
                   2541:        } 
                   2542:     }
1.620     albertel 2543:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2544: 
                   2545:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2546:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2547: 
1.12      www      2548:     my $namevalue='';
1.191     harris41 2549:     foreach (keys %$storehash) {
1.591     albertel 2550:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2551:     }
1.12      www      2552:     $namevalue=~s/\&$//;
1.187     www      2553:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2554:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2555: }
                   2556: 
1.47      www      2557: # -------------------------------------------------------------- Critical Store
                   2558: 
                   2559: sub cstore {
1.124     www      2560:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2561:     my $home='';
                   2562: 
1.168     albertel 2563:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2564: 
1.213     www      2565:     $symb=&symbclean($symb);
1.122     albertel 2566:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2567: 
1.620     albertel 2568:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2569:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2570: 
                   2571:     &devalidate($symb,$stuname,$domain);
1.109     www      2572: 
                   2573:     $symb=escape($symb);
1.187     www      2574:     if (!$namespace) { 
1.620     albertel 2575:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2576:           return ''; 
                   2577:        } 
                   2578:     }
1.620     albertel 2579:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2580: 
                   2581:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2582:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2583: 
1.47      www      2584:     my $namevalue='';
1.191     harris41 2585:     foreach (keys %$storehash) {
1.591     albertel 2586:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2587:     }
1.47      www      2588:     $namevalue=~s/\&$//;
1.187     www      2589:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2590:     return critical
                   2591:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2592: }
                   2593: 
1.9       www      2594: # --------------------------------------------------------------------- Restore
                   2595: 
                   2596: sub restore {
1.124     www      2597:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2598:     my $home='';
                   2599: 
1.168     albertel 2600:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2601: 
1.122     albertel 2602:     if (!$symb) {
                   2603:       unless ($symb=escape(&symbread())) { return ''; }
                   2604:     } else {
1.213     www      2605:       $symb=&escape(&symbclean($symb));
1.122     albertel 2606:     }
1.188     www      2607:     if (!$namespace) { 
1.620     albertel 2608:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2609:           return ''; 
                   2610:        } 
                   2611:     }
1.620     albertel 2612:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2613:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2614:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2615:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2616: 
1.12      www      2617:     my %returnhash=();
1.191     harris41 2618:     foreach (split(/\&/,$answer)) {
1.12      www      2619: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2620:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2621:     }
1.75      www      2622:     my $version;
                   2623:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2624:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2625:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2626:        }
1.75      www      2627:     }
1.13      www      2628:     return %returnhash;
1.34      www      2629: }
                   2630: 
                   2631: # ---------------------------------------------------------- Course Description
                   2632: 
                   2633: sub coursedescription {
1.731     albertel 2634:     my ($courseid,$args)=@_;
1.34      www      2635:     $courseid=~s/^\///;
1.49      www      2636:     $courseid=~s/\_/\//g;
1.34      www      2637:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2638:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2639:     my $normalid=$cdomain.'_'.$cnum;
                   2640:     # need to always cache even if we get errors otherwise we keep 
                   2641:     # trying and trying and trying to get the course description.
                   2642:     my %envhash=();
                   2643:     my %returnhash=();
1.731     albertel 2644:     
                   2645:     my $expiretime=600;
                   2646:     if ($env{'request.course.id'} eq $normalid) {
                   2647: 	$expiretime=120;
                   2648:     }
                   2649: 
                   2650:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2651:     if (!$args->{'freshen_cache'}
                   2652: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2653: 	foreach my $key (keys(%env)) {
                   2654: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2655: 	    my ($setting) = $1;
                   2656: 	    $returnhash{$setting} = $env{$key};
                   2657: 	}
                   2658: 	return %returnhash;
                   2659:     }
                   2660: 
                   2661:     # get the data agin
                   2662:     if (!$args->{'one_time'}) {
                   2663: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2664:     }
1.34      www      2665:     if ($chome ne 'no_host') {
1.302     albertel 2666:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2667:        if (!exists($returnhash{'con_lost'})) {
                   2668:            $returnhash{'home'}= $chome;
                   2669: 	   $returnhash{'domain'} = $cdomain;
                   2670: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2671:            if (!defined($returnhash{'type'})) {
                   2672:                $returnhash{'type'} = 'Course';
                   2673:            }
1.130     albertel 2674:            while (my ($name,$value) = each %returnhash) {
1.53      www      2675:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2676:            }
1.270     www      2677:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2678:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2679: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2680:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2681:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2682:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2683:        }
                   2684:     }
1.731     albertel 2685:     if (!$args->{'one_time'}) {
                   2686: 	&appenv(%envhash);
                   2687:     }
1.302     albertel 2688:     return %returnhash;
1.461     www      2689: }
                   2690: 
                   2691: # -------------------------------------------------See if a user is privileged
                   2692: 
                   2693: sub privileged {
                   2694:     my ($username,$domain)=@_;
                   2695:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2696: 			&homeserver($username,$domain));
                   2697:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2698:     my $now=time;
                   2699:     if ($rolesdump ne '') {
                   2700:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2701: 	    if ($_!~/^rolesdef_/) {
1.461     www      2702: 		my ($area,$role)=split(/=/,$_);
                   2703: 		$area=~s/\_\w\w$//;
                   2704: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2705: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2706: 		    my $active=1;
                   2707: 		    if ($tend) {
                   2708: 			if ($tend<$now) { $active=0; }
                   2709: 		    }
                   2710: 		    if ($tstart) {
                   2711: 			if ($tstart>$now) { $active=0; }
                   2712: 		    }
                   2713: 		    if ($active) { return 1; }
                   2714: 		}
                   2715: 	    }
                   2716: 	}
                   2717:     }
                   2718:     return 0;
1.9       www      2719: }
1.1       albertel 2720: 
1.103     harris41 2721: # -------------------------------------------------------- Get user privileges
1.11      www      2722: 
                   2723: sub rolesinit {
                   2724:     my ($domain,$username,$authhost)=@_;
                   2725:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2726:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2727:     my %allroles=();
1.678     raeburn  2728:     my %allgroups=();   
1.11      www      2729:     my $now=time;
1.743     albertel 2730:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2731:     my $group_privs;
1.11      www      2732: 
                   2733:     if ($rolesdump ne '') {
1.191     harris41 2734:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2735: 	  if ($_!~/^rolesdef_/) {
1.11      www      2736:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2737: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2738:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2739: 	    if ($role=~/^cr/) { 
1.655     albertel 2740: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2741: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2742: 		    ($tend,$tstart)=split('_',$trest);
                   2743: 		} else {
                   2744: 		    $trole=$role;
                   2745: 		}
1.678     raeburn  2746:             } elsif ($role =~ m|^gr/|) {
                   2747:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2748:                 ($trole,$group_privs) = split(/\//,$trole);
                   2749:                 $group_privs = &unescape($group_privs);
1.587     albertel 2750: 	    } else {
                   2751: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2752: 	    }
1.743     albertel 2753: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2754: 					 $username);
                   2755: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2756:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2757:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2758:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2759: 		my $spec=$trole.'.'.$area;
                   2760: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2761: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2762:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2763:                 } elsif ($trole eq 'gr') {
                   2764:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2765: 		} else {
1.567     raeburn  2766:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2767: 		}
1.12      www      2768:             }
1.662     raeburn  2769:           }
1.191     harris41 2770:         }
1.743     albertel 2771:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2772:         $userroles{'user.adv'}    = $adv;
                   2773: 	$userroles{'user.author'} = $author;
1.620     albertel 2774:         $env{'user.adv'}=$adv;
1.11      www      2775:     }
1.743     albertel 2776:     return \%userroles;  
1.11      www      2777: }
                   2778: 
1.567     raeburn  2779: sub set_arearole {
                   2780:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2781: # log the associated role with the area
                   2782:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2783:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2784: }
                   2785: 
                   2786: sub custom_roleprivs {
                   2787:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2788:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2789:     my $homsvr=homeserver($rauthor,$rdomain);
                   2790:     if ($hostname{$homsvr} ne '') {
                   2791:         my ($rdummy,$roledef)=
                   2792:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2793:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2794:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2795:             if (defined($syspriv)) {
                   2796:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2797:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2798:             }
                   2799:             if ($tdomain ne '') {
                   2800:                 if (defined($dompriv)) {
                   2801:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2802:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2803:                 }
                   2804:                 if (($trest ne '') && (defined($coursepriv))) {
                   2805:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2806:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2807:                 }
                   2808:             }
                   2809:         }
                   2810:     }
                   2811: }
                   2812: 
1.678     raeburn  2813: sub group_roleprivs {
                   2814:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2815:     my $access = 1;
                   2816:     my $now = time;
                   2817:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2818:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2819:     if ($access) {
                   2820:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2821:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2822:     }
                   2823: }
1.567     raeburn  2824: 
                   2825: sub standard_roleprivs {
                   2826:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2827:     if (defined($pr{$trole.':s'})) {
                   2828:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2829:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2830:     }
                   2831:     if ($tdomain ne '') {
                   2832:         if (defined($pr{$trole.':d'})) {
                   2833:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2834:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2835:         }
                   2836:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2837:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2838:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2839:         }
                   2840:     }
                   2841: }
                   2842: 
                   2843: sub set_userprivs {
1.678     raeburn  2844:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2845:     my $author=0;
                   2846:     my $adv=0;
1.678     raeburn  2847:     my %grouproles = ();
                   2848:     if (keys(%{$allgroups}) > 0) {
                   2849:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2850:             my ($trole,$area,$sec,$extendedarea);
                   2851:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2852:                 $trole = $1;
                   2853:                 $area = $2;
1.681     raeburn  2854:                 $sec = $3;
                   2855:                 $extendedarea = $area.$sec;
                   2856:                 if (exists($$allgroups{$area})) {
                   2857:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2858:                         my $spec = $trole.'.'.$extendedarea;
                   2859:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2860:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2861:                     }
                   2862:                 }
                   2863:             }
                   2864:         }
                   2865:     }
                   2866:     foreach (keys(%grouproles)) {
                   2867:         $$allroles{$_} = $grouproles{$_};
                   2868:     }
1.567     raeburn  2869:     foreach (keys %{$allroles}) {
                   2870:         my %thesepriv=();
                   2871:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2872:         foreach (split(/:/,$$allroles{$_})) {
                   2873:             if ($_ ne '') {
                   2874:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2875:                 if ($restrictions eq '') {
                   2876:                     $thesepriv{$privilege}='F';
                   2877:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2878:                     $thesepriv{$privilege}.=$restrictions;
                   2879:                 }
                   2880:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2881:             }
                   2882:         }
                   2883:         my $thesestr='';
                   2884:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2885:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2886:     }
                   2887:     return ($author,$adv);
                   2888: }
                   2889: 
1.12      www      2890: # --------------------------------------------------------------- get interface
                   2891: 
                   2892: sub get {
1.131     albertel 2893:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2894:    my $items='';
1.191     harris41 2895:    foreach (@$storearr) {
1.12      www      2896:        $items.=escape($_).'&';
1.191     harris41 2897:    }
1.12      www      2898:    $items=~s/\&$//;
1.620     albertel 2899:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2900:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2901:    my $uhome=&homeserver($uname,$udomain);
                   2902: 
1.133     albertel 2903:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2904:    my @pairs=split(/\&/,$rep);
1.273     albertel 2905:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2906:      return @pairs;
                   2907:    }
1.15      www      2908:    my %returnhash=();
1.42      www      2909:    my $i=0;
1.191     harris41 2910:    foreach (@$storearr) {
1.557     albertel 2911:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2912:       $i++;
1.191     harris41 2913:    }
1.15      www      2914:    return %returnhash;
1.27      www      2915: }
                   2916: 
                   2917: # --------------------------------------------------------------- del interface
                   2918: 
                   2919: sub del {
1.133     albertel 2920:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2921:    my $items='';
1.191     harris41 2922:    foreach (@$storearr) {
1.27      www      2923:        $items.=escape($_).'&';
1.191     harris41 2924:    }
1.27      www      2925:    $items=~s/\&$//;
1.620     albertel 2926:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2927:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2928:    my $uhome=&homeserver($uname,$udomain);
                   2929: 
                   2930:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2931: }
                   2932: 
                   2933: # -------------------------------------------------------------- dump interface
                   2934: 
                   2935: sub dump {
1.755     albertel 2936:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2937:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2938:     if (!$uname) { $uname=$env{'user.name'}; }
                   2939:     my $uhome=&homeserver($uname,$udomain);
                   2940:     if ($regexp) {
                   2941: 	$regexp=&escape($regexp);
                   2942:     } else {
                   2943: 	$regexp='.';
                   2944:     }
                   2945:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2946:     my @pairs=split(/\&/,$rep);
                   2947:     my %returnhash=();
                   2948:     foreach my $item (@pairs) {
                   2949: 	my ($key,$value)=split(/=/,$item,2);
                   2950: 	$key = &unescape($key);
                   2951: 	next if ($key =~ /^error: 2 /);
                   2952: 	$returnhash{$key}=&thaw_unescape($value);
                   2953:     }
                   2954:     return %returnhash;
1.407     www      2955: }
                   2956: 
1.717     albertel 2957: # --------------------------------------------------------- dumpstore interface
                   2958: 
                   2959: sub dumpstore {
                   2960:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2961:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2962: }
                   2963: 
1.407     www      2964: # -------------------------------------------------------------- keys interface
                   2965: 
                   2966: sub getkeys {
                   2967:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2968:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2969:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2970:    my $uhome=&homeserver($uname,$udomain);
                   2971:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2972:    my @keyarray=();
                   2973:    foreach (split(/\&/,$rep)) {
                   2974:       push (@keyarray,&unescape($_));
                   2975:    }
                   2976:    return @keyarray;
1.318     matthew  2977: }
                   2978: 
1.319     matthew  2979: # --------------------------------------------------------------- currentdump
                   2980: sub currentdump {
1.328     matthew  2981:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2982:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2983:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2984:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2985:    my $uhome = &homeserver($sname,$sdom);
                   2986:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2987:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2988:    #
1.318     matthew  2989:    my %returnhash=();
1.319     matthew  2990:    #
                   2991:    if ($rep eq "unknown_cmd") { 
                   2992:        # an old lond will not know currentdump
                   2993:        # Do a dump and make it look like a currentdump
1.326     matthew  2994:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2995:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2996:        my %hash = @tmp;
                   2997:        @tmp=();
1.424     matthew  2998:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2999:    } else {
                   3000:        my @pairs=split(/\&/,$rep);
                   3001:        foreach (@pairs) {
                   3002:            my ($key,$value)=split(/=/,$_);
                   3003:            my ($symb,$param) = split(/:/,$key);
                   3004:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3005:                                                         &thaw_unescape($value);
1.319     matthew  3006:        }
1.191     harris41 3007:    }
1.12      www      3008:    return %returnhash;
1.424     matthew  3009: }
                   3010: 
                   3011: sub convert_dump_to_currentdump{
                   3012:     my %hash = %{shift()};
                   3013:     my %returnhash;
                   3014:     # Code ripped from lond, essentially.  The only difference
                   3015:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3016:     # we might run in to problems with parameter names =~ /^v\./
                   3017:     while (my ($key,$value) = each(%hash)) {
                   3018:         my ($v,$symb,$param) = split(/:/,$key);
                   3019:         next if ($v eq 'version' || $symb eq 'keys');
                   3020:         next if (exists($returnhash{$symb}) &&
                   3021:                  exists($returnhash{$symb}->{$param}) &&
                   3022:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3023:         $returnhash{$symb}->{$param}=$value;
                   3024:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3025:     }
                   3026:     #
                   3027:     # Remove all of the keys in the hashes which keep track of
                   3028:     # the version of the parameter.
                   3029:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3030:         # use a foreach because we are going to delete from the hash.
                   3031:         foreach my $key (keys(%$param_hash)) {
                   3032:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3033:         }
                   3034:     }
                   3035:     return \%returnhash;
1.12      www      3036: }
                   3037: 
1.627     albertel 3038: # ------------------------------------------------------ critical inc interface
                   3039: 
                   3040: sub cinc {
                   3041:     return &inc(@_,'critical');
                   3042: }
                   3043: 
1.449     matthew  3044: # --------------------------------------------------------------- inc interface
                   3045: 
                   3046: sub inc {
1.627     albertel 3047:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3048:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3049:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3050:     my $uhome=&homeserver($uname,$udomain);
                   3051:     my $items='';
                   3052:     if (! ref($store)) {
                   3053:         # got a single value, so use that instead
                   3054:         $items = &escape($store).'=&';
                   3055:     } elsif (ref($store) eq 'SCALAR') {
                   3056:         $items = &escape($$store).'=&';        
                   3057:     } elsif (ref($store) eq 'ARRAY') {
                   3058:         $items = join('=&',map {&escape($_);} @{$store});
                   3059:     } elsif (ref($store) eq 'HASH') {
                   3060:         while (my($key,$value) = each(%{$store})) {
                   3061:             $items.= &escape($key).'='.&escape($value).'&';
                   3062:         }
                   3063:     }
                   3064:     $items=~s/\&$//;
1.627     albertel 3065:     if ($critical) {
                   3066: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3067:     } else {
                   3068: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3069:     }
1.449     matthew  3070: }
                   3071: 
1.12      www      3072: # --------------------------------------------------------------- put interface
                   3073: 
                   3074: sub put {
1.134     albertel 3075:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3077:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3078:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3079:    my $items='';
1.191     harris41 3080:    foreach (keys %$storehash) {
1.557     albertel 3081:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3082:    }
1.12      www      3083:    $items=~s/\&$//;
1.134     albertel 3084:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3085: }
                   3086: 
1.631     albertel 3087: # ------------------------------------------------------------ newput interface
                   3088: 
                   3089: sub newput {
                   3090:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3091:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3092:    if (!$uname) { $uname=$env{'user.name'}; }
                   3093:    my $uhome=&homeserver($uname,$udomain);
                   3094:    my $items='';
                   3095:    foreach my $key (keys(%$storehash)) {
                   3096:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3097:    }
                   3098:    $items=~s/\&$//;
                   3099:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3100: }
                   3101: 
                   3102: # ---------------------------------------------------------  putstore interface
                   3103: 
1.524     raeburn  3104: sub putstore {
1.715     albertel 3105:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3106:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3107:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3108:    my $uhome=&homeserver($uname,$udomain);
                   3109:    my $items='';
1.715     albertel 3110:    foreach my $key (keys(%$storehash)) {
                   3111:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3112:    }
1.715     albertel 3113:    $items=~s/\&$//;
1.716     albertel 3114:    my $esc_symb=&escape($symb);
                   3115:    my $esc_v=&escape($version);
1.715     albertel 3116:    my $reply =
1.716     albertel 3117:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3118: 	      $uhome);
                   3119:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3120:        # gfall back to way things use to be done
1.715     albertel 3121:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3122: 			    $uname);
1.524     raeburn  3123:    }
1.715     albertel 3124:    return $reply;
                   3125: }
                   3126: 
                   3127: sub old_putstore {
1.716     albertel 3128:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3129:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3130:     if (!$uname) { $uname=$env{'user.name'}; }
                   3131:     my $uhome=&homeserver($uname,$udomain);
                   3132:     my %newstorehash;
                   3133:     foreach (keys %$storehash) {
                   3134: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3135: 	$newstorehash{$key} = $storehash->{$_};
                   3136:     }
                   3137:     my $items='';
                   3138:     my %allitems = ();
                   3139:     foreach (keys %newstorehash) {
                   3140: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3141: 	    my $key = $1.':keys:'.$2;
                   3142: 	    $allitems{$key} .= $3.':';
                   3143: 	}
                   3144: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3145:     }
                   3146:     foreach (keys %allitems) {
                   3147: 	$allitems{$_} =~ s/\:$//;
                   3148: 	$items.= $_.'='.$allitems{$_}.'&';
                   3149:     }
                   3150:     $items=~s/\&$//;
                   3151:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3152: }
                   3153: 
1.47      www      3154: # ------------------------------------------------------ critical put interface
                   3155: 
                   3156: sub cput {
1.134     albertel 3157:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3158:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3159:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3160:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3161:    my $items='';
1.191     harris41 3162:    foreach (keys %$storehash) {
1.715     albertel 3163:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3164:    }
1.47      www      3165:    $items=~s/\&$//;
1.134     albertel 3166:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3167: }
                   3168: 
                   3169: # -------------------------------------------------------------- eget interface
                   3170: 
                   3171: sub eget {
1.133     albertel 3172:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3173:    my $items='';
1.191     harris41 3174:    foreach (@$storearr) {
1.12      www      3175:        $items.=escape($_).'&';
1.191     harris41 3176:    }
1.12      www      3177:    $items=~s/\&$//;
1.620     albertel 3178:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3179:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3180:    my $uhome=&homeserver($uname,$udomain);
                   3181:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3182:    my @pairs=split(/\&/,$rep);
                   3183:    my %returnhash=();
1.42      www      3184:    my $i=0;
1.191     harris41 3185:    foreach (@$storearr) {
1.557     albertel 3186:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3187:       $i++;
1.191     harris41 3188:    }
1.12      www      3189:    return %returnhash;
                   3190: }
                   3191: 
1.667     albertel 3192: # ------------------------------------------------------------ tmpput interface
                   3193: sub tmpput {
                   3194:     my ($storehash,$server)=@_;
                   3195:     my $items='';
                   3196:     foreach (keys(%$storehash)) {
                   3197: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3198:     }
                   3199:     $items=~s/\&$//;
                   3200:     return &reply("tmpput:$items",$server);
                   3201: }
                   3202: 
                   3203: # ------------------------------------------------------------ tmpget interface
                   3204: sub tmpget {
1.688     albertel 3205:     my ($token,$server)=@_;
                   3206:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3207:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3208:     my %returnhash;
                   3209:     foreach my $item (split(/\&/,$rep)) {
                   3210: 	my ($key,$value)=split(/=/,$item);
                   3211: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3212:     }
                   3213:     return %returnhash;
                   3214: }
                   3215: 
1.688     albertel 3216: # ------------------------------------------------------------ tmpget interface
                   3217: sub tmpdel {
                   3218:     my ($token,$server)=@_;
                   3219:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3220:     return &reply("tmpdel:$token",$server);
                   3221: }
                   3222: 
1.341     www      3223: # ---------------------------------------------- Custom access rule evaluation
                   3224: 
                   3225: sub customaccess {
                   3226:     my ($priv,$uri)=@_;
1.620     albertel 3227:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3228:     $urealm=~s/^\W//;
                   3229:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3230:     my $access=0;
                   3231:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3232: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3233:         if ($role) {
                   3234: 	   if ($role ne $urole) { next; }
                   3235:         }
                   3236:         foreach (split(/\s*\,\s*/,$realm)) {
                   3237:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3238:             if ($tdom) {
                   3239: 		if ($tdom ne $udom) { next; }
                   3240:             }
                   3241:             if ($tcrs) {
                   3242: 		if ($tcrs ne $ucrs) { next; }
                   3243:             }
                   3244:             if ($tsec) {
                   3245: 		if ($tsec ne $usec) { next; }
                   3246:             }
                   3247:             $access=($effect eq 'allow');
                   3248:             last;
1.342     www      3249:         }
1.402     bowersj2 3250: 	if ($realm eq '' && $role eq '') {
                   3251:             $access=($effect eq 'allow');
                   3252: 	}
1.341     www      3253:     }
                   3254:     return $access;
                   3255: }
                   3256: 
1.103     harris41 3257: # ------------------------------------------------- Check for a user privilege
1.12      www      3258: 
                   3259: sub allowed {
1.579     albertel 3260:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3261:     my $ver_orguri=$uri;
1.439     www      3262:     $uri=&deversion($uri);
1.152     www      3263:     my $orguri=$uri;
1.52      www      3264:     $uri=&declutter($uri);
1.545     banghart 3265:     
1.620     albertel 3266:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3267: # Free bre access to adm and meta resources
1.529     albertel 3268:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3269: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3270: 	return 'F';
1.159     www      3271:     }
                   3272: 
1.545     banghart 3273: # Free bre access to user's own portfolio contents
1.714     raeburn  3274:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3275:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3276: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3277:         return 'F';
                   3278:     }
                   3279: 
1.714     raeburn  3280: # bre access to group if user has rgf priv for this group and course.
                   3281:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3282:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3283:         if (exists($env{'request.course.id'})) {
                   3284:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3285:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3286:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3287:                 my $courseprivid=$env{'request.course.id'};
                   3288:                 $courseprivid=~s/\_/\//;
                   3289:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3290:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3291:                     return $1; 
                   3292:                 }
                   3293:             }
                   3294:         }
                   3295:     }
                   3296: 
1.159     www      3297: # Free bre to public access
                   3298: 
                   3299:     if ($priv eq 'bre') {
1.238     www      3300:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3301: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3302:            return 'F'; 
                   3303:         }
1.238     www      3304:         if ($copyright eq 'priv') {
                   3305:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3306: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3307: 		return '';
                   3308:             }
                   3309:         }
                   3310:         if ($copyright eq 'domain') {
                   3311:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3312: 	    unless (($env{'user.domain'} eq $1) ||
                   3313:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3314: 		return '';
                   3315:             }
1.262     matthew  3316:         }
1.620     albertel 3317:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3318:             # Library role, so allow browsing of resources in this domain.
                   3319:             return 'F';
1.238     www      3320:         }
1.341     www      3321:         if ($copyright eq 'custom') {
                   3322: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3323:         }
1.14      www      3324:     }
1.264     matthew  3325:     # Domain coordinator is trying to create a course
1.620     albertel 3326:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3327:         # uri is the requested domain in this case.
                   3328:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3329:         # a role of dc for the domain in question.
1.620     albertel 3330:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3331:     }
1.29      www      3332: 
1.52      www      3333:     my $thisallowed='';
                   3334:     my $statecond=0;
                   3335:     my $courseprivid='';
                   3336: 
                   3337: # Course
                   3338: 
1.620     albertel 3339:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3340:        $thisallowed.=$1;
                   3341:     }
1.29      www      3342: 
1.52      www      3343: # Domain
                   3344: 
1.620     albertel 3345:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3346:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3347:        $thisallowed.=$1;
                   3348:     }
1.52      www      3349: 
                   3350: # Course: uri itself is a course
1.66      www      3351:     my $courseuri=$uri;
                   3352:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3353:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3354: 
1.620     albertel 3355:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3356:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3357:        $thisallowed.=$1;
                   3358:     }
1.29      www      3359: 
1.678     raeburn  3360: # Group: uri itself is a group
                   3361:     my $groupuri=$uri;
                   3362:     $groupuri=~s/^([^\/])/\/$1/;
                   3363:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3364:        =~/\Q$priv\E\&([^\:]*)/) {
                   3365:        $thisallowed.=$1;
                   3366:     }
                   3367: 
1.665     albertel 3368: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3369: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3370:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3371: 	$thisallowed='';
1.671     raeburn  3372:         my ($match)=&is_on_map($uri);
                   3373:         if ($match) {
                   3374:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3375:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3376:                 $thisallowed.=$1;
                   3377:             }
                   3378:         } else {
1.705     albertel 3379:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3380:             if ($refuri) {
                   3381:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3382:                     $thisallowed='F';
1.671     raeburn  3383:                 } else {
                   3384:                     $refuri=&declutter($refuri);
                   3385:                     my ($match) = &is_on_map($refuri);
                   3386:                     if ($match) {
                   3387:                         $thisallowed='F';
                   3388:                     }
1.669     raeburn  3389:                 }
1.671     raeburn  3390:             }
                   3391:         }
1.314     www      3392:     }
1.492     albertel 3393: 
1.52      www      3394: # Full access at system, domain or course-wide level? Exit.
1.29      www      3395: 
                   3396:     if ($thisallowed=~/F/) {
                   3397: 	return 'F';
                   3398:     }
                   3399: 
1.52      www      3400: # If this is generating or modifying users, exit with special codes
1.29      www      3401: 
1.643     www      3402:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3403: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3404: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3405: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3406: 	    unless ($auname) { return $thisallowed; }
                   3407: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3408: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3409: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3410: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3411: 	}
1.52      www      3412: 	return $thisallowed;
                   3413:     }
                   3414: #
1.103     harris41 3415: # Gathered so far: system, domain and course wide privileges
1.52      www      3416: #
                   3417: # Course: See if uri or referer is an individual resource that is part of 
                   3418: # the course
                   3419: 
1.620     albertel 3420:     if ($env{'request.course.id'}) {
1.232     www      3421: 
1.620     albertel 3422:        $courseprivid=$env{'request.course.id'};
                   3423:        if ($env{'request.course.sec'}) {
                   3424:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3425:        }
                   3426:        $courseprivid=~s/\_/\//;
                   3427:        my $checkreferer=1;
1.232     www      3428:        my ($match,$cond)=&is_on_map($uri);
                   3429:        if ($match) {
                   3430:            $statecond=$cond;
1.620     albertel 3431:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3432:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3433:                $thisallowed.=$1;
                   3434:                $checkreferer=0;
                   3435:            }
1.29      www      3436:        }
1.83      www      3437:        
1.148     www      3438:        if ($checkreferer) {
1.620     albertel 3439: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3440:             unless ($refuri) {
1.620     albertel 3441:                 foreach (keys %env) {
1.148     www      3442: 		    if ($_=~/^httpref\..*\*/) {
                   3443: 			my $pattern=$_;
1.156     www      3444:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3445:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3446:                         $pattern=~s/\//\\\//g;
1.152     www      3447:                         if ($orguri=~/$pattern/) {
1.620     albertel 3448: 			    $refuri=$env{$_};
1.148     www      3449:                         }
                   3450:                     }
1.191     harris41 3451:                 }
1.148     www      3452:             }
1.232     www      3453: 
1.148     www      3454:          if ($refuri) { 
1.152     www      3455: 	  $refuri=&declutter($refuri);
1.232     www      3456:           my ($match,$cond)=&is_on_map($refuri);
                   3457:             if ($match) {
                   3458:               my $refstatecond=$cond;
1.620     albertel 3459:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3460:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3461:                   $thisallowed.=$1;
1.53      www      3462:                   $uri=$refuri;
                   3463:                   $statecond=$refstatecond;
1.52      www      3464:               }
                   3465:           }
1.148     www      3466:         }
1.29      www      3467:        }
1.52      www      3468:    }
1.29      www      3469: 
1.52      www      3470: #
1.103     harris41 3471: # Gathered now: all privileges that could apply, and condition number
1.52      www      3472: # 
                   3473: #
                   3474: # Full or no access?
                   3475: #
1.29      www      3476: 
1.52      www      3477:     if ($thisallowed=~/F/) {
                   3478: 	return 'F';
                   3479:     }
1.29      www      3480: 
1.52      www      3481:     unless ($thisallowed) {
                   3482:         return '';
                   3483:     }
1.29      www      3484: 
1.52      www      3485: # Restrictions exist, deal with them
                   3486: #
                   3487: #   C:according to course preferences
                   3488: #   R:according to resource settings
                   3489: #   L:unless locked
                   3490: #   X:according to user session state
                   3491: #
                   3492: 
                   3493: # Possibly locked functionality, check all courses
1.54      www      3494: # Locks might take effect only after 10 minutes cache expiration for other
                   3495: # courses, and 2 minutes for current course
1.52      www      3496: 
                   3497:     my $envkey;
                   3498:     if ($thisallowed=~/L/) {
1.620     albertel 3499:         foreach $envkey (keys %env) {
1.54      www      3500:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3501:                my $courseid=$2;
                   3502:                my $roleid=$1.'.'.$2;
1.92      www      3503:                $courseid=~s/^\///;
1.54      www      3504:                my $expiretime=600;
1.620     albertel 3505:                if ($env{'request.role'} eq $roleid) {
1.54      www      3506: 		  $expiretime=120;
                   3507:                }
                   3508: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3509:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3510:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3511: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3512:                }
1.620     albertel 3513:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3514:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3515: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3516:                        &log($env{'user.domain'},$env{'user.name'},
                   3517:                             $env{'user.home'},
1.57      www      3518:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3519:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3520:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3521: 		       return '';
                   3522:                    }
                   3523:                }
1.620     albertel 3524:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3525:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3526: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3527:                        &log($env{'user.domain'},$env{'user.name'},
                   3528:                             $env{'user.home'},
1.57      www      3529:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3530:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3531:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3532: 		       return '';
                   3533:                    }
                   3534:                }
                   3535: 	   }
1.29      www      3536:        }
1.52      www      3537:     }
                   3538:    
                   3539: #
                   3540: # Rest of the restrictions depend on selected course
                   3541: #
                   3542: 
1.620     albertel 3543:     unless ($env{'request.course.id'}) {
1.52      www      3544:        return '1';
                   3545:     }
1.29      www      3546: 
1.52      www      3547: #
                   3548: # Now user is definitely in a course
                   3549: #
1.53      www      3550: 
                   3551: 
                   3552: # Course preferences
                   3553: 
                   3554:    if ($thisallowed=~/C/) {
1.620     albertel 3555:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3556:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3557:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3558: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3559: 	   if ($priv ne 'pch') { 
                   3560: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3561: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3562: 			$env{'request.course.id'});
                   3563: 	   }
1.237     www      3564:            return '';
                   3565:        }
                   3566: 
1.620     albertel 3567:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3568: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3569: 	   if ($priv ne 'pch') { 
                   3570: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3571: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3572: 			$env{'request.course.id'});
                   3573: 	   }
1.54      www      3574:            return '';
                   3575:        }
1.53      www      3576:    }
                   3577: 
                   3578: # Resource preferences
                   3579: 
                   3580:    if ($thisallowed=~/R/) {
1.620     albertel 3581:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3582:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3583: 	   if ($priv ne 'pch') { 
                   3584: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3585: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3586: 	   }
                   3587: 	   return '';
1.54      www      3588:        }
1.53      www      3589:    }
1.30      www      3590: 
1.246     www      3591: # Restricted by state or randomout?
1.30      www      3592: 
1.52      www      3593:    if ($thisallowed=~/X/) {
1.620     albertel 3594:       if ($env{'acc.randomout'}) {
1.579     albertel 3595: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3596:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3597:             return ''; 
                   3598:          }
1.247     www      3599:       }
                   3600:       if (&condval($statecond)) {
1.52      www      3601: 	 return '2';
                   3602:       } else {
                   3603:          return '';
                   3604:       }
                   3605:    }
1.30      www      3606: 
1.52      www      3607:    return 'F';
1.232     www      3608: }
                   3609: 
1.710     albertel 3610: sub split_uri_for_cond {
                   3611:     my $uri=&deversion(&declutter(shift));
                   3612:     my @uriparts=split(/\//,$uri);
                   3613:     my $filename=pop(@uriparts);
                   3614:     my $pathname=join('/',@uriparts);
                   3615:     return ($pathname,$filename);
                   3616: }
1.232     www      3617: # --------------------------------------------------- Is a resource on the map?
                   3618: 
                   3619: sub is_on_map {
1.710     albertel 3620:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3621:     #Trying to find the conditional for the file
1.620     albertel 3622:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3623: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3624:     if ($match) {
1.289     bowersj2 3625: 	return (1,$1);
                   3626:     } else {
1.434     www      3627: 	return (0,0);
1.289     bowersj2 3628:     }
1.12      www      3629: }
                   3630: 
1.427     www      3631: # --------------------------------------------------------- Get symb from alias
                   3632: 
                   3633: sub get_symb_from_alias {
                   3634:     my $symb=shift;
                   3635:     my ($map,$resid,$url)=&decode_symb($symb);
                   3636: # Already is a symb
                   3637:     if ($url) { return $symb; }
                   3638: # Must be an alias
                   3639:     my $aliassymb='';
                   3640:     my %bighash;
1.620     albertel 3641:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3642:                             &GDBM_READER(),0640)) {
                   3643:         my $rid=$bighash{'mapalias_'.$symb};
                   3644: 	if ($rid) {
                   3645: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3646: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3647: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3648: 	}
                   3649:         untie %bighash;
                   3650:     }
                   3651:     return $aliassymb;
                   3652: }
                   3653: 
1.12      www      3654: # ----------------------------------------------------------------- Define Role
                   3655: 
                   3656: sub definerole {
                   3657:   if (allowed('mcr','/')) {
                   3658:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3659:     foreach (split(':',$sysrole)) {
1.21      www      3660: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3661:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3662:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3663: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3664:                return "refused:s:$crole&$cqual"; 
                   3665:             }
                   3666:         }
1.191     harris41 3667:     }
1.392     www      3668:     foreach (split(':',$domrole)) {
1.21      www      3669: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3670:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3671:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3672: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3673:                return "refused:d:$crole&$cqual"; 
                   3674:             }
                   3675:         }
1.191     harris41 3676:     }
1.392     www      3677:     foreach (split(':',$courole)) {
1.21      www      3678: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3679:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3680:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3681: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3682:                return "refused:c:$crole&$cqual"; 
                   3683:             }
                   3684:         }
1.191     harris41 3685:     }
1.620     albertel 3686:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3687:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3688: 	        "rolesdef_$rolename=".
                   3689:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3690:     return reply($command,$env{'user.home'});
1.12      www      3691:   } else {
                   3692:     return 'refused';
                   3693:   }
1.105     harris41 3694: }
                   3695: 
                   3696: # ---------------- Make a metadata query against the network of library servers
                   3697: 
                   3698: sub metadata_query {
1.244     matthew  3699:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3700:     my %rhash;
1.244     matthew  3701:     my @server_list = (defined($server_array) ? @$server_array
                   3702:                                               : keys(%libserv) );
                   3703:     for my $server (@server_list) {
1.118     harris41 3704: 	unless ($custom or $customshow) {
                   3705: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3706: 	    $rhash{$server}=$reply;
                   3707: 	}
                   3708: 	else {
                   3709: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3710: 			     &escape($custom).':'.&escape($customshow),
                   3711: 			     $server);
                   3712: 	    $rhash{$server}=$reply;
                   3713: 	}
1.112     harris41 3714:     }
1.118     harris41 3715:     return \%rhash;
1.240     www      3716: }
                   3717: 
                   3718: # ----------------------------------------- Send log queries and wait for reply
                   3719: 
                   3720: sub log_query {
                   3721:     my ($uname,$udom,$query,%filters)=@_;
                   3722:     my $uhome=&homeserver($uname,$udom);
                   3723:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3724:     my $uhost=$hostname{$uhome};
1.241     www      3725:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3726:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3727:                        $uhome);
1.479     albertel 3728:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3729:     return get_query_reply($queryid);
                   3730: }
                   3731: 
1.508     raeburn  3732: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3733: 
                   3734: sub fetch_enrollment_query {
1.511     raeburn  3735:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3736:     my $homeserver;
1.547     raeburn  3737:     my $maxtries = 1;
1.508     raeburn  3738:     if ($context eq 'automated') {
                   3739:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3740:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3741:     } else {
                   3742:         $homeserver = &homeserver($cnum,$dom);
                   3743:     }
1.506     raeburn  3744:     my $host=$hostname{$homeserver};
                   3745:     my $cmd = '';
                   3746:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3747:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3748:     }
                   3749:     $cmd =~ s/%%$//;
                   3750:     $cmd = &escape($cmd);
                   3751:     my $query = 'fetchenrollment';
1.620     albertel 3752:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3753:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3754:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3755:         return 'error: '.$queryid;
                   3756:     }
1.506     raeburn  3757:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3758:     my $tries = 1;
                   3759:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3760:         $reply = &get_query_reply($queryid);
                   3761:         $tries ++;
                   3762:     }
1.526     raeburn  3763:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3764:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3765:     } else {
1.515     raeburn  3766:         my @responses = split/:/,$reply;
                   3767:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3768:             foreach (@responses) {
                   3769:                 my ($key,$value) = split/=/,$_;
                   3770:                 $$replyref{$key} = $value;
                   3771:             }
                   3772:         } else {
1.506     raeburn  3773:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3774:             foreach (@responses) {
                   3775:                 my ($key,$value) = split/=/,$_;
                   3776:                 $$replyref{$key} = $value;
                   3777:                 if ($value > 0) {
                   3778:                     foreach (@{$$affiliatesref{$key}}) {
                   3779:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3780:                         my $destname = $pathname.'/'.$filename;
                   3781:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3782:                         if ($xml_classlist =~ /^error/) {
                   3783:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3784:                         } else {
1.506     raeburn  3785:                             if ( open(FILE,">$destname") ) {
                   3786:                                 print FILE &unescape($xml_classlist);
                   3787:                                 close(FILE);
1.526     raeburn  3788:                             } else {
                   3789:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3790:                             }
                   3791:                         }
                   3792:                     }
                   3793:                 }
                   3794:             }
                   3795:         }
                   3796:         return 'ok';
                   3797:     }
                   3798:     return 'error';
                   3799: }
                   3800: 
1.242     www      3801: sub get_query_reply {
                   3802:     my $queryid=shift;
1.240     www      3803:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3804:     my $reply='';
                   3805:     for (1..100) {
                   3806: 	sleep 2;
                   3807:         if (-e $replyfile.'.end') {
1.448     albertel 3808: 	    if (open(my $fh,$replyfile)) {
1.240     www      3809:                $reply.=<$fh>;
1.448     albertel 3810:                close($fh);
1.240     www      3811: 	   } else { return 'error: reply_file_error'; }
1.242     www      3812:            return &unescape($reply);
                   3813: 	}
1.240     www      3814:     }
1.242     www      3815:     return 'timeout:'.$queryid;
1.240     www      3816: }
                   3817: 
                   3818: sub courselog_query {
1.241     www      3819: #
                   3820: # possible filters:
                   3821: # url: url or symb
                   3822: # username
                   3823: # domain
                   3824: # action: view, submit, grade
                   3825: # start: timestamp
                   3826: # end: timestamp
                   3827: #
1.240     www      3828:     my (%filters)=@_;
1.620     albertel 3829:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3830:     if ($filters{'url'}) {
                   3831: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3832:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3833:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3834:     }
1.620     albertel 3835:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3836:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3837:     return &log_query($cname,$cdom,'courselog',%filters);
                   3838: }
                   3839: 
                   3840: sub userlog_query {
                   3841:     my ($uname,$udom,%filters)=@_;
                   3842:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3843: }
                   3844: 
1.506     raeburn  3845: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3846: 
                   3847: sub auto_run {
1.508     raeburn  3848:     my ($cnum,$cdom) = @_;
                   3849:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3850:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3851:     return $response;
                   3852: }
                   3853:                                                                                    
                   3854: sub auto_get_sections {
1.508     raeburn  3855:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3856:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3857:     my @secs = ();
1.511     raeburn  3858:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3859:     unless ($response eq 'refused') {
                   3860:         @secs = split/:/,$response;
                   3861:     }
                   3862:     return @secs;
                   3863: }
                   3864:                                                                                    
                   3865: sub auto_new_course {
1.508     raeburn  3866:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3867:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3868:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3869:     return $response;
                   3870: }
                   3871:                                                                                    
                   3872: sub auto_validate_courseID {
1.508     raeburn  3873:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3874:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3875:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3876:     return $response;
                   3877: }
                   3878:                                                                                    
                   3879: sub auto_create_password {
1.508     raeburn  3880:     my ($cnum,$cdom,$authparam) = @_;
                   3881:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3882:     my $create_passwd = 0;
                   3883:     my $authchk = '';
1.511     raeburn  3884:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3885:     if ($response eq 'refused') {
                   3886:         $authchk = 'refused';
                   3887:     } else {
                   3888:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3889:     }
                   3890:     return ($authparam,$create_passwd,$authchk);
                   3891: }
                   3892: 
1.706     raeburn  3893: sub auto_photo_permission {
                   3894:     my ($cnum,$cdom,$students) = @_;
                   3895:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 3896:     my ($outcome,$perm_reqd,$conditions) = 
                   3897: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 3898:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3899: 	return (undef,undef);
                   3900:     }
1.706     raeburn  3901:     return ($outcome,$perm_reqd,$conditions);
                   3902: }
                   3903: 
                   3904: sub auto_checkphotos {
                   3905:     my ($uname,$udom,$pid) = @_;
                   3906:     my $homeserver = &homeserver($uname,$udom);
                   3907:     my ($result,$resulttype);
                   3908:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 3909: 				   &escape($uname).':'.&escape($pid),
                   3910: 				   $homeserver));
1.709     albertel 3911:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3912: 	return (undef,undef);
                   3913:     }
1.706     raeburn  3914:     if ($outcome) {
                   3915:         ($result,$resulttype) = split(/:/,$outcome);
                   3916:     } 
                   3917:     return ($result,$resulttype);
                   3918: }
                   3919: 
                   3920: sub auto_photochoice {
                   3921:     my ($cnum,$cdom) = @_;
                   3922:     my $homeserver = &homeserver($cnum,$cdom);
                   3923:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 3924: 						       &escape($cdom),
                   3925: 						       $homeserver)));
1.709     albertel 3926:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3927: 	return (undef,undef);
                   3928:     }
1.706     raeburn  3929:     return ($update,$comment);
                   3930: }
                   3931: 
                   3932: sub auto_photoupdate {
                   3933:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   3934:     my $homeserver = &homeserver($cnum,$dom);
                   3935:     my $host=$hostname{$homeserver};
                   3936:     my $cmd = '';
                   3937:     my $maxtries = 1;
                   3938:     foreach (keys %{$affiliatesref}) {
                   3939:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   3940:     }
                   3941:     $cmd =~ s/%%$//;
                   3942:     $cmd = &escape($cmd);
                   3943:     my $query = 'institutionalphotos';
                   3944:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   3945:     unless ($queryid=~/^\Q$host\E\_/) {
                   3946:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   3947:         return 'error: '.$queryid;
                   3948:     }
                   3949:     my $reply = &get_query_reply($queryid);
                   3950:     my $tries = 1;
                   3951:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3952:         $reply = &get_query_reply($queryid);
                   3953:         $tries ++;
                   3954:     }
                   3955:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   3956:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   3957:     } else {
                   3958:         my @responses = split(/:/,$reply);
                   3959:         my $outcome = shift(@responses); 
                   3960:         foreach my $item (@responses) {
                   3961:             my ($key,$value) = split(/=/,$item);
                   3962:             $$photo{$key} = $value;
                   3963:         }
                   3964:         return $outcome;
                   3965:     }
                   3966:     return 'error';
                   3967: }
                   3968: 
1.521     raeburn  3969: sub auto_instcode_format {
                   3970:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3971:     my $courses = '';
                   3972:     my $homeserver;
                   3973:     if ($caller eq 'global') {
1.584     raeburn  3974:         foreach my $tryserver (keys %libserv) {
                   3975:             if ($hostdom{$tryserver} eq $codedom) {
                   3976:                 $homeserver = $tryserver;
                   3977:                 last;
                   3978:             }
                   3979:         }
1.620     albertel 3980:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3981:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3982:         }
1.521     raeburn  3983:     } else {
                   3984:         $homeserver = &homeserver($caller,$codedom);
                   3985:     }
                   3986:     foreach (keys %{$instcodes}) {
                   3987:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3988:     }
                   3989:     chop($courses);
                   3990:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3991:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3992:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3993:         %{$codes} = &str2hash($codes_str);
                   3994:         @{$codetitles} = &str2array($codetitles_str);
                   3995:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3996:         %{$cat_order} = &str2hash($cat_order_str);
                   3997:         return 'ok';
                   3998:     }
                   3999:     return $response;
                   4000: }
                   4001: 
1.679     raeburn  4002: # ------------------------------------------------------- Course Group routines
                   4003: 
                   4004: sub get_coursegroups {
1.683     raeburn  4005:     my ($cdom,$cnum,$group) = @_;
                   4006:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4007: }
                   4008: 
                   4009: sub modify_coursegroup {
                   4010:     my ($cdom,$cnum,$groupsettings) = @_;
                   4011:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4012: }
                   4013: 
                   4014: sub modify_group_roles {
                   4015:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4016:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4017:     my $role = 'gr/'.&escape($userprivs);
                   4018:     my ($uname,$udom) = split(/:/,$user);
                   4019:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4020:     if ($result eq 'ok') {
                   4021:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4022:     }
1.679     raeburn  4023:     return $result;
                   4024: }
                   4025: 
                   4026: sub modify_coursegroup_membership {
                   4027:     my ($cdom,$cnum,$membership) = @_;
                   4028:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4029:     return $result;
                   4030: }
                   4031: 
1.682     raeburn  4032: sub get_active_groups {
                   4033:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4034:     my $now = time;
                   4035:     my %groups = ();
                   4036:     foreach my $key (keys(%env)) {
                   4037:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4038:             my ($start,$end) = split(/\./,$env{$key});
                   4039:             if (($end!=0) && ($end<$now)) { next; }
                   4040:             if (($start!=0) && ($start>$now)) { next; }
                   4041:             if ($1 eq $cdom && $2 eq $cnum) {
                   4042:                 $groups{$3} = $env{$key} ;
                   4043:             }
                   4044:         }
                   4045:     }
                   4046:     return %groups;
                   4047: }
                   4048: 
1.683     raeburn  4049: sub get_group_membership {
                   4050:     my ($cdom,$cnum,$group) = @_;
                   4051:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4052: }
                   4053: 
                   4054: sub get_users_groups {
                   4055:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4056:     my @usersgroups;
1.683     raeburn  4057:     my $cachetime=1800;
                   4058:     $courseid=~s/\_/\//g;
                   4059:     $courseid=~s/^(\w)/\/$1/;
                   4060: 
                   4061:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4062:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4063:     if (defined($cached)) {
1.734     albertel 4064:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4065:     } else {  
                   4066:         $grouplist = '';
                   4067:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4068:         my ($tmp) = keys(%roleshash);
                   4069:         if ($tmp=~/^error:/) {
                   4070:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4071:         } else {
                   4072:             my $access_end = $env{'course.'.$courseid.
                   4073:                                   '.default_enrollment_end_date'};
                   4074:             my $now = time;
1.734     albertel 4075:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4076:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4077:                     my $group = $1;
                   4078:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4079:                         my $start = $2;
                   4080:                         my $end = $1;
                   4081:                         if ($start == -1) { next; } # deleted from group
                   4082:                         if (($start!=0) && ($start>$now)) { next; }
                   4083:                         if (($end!=0) && ($end<$now)) {
                   4084:                             if ($access_end && $access_end < $now) {
                   4085:                                 if ($access_end - $end < 86400) {
                   4086:                                     push(@usersgroups,$group);
                   4087:                                 }
                   4088:                             }
                   4089:                             next;
                   4090:                         }
                   4091:                         push(@usersgroups,$group);
                   4092:                     }
1.683     raeburn  4093:                 }
                   4094:             }
1.733     raeburn  4095:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4096:             $grouplist = join(':',@usersgroups);
                   4097:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4098:         }
                   4099:     }
1.733     raeburn  4100:     return @usersgroups;
1.683     raeburn  4101: }
                   4102: 
                   4103: sub devalidate_getgroups_cache {
                   4104:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4105:     my $courseid = $cdom.'_'.$cnum;
                   4106:     $courseid=~s/\_/\//g;
                   4107:     $courseid=~s/^(\w)/\/$1/;
                   4108:     my $hashid="$udom:$uname:$courseid";
                   4109:     &devalidate_cache_new('getgroups',$hashid);
                   4110: }
                   4111: 
1.12      www      4112: # ------------------------------------------------------------------ Plain Text
                   4113: 
                   4114: sub plaintext {
1.742     raeburn  4115:     my ($short,$type,$cid) = @_;
                   4116:     if (!defined($cid)) {
                   4117:         $cid = $env{'request.course.id'};
                   4118:     }
                   4119:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4120:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4121:                                           '.plaintext'});
                   4122:     }
                   4123:     my %rolenames = (
                   4124:                       Course => 'std',
                   4125:                       Group => 'alt1',
                   4126:                     );
                   4127:     if (defined($type) && 
                   4128:          defined($rolenames{$type}) && 
                   4129:          defined($prp{$short}{$rolenames{$type}})) {
                   4130:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4131:     } else {
                   4132:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4133:     }
1.12      www      4134: }
                   4135: 
                   4136: # ----------------------------------------------------------------- Assign Role
                   4137: 
                   4138: sub assignrole {
1.357     www      4139:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4140:     my $mrole;
                   4141:     if ($role =~ /^cr\//) {
1.393     www      4142:         my $cwosec=$url;
                   4143:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4144: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4145:            &logthis('Refused custom assignrole: '.
                   4146:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4147: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4148:            return 'refused'; 
                   4149:         }
1.21      www      4150:         $mrole='cr';
1.678     raeburn  4151:     } elsif ($role =~ /^gr\//) {
                   4152:         my $cwogrp=$url;
                   4153:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4154:         unless (&allowed('mdg',$cwogrp)) {
                   4155:             &logthis('Refused group assignrole: '.
                   4156:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4157:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4158:             return 'refused';
                   4159:         }
                   4160:         $mrole='gr';
1.21      www      4161:     } else {
1.82      www      4162:         my $cwosec=$url;
1.83      www      4163:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4164:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4165:            &logthis('Refused assignrole: '.
                   4166:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4167: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4168:            return 'refused'; 
                   4169:         }
1.21      www      4170:         $mrole=$role;
                   4171:     }
1.620     albertel 4172:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4173:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4174:     if ($end) { $command.='_'.$end; }
1.21      www      4175:     if ($start) {
                   4176: 	if ($end) { 
1.81      www      4177:            $command.='_'.$start; 
1.21      www      4178:         } else {
1.81      www      4179:            $command.='_0_'.$start;
1.21      www      4180:         }
                   4181:     }
1.739     raeburn  4182:     my $origstart = $start;
                   4183:     my $origend = $end;
1.357     www      4184: # actually delete
                   4185:     if ($deleteflag) {
1.373     www      4186: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4187: # modify command to delete the role
1.620     albertel 4188:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4189:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4190: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4191: # set start and finish to negative values for userrolelog
                   4192:            $start=-1;
                   4193:            $end=-1;
                   4194:         }
                   4195:     }
                   4196: # send command
1.349     www      4197:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4198: # log new user role if status is ok
1.349     www      4199:     if ($answer eq 'ok') {
1.663     raeburn  4200: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4201: # for course roles, perform group memberships changes triggered by role change.
                   4202:         unless ($role =~ /^gr/) {
                   4203:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4204:                                              $origstart);
                   4205:         }
1.349     www      4206:     }
                   4207:     return $answer;
1.169     harris41 4208: }
                   4209: 
                   4210: # -------------------------------------------------- Modify user authentication
1.197     www      4211: # Overrides without validation
                   4212: 
1.169     harris41 4213: sub modifyuserauth {
                   4214:     my ($udom,$uname,$umode,$upass)=@_;
                   4215:     my $uhome=&homeserver($uname,$udom);
1.197     www      4216:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4217:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4218:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4219:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4220:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4221: 		     &escape($upass),$uhome);
1.620     albertel 4222:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4223:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4224:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4225:     &log($udom,,$uname,$uhome,
1.620     albertel 4226:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4227:                                      $env{'user.name'}.', '.$umode.
1.197     www      4228:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4229:     unless ($reply eq 'ok') {
1.197     www      4230:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4231: 	return 'error: '.$reply;
                   4232:     }   
1.170     harris41 4233:     return 'ok';
1.80      www      4234: }
                   4235: 
1.81      www      4236: # --------------------------------------------------------------- Modify a user
1.80      www      4237: 
1.81      www      4238: sub modifyuser {
1.206     matthew  4239:     my ($udom,    $uname, $uid,
                   4240:         $umode,   $upass, $first,
                   4241:         $middle,  $last,  $gene,
1.387     www      4242:         $forceid, $desiredhome, $email)=@_;
1.198     www      4243:     $udom=~s/\W//g;
                   4244:     $uname=~s/\W//g;
1.81      www      4245:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4246:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4247: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4248:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4249:                                      ' desiredhome not specified'). 
1.620     albertel 4250:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4251:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4252:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4253: # ----------------------------------------------------------------- Create User
1.406     albertel 4254:     if (($uhome eq 'no_host') && 
                   4255: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4256:         my $unhome='';
1.209     matthew  4257:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4258:             $unhome = $desiredhome;
1.620     albertel 4259: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4260: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4261:         } else { # load balancing routine for determining $unhome
1.80      www      4262:             my $tryserver;
1.81      www      4263:             my $loadm=10000000;
1.80      www      4264:             foreach $tryserver (keys %libserv) {
                   4265: 	       if ($hostdom{$tryserver} eq $udom) {
                   4266:                   my $answer=reply('load',$tryserver);
                   4267:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4268: 		      $loadm=$answer;
                   4269:                       $unhome=$tryserver;
                   4270:                   }
                   4271: 	       }
                   4272: 	    }
                   4273:         }
                   4274:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4275: 	    return 'error: unable to find a home server for '.$uname.
                   4276:                    ' in domain '.$udom;
1.80      www      4277:         }
                   4278:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4279:                          &escape($upass),$unhome);
                   4280: 	unless ($reply eq 'ok') {
                   4281:             return 'error: '.$reply;
                   4282:         }   
1.230     stredwic 4283:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4284:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4285: 	    return 'error: unable verify users home machine.';
1.80      www      4286:         }
1.209     matthew  4287:     }   # End of creation of new user
1.80      www      4288: # ---------------------------------------------------------------------- Add ID
                   4289:     if ($uid) {
                   4290:        $uid=~tr/A-Z/a-z/;
                   4291:        my %uidhash=&idrget($udom,$uname);
1.196     www      4292:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4293:          && (!$forceid)) {
1.80      www      4294: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4295: 	      return 'error: user id "'.$uid.'" does not match '.
                   4296:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4297:           }
                   4298:        } else {
                   4299: 	  &idput($udom,($uname => $uid));
                   4300:        }
                   4301:     }
                   4302: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4303:     my @tmp=&get('environment',
1.134     albertel 4304: 		   ['firstname','middlename','lastname','generation'],
                   4305: 		   $udom,$uname);
1.313     matthew  4306:     my %names;
                   4307:     if ($tmp[0] =~ m/^error:.*/) { 
                   4308:         %names=(); 
                   4309:     } else {
                   4310:         %names = @tmp;
                   4311:     }
1.388     www      4312: #
                   4313: # Make sure to not trash student environment if instructor does not bother
                   4314: # to supply name and email information
                   4315: #
                   4316:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4317:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4318:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4319:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4320:     if ($email) {
                   4321:        $email=~s/[^\w\@\.\-\,]//gs;
                   4322:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4323: 			   $names{'critnotification'} = $email;
                   4324: 			   $names{'permanentemail'} = $email; }
                   4325:     }
1.134     albertel 4326:     my $reply = &put('environment', \%names, $udom,$uname);
                   4327:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4328:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4329:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4330:              $umode.', '.$first.', '.$middle.', '.
                   4331: 	     $last.', '.$gene.' by '.
1.620     albertel 4332:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4333:     return 'ok';
1.80      www      4334: }
                   4335: 
1.81      www      4336: # -------------------------------------------------------------- Modify student
1.80      www      4337: 
1.81      www      4338: sub modifystudent {
                   4339:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4340:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4341:     if (!$cid) {
1.620     albertel 4342: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4343: 	    return 'not_in_class';
                   4344: 	}
1.80      www      4345:     }
                   4346: # --------------------------------------------------------------- Make the user
1.81      www      4347:     my $reply=&modifyuser
1.209     matthew  4348: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4349:          $desiredhome,$email);
1.80      www      4350:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4351:     # This will cause &modify_student_enrollment to get the uid from the
                   4352:     # students environment
                   4353:     $uid = undef if (!$forceid);
1.455     albertel 4354:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4355: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4356:     return $reply;
                   4357: }
                   4358: 
                   4359: sub modify_student_enrollment {
1.515     raeburn  4360:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4361:     my ($cdom,$cnum,$chome);
                   4362:     if (!$cid) {
1.620     albertel 4363: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4364: 	    return 'not_in_class';
                   4365: 	}
1.620     albertel 4366: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4367: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4368:     } else {
                   4369: 	($cdom,$cnum)=split(/_/,$cid);
                   4370:     }
1.620     albertel 4371:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4372:     if (!$chome) {
1.457     raeburn  4373: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4374:     }
1.455     albertel 4375:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4376:     # Make sure the user exists
1.81      www      4377:     my $uhome=&homeserver($uname,$udom);
                   4378:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4379: 	return 'error: no such user';
                   4380:     }
1.297     matthew  4381:     # Get student data if we were not given enough information
                   4382:     if (!defined($first)  || $first  eq '' || 
                   4383:         !defined($last)   || $last   eq '' || 
                   4384:         !defined($uid)    || $uid    eq '' || 
                   4385:         !defined($middle) || $middle eq '' || 
                   4386:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4387:         # They did not supply us with enough data to enroll the student, so
                   4388:         # we need to pick up more information.
1.297     matthew  4389:         my %tmp = &get('environment',
1.294     matthew  4390:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4391:                        ,$udom,$uname);
                   4392: 
1.455     albertel 4393:         #foreach (keys(%tmp)) {
                   4394:         #    &logthis("key $_ = ".$tmp{$_});
                   4395:         #}
1.294     matthew  4396:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4397:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4398:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4399:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4400:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4401:     }
1.556     albertel 4402:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4403:     my $reply=cput('classlist',
                   4404: 		   {"$uname:$udom" => 
1.515     raeburn  4405: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4406: 		   $cdom,$cnum);
1.81      www      4407:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4408: 	return 'error: '.$reply;
1.652     albertel 4409:     } else {
                   4410: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4411:     }
1.297     matthew  4412:     # Add student role to user
1.83      www      4413:     my $uurl='/'.$cid;
1.81      www      4414:     $uurl=~s/\_/\//g;
                   4415:     if ($usec) {
                   4416: 	$uurl.='/'.$usec;
                   4417:     }
                   4418:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4419: }
                   4420: 
1.556     albertel 4421: sub format_name {
                   4422:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4423:     my $name;
                   4424:     if ($first ne 'lastname') {
                   4425: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4426:     } else {
                   4427: 	if ($lastname=~/\S/) {
                   4428: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4429: 	    $name=~s/\s+,/,/;
                   4430: 	} else {
                   4431: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4432: 	}
                   4433:     }
                   4434:     $name=~s/^\s+//;
                   4435:     $name=~s/\s+$//;
                   4436:     $name=~s/\s+/ /g;
                   4437:     return $name;
                   4438: }
                   4439: 
1.84      www      4440: # ------------------------------------------------- Write to course preferences
                   4441: 
                   4442: sub writecoursepref {
                   4443:     my ($courseid,%prefs)=@_;
                   4444:     $courseid=~s/^\///;
                   4445:     $courseid=~s/\_/\//g;
                   4446:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4447:     my $chome=homeserver($cnum,$cdomain);
                   4448:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4449: 	return 'error: no such course';
                   4450:     }
                   4451:     my $cstring='';
1.191     harris41 4452:     foreach (keys %prefs) {
1.84      www      4453: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4454:     }
1.84      www      4455:     $cstring=~s/\&$//;
                   4456:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4457: }
                   4458: 
                   4459: # ---------------------------------------------------------- Make/modify course
                   4460: 
                   4461: sub createcourse {
1.741     raeburn  4462:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4463:         $course_owner,$crstype)=@_;
1.84      www      4464:     $url=&declutter($url);
                   4465:     my $cid='';
1.264     matthew  4466:     unless (&allowed('ccc',$udom)) {
1.84      www      4467:         return 'refused';
                   4468:     }
                   4469: # ------------------------------------------------------------------- Create ID
1.674     www      4470:    my $uname=int(1+rand(9)).
                   4471:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4472:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4473:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4474: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4475:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4476:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4477:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4478:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4479:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4480:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4481:            return 'error: unable to generate unique course-ID';
                   4482:        } 
                   4483:    }
1.264     matthew  4484: # ------------------------------------------------ Check supplied server name
1.620     albertel 4485:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4486:     if (! exists($libserv{$course_server})) {
                   4487:         return 'error:bad server name '.$course_server;
                   4488:     }
1.84      www      4489: # ------------------------------------------------------------- Make the course
                   4490:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4491:                       $course_server);
1.84      www      4492:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4493:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4494:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4495: 	return 'error: no such course';
                   4496:     }
1.271     www      4497: # ----------------------------------------------------------------- Course made
1.516     raeburn  4498: # log existence
                   4499:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4500:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4501:                   &escape($crstype),$uhome);
1.358     www      4502:     &flushcourselogs();
                   4503: # set toplevel url
1.271     www      4504:     my $topurl=$url;
                   4505:     unless ($nonstandard) {
                   4506: # ------------------------------------------ For standard courses, make top url
                   4507:         my $mapurl=&clutter($url);
1.278     www      4508:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4509:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4510: <map>
                   4511: <resource id="1" type="start"></resource>
                   4512: <resource id="2" src="$mapurl"></resource>
                   4513: <resource id="3" type="finish"></resource>
                   4514: <link index="1" from="1" to="2"></link>
                   4515: <link index="2" from="2" to="3"></link>
                   4516: </map>
                   4517: ENDINITMAP
                   4518:         $topurl=&declutter(
1.638     albertel 4519:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4520:                           );
                   4521:     }
                   4522: # ----------------------------------------------------------- Write preferences
1.84      www      4523:     &writecoursepref($udom.'_'.$uname,
                   4524:                      ('description' => $description,
1.271     www      4525:                       'url'         => $topurl));
1.84      www      4526:     return '/'.$udom.'/'.$uname;
                   4527: }
                   4528: 
1.21      www      4529: # ---------------------------------------------------------- Assign Custom Role
                   4530: 
                   4531: sub assigncustomrole {
1.357     www      4532:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4533:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4534:                        $end,$start,$deleteflag);
1.21      www      4535: }
                   4536: 
                   4537: # ----------------------------------------------------------------- Revoke Role
                   4538: 
                   4539: sub revokerole {
1.357     www      4540:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4541:     my $now=time;
1.357     www      4542:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4543: }
                   4544: 
                   4545: # ---------------------------------------------------------- Revoke Custom Role
                   4546: 
                   4547: sub revokecustomrole {
1.357     www      4548:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4549:     my $now=time;
1.357     www      4550:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4551:            $deleteflag);
1.17      www      4552: }
                   4553: 
1.533     banghart 4554: # ------------------------------------------------------------ Disk usage
1.535     albertel 4555: sub diskusage {
1.533     banghart 4556:     my ($udom,$uname,$directoryRoot)=@_;
                   4557:     $directoryRoot =~ s/\/$//;
1.535     albertel 4558:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4559:     return $listing;
1.512     banghart 4560: }
                   4561: 
1.566     banghart 4562: sub is_locked {
                   4563:     my ($file_name, $domain, $user) = @_;
                   4564:     my @check;
                   4565:     my $is_locked;
                   4566:     push @check, $file_name;
1.613     albertel 4567:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4568: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4569:     my ($tmp)=keys(%locked);
                   4570:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4571:     
1.566     banghart 4572:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4573:         $is_locked = 'false';
                   4574:         foreach my $entry (@{$locked{$file_name}}) {
                   4575:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4576:                $is_locked = 'true';
                   4577:                last;
1.745     raeburn  4578:            }
                   4579:        }
1.566     banghart 4580:     } else {
                   4581:         $is_locked = 'false';
                   4582:     }
                   4583: }
                   4584: 
1.559     banghart 4585: # ------------------------------------------------------------- Mark as Read Only
                   4586: 
                   4587: sub mark_as_readonly {
                   4588:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4589:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4590:     my ($tmp)=keys(%current_permissions);
                   4591:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4592:     foreach my $file (@{$files}) {
1.561     banghart 4593:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4594:     }
1.613     albertel 4595:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4596:     return;
                   4597: }
                   4598: 
1.572     banghart 4599: # ------------------------------------------------------------Save Selected Files
                   4600: 
                   4601: sub save_selected_files {
                   4602:     my ($user, $path, @files) = @_;
                   4603:     my $filename = $user."savedfiles";
1.573     banghart 4604:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4605:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4606:     foreach my $file (@files) {
1.620     albertel 4607:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4608:     }
                   4609:     foreach my $file (@other_files) {
1.574     banghart 4610:         print (OUT $file."\n");
1.572     banghart 4611:     }
1.574     banghart 4612:     close (OUT);
1.572     banghart 4613:     return 'ok';
                   4614: }
                   4615: 
1.574     banghart 4616: sub clear_selected_files {
                   4617:     my ($user) = @_;
                   4618:     my $filename = $user."savedfiles";
                   4619:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4620:     print (OUT undef);
                   4621:     close (OUT);
                   4622:     return ("ok");    
                   4623: }
                   4624: 
1.572     banghart 4625: sub files_in_path {
                   4626:     my ($user, $path) = @_;
                   4627:     my $filename = $user."savedfiles";
                   4628:     my %return_files;
1.574     banghart 4629:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4630:     while (my $line_in = <IN>) {
1.574     banghart 4631:         chomp ($line_in);
                   4632:         my @paths_and_file = split (m!/!, $line_in);
                   4633:         my $file_part = pop (@paths_and_file);
                   4634:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4635:         $path_part.='/';
                   4636:         my $path_and_file = $path_part.$file_part;
                   4637:         if ($path_part eq $path) {
                   4638:             $return_files{$file_part}= 'selected';
                   4639:         }
                   4640:     }
1.574     banghart 4641:     close (IN);
                   4642:     return (\%return_files);
1.572     banghart 4643: }
                   4644: 
                   4645: # called in portfolio select mode, to show files selected NOT in current directory
                   4646: sub files_not_in_path {
                   4647:     my ($user, $path) = @_;
                   4648:     my $filename = $user."savedfiles";
                   4649:     my @return_files;
                   4650:     my $path_part;
1.574     banghart 4651:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4652:     while (<IN>) {
                   4653:         #ok, I know it's clunky, but I want it to work
                   4654:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4655:         my $file_part = pop (@paths_and_file);
                   4656:         chomp ($file_part);
                   4657:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4658:         $path_part .= '/';
                   4659:         my $path_and_file = $path_part.$file_part;
                   4660:         if ($path_part ne $path) {
1.574     banghart 4661:             push (@return_files, ($path_and_file));
1.572     banghart 4662:         }
                   4663:     }
1.574     banghart 4664:     close (OUT);
                   4665:     return (@return_files);
1.572     banghart 4666: }
                   4667: 
1.745     raeburn  4668: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4669: 
1.745     raeburn  4670: sub get_portfile_permissions {
                   4671:     my ($domain,$user) = @_;
1.613     albertel 4672:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4673:     my ($tmp)=keys(%current_permissions);
                   4674:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4675:     return \%current_permissions;
                   4676: }
                   4677: 
                   4678: #---------------------------------------------Get portfolio file access controls
                   4679: 
1.749     raeburn  4680: sub get_access_controls {
1.745     raeburn  4681:     my ($current_permissions,$group,$file) = @_;
                   4682:     my %access; 
                   4683:     if (defined($file)) {
1.749     raeburn  4684:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4685:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
                   4686:                 $access{$file}{$control} = $$current_permissions{$file."\0".$control};
                   4687:             }
                   4688:         }
1.745     raeburn  4689:     } else {
1.749     raeburn  4690:         foreach my $key (keys(%{$current_permissions})) {
                   4691:             if ($key =~ /\0accesscontrol$/) {
                   4692:                 if (defined($group)) {
                   4693:                     if ($key !~ m-^\Q$group\E/-) {
                   4694:                         next;
                   4695:                     }
                   4696:                 }
                   4697:                 my ($fullpath) = split(/\0/,$key);
                   4698:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4699:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4700:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4701:                     }
                   4702:                 }
                   4703:             }
                   4704:         }
                   4705:     }
                   4706:     return %access;
                   4707: }
                   4708: 
                   4709: sub modify_access_controls {
                   4710:     my ($file_name,$changes,$domain,$user)=@_;
                   4711:     my ($outcome,$deloutcome);
                   4712:     my %store_permissions;
                   4713:     my %new_values;
                   4714:     my %new_control;
                   4715:     my %translation;
                   4716:     my @deletions = ();
                   4717:     my $now = time;
                   4718:     if (exists($$changes{'activate'})) {
                   4719:         if (ref($$changes{'activate'}) eq 'HASH') {
                   4720:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   4721:             my $numnew = scalar(@newitems);
                   4722:             for (my $i=0; $i<$numnew; $i++) {
                   4723:                 my $newkey = $newitems[$i];
                   4724:                 my $newid = &Apache::loncommon::get_cgi_id();
                   4725:                 $newkey =~ s/^(\d+)/$newid/;
                   4726:                 $translation{$1} = $newid;
                   4727:                 $new_values{$file_name."\0".$newkey} = 
                   4728:                                           $$changes{'activate'}{$newitems[$i]};
                   4729:                 $new_control{$newkey} = $now;
                   4730:             }
                   4731:         }
                   4732:     }
                   4733:     my %todelete;
                   4734:     my %changed_items;
                   4735:     foreach my $action ('delete','update') {
                   4736:         if (exists($$changes{$action})) {
                   4737:             if (ref($$changes{$action}) eq 'HASH') {
                   4738:                 foreach my $key (keys(%{$$changes{$action}})) {
                   4739:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   4740:                     if ($action eq 'delete') { 
                   4741:                         $todelete{$itemnum} = 1;
                   4742:                     } else {
                   4743:                         $changed_items{$itemnum} = $key;
                   4744:                     }
                   4745:                 }
1.745     raeburn  4746:             }
                   4747:         }
1.749     raeburn  4748:     }
                   4749:     # get lock on access controls for file.
                   4750:     my $lockhash = {
                   4751:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   4752:                                                        ':'.$env{'user.domain'},
                   4753:                    }; 
                   4754:     my $tries = 0;
                   4755:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   4756:    
                   4757:     while (($gotlock ne 'ok') && $tries <3) {
                   4758:         $tries ++;
                   4759:         sleep 1;
                   4760:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   4761:     }
                   4762:     if ($gotlock eq 'ok') {
                   4763:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   4764:         my ($tmp)=keys(%curr_permissions);
                   4765:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   4766:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   4767:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   4768:             if (ref($curr_controls) eq 'HASH') {
                   4769:                 foreach my $control_item (keys(%{$curr_controls})) {
                   4770:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   4771:                     if (defined($todelete{$itemnum})) {
                   4772:                         push(@deletions,$file_name."\0".$control_item);
                   4773:                     } else {
                   4774:                         if (defined($changed_items{$itemnum})) {
                   4775:                             $new_control{$changed_items{$itemnum}} = $now;
                   4776:                             push(@deletions,$file_name."\0".$control_item);
                   4777:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   4778:                         } else {
                   4779:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   4780:                         }
                   4781:                     }
1.745     raeburn  4782:                 }
                   4783:             }
                   4784:         }
1.749     raeburn  4785:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   4786:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   4787:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   4788:         #  remove lock
                   4789:         my @del_lock = ($file_name."\0".'locked_access_records');
                   4790:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   4791:     } else {
                   4792:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  4793:     }
1.749     raeburn  4794:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  4795: }
                   4796: 
                   4797: #------------------------------------------------------Get Marked as Read Only
                   4798: 
                   4799: sub get_marked_as_readonly {
                   4800:     my ($domain,$user,$what,$group) = @_;
                   4801:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 4802:     my @readonly_files;
1.629     banghart 4803:     my $cmp1=$what;
                   4804:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  4805:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   4806:         if (defined($group)) {
                   4807:             if ($file_name !~ m-^\Q$group\E/-) {
                   4808:                 next;
                   4809:             }
                   4810:         }
1.561     banghart 4811:         if (ref($value) eq "ARRAY"){
                   4812:             foreach my $stored_what (@{$value}) {
1.629     banghart 4813:                 my $cmp2=$stored_what;
1.749     raeburn  4814:                 if (ref($stored_what eq 'ARRAY')) {
1.746     raeburn  4815:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  4816:                 }
1.629     banghart 4817:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4818:                     push(@readonly_files, $file_name);
1.745     raeburn  4819:                     last;
1.563     banghart 4820:                 } elsif (!defined($what)) {
                   4821:                     push(@readonly_files, $file_name);
1.745     raeburn  4822:                     last;
1.561     banghart 4823:                 }
                   4824:             }
1.745     raeburn  4825:         }
1.561     banghart 4826:     }
                   4827:     return @readonly_files;
                   4828: }
1.577     banghart 4829: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4830: 
1.577     banghart 4831: sub get_marked_as_readonly_hash {
1.745     raeburn  4832:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 4833:     my %readonly_files;
1.745     raeburn  4834:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   4835:         if (defined($group)) {
                   4836:             if ($file_name !~ m-^\Q$group\E/-) {
                   4837:                 next;
                   4838:             }
                   4839:         }
1.577     banghart 4840:         if (ref($value) eq "ARRAY"){
                   4841:             foreach my $stored_what (@{$value}) {
1.745     raeburn  4842:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 4843:                     foreach my $lock_descriptor(@{$stored_what}) {
                   4844:                         if ($lock_descriptor eq 'graded') {
                   4845:                             $readonly_files{$file_name} = 'graded';
                   4846:                         } elsif ($lock_descriptor eq 'handback') {
                   4847:                             $readonly_files{$file_name} = 'handback';
                   4848:                         } else {
                   4849:                             if (!exists($readonly_files{$file_name})) {
                   4850:                                 $readonly_files{$file_name} = 'locked';
                   4851:                             }
                   4852:                         }
1.745     raeburn  4853:                     }
1.750     banghart 4854:                 } 
1.577     banghart 4855:             }
                   4856:         } 
                   4857:     }
                   4858:     return %readonly_files;
                   4859: }
1.559     banghart 4860: # ------------------------------------------------------------ Unmark as Read Only
                   4861: 
                   4862: sub unmark_as_readonly {
1.629     banghart 4863:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4864:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  4865:     my ($domain,$user,$what,$file_name,$group) = @_;
1.634     albertel 4866:     my $symb_crs = $what;
                   4867:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  4868:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 4869:     my ($tmp)=keys(%current_permissions);
                   4870:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4871:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 4872:     foreach my $file (@readonly_files) {
                   4873: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4874: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4875:         my @new_locks;
                   4876:         my @del_keys;
                   4877:         if (ref($current_locks) eq "ARRAY"){
                   4878:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4879:                 my $compare=$locker;
1.749     raeburn  4880:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  4881:                     $compare=join('',@{$locker});
1.746     raeburn  4882:                     if ($compare ne $symb_crs) {
                   4883:                         push(@new_locks, $locker);
                   4884:                     }
1.563     banghart 4885:                 }
                   4886:             }
1.650     albertel 4887:             if (scalar(@new_locks) > 0) {
1.563     banghart 4888:                 $current_permissions{$file} = \@new_locks;
                   4889:             } else {
                   4890:                 push(@del_keys, $file);
1.613     albertel 4891:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4892:                 delete($current_permissions{$file});
1.563     banghart 4893:             }
                   4894:         }
1.561     banghart 4895:     }
1.613     albertel 4896:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4897:     return;
                   4898: }
1.512     banghart 4899: 
1.17      www      4900: # ------------------------------------------------------------ Directory lister
                   4901: 
                   4902: sub dirlist {
1.253     stredwic 4903:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4904: 
1.18      www      4905:     $uri=~s/^\///;
                   4906:     $uri=~s/\/$//;
1.253     stredwic 4907:     my ($udom, $uname);
                   4908:     (undef,$udom,$uname)=split(/\//,$uri);
                   4909:     if(defined($userdomain)) {
                   4910:         $udom = $userdomain;
                   4911:     }
                   4912:     if(defined($username)) {
                   4913:         $uname = $username;
                   4914:     }
                   4915: 
                   4916:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4917:     if(defined($alternateDirectoryRoot)) {
                   4918:         $dirRoot = $alternateDirectoryRoot;
                   4919:         $dirRoot =~ s/\/$//;
1.751     banghart 4920:     }
1.253     stredwic 4921: 
                   4922:     if($udom) {
                   4923:         if($uname) {
1.605     matthew  4924:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4925:                               homeserver($uname,$udom));
1.605     matthew  4926:             my @listing_results;
                   4927:             if ($listing eq 'unknown_cmd') {
                   4928:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4929:                                homeserver($uname,$udom));
                   4930:                 @listing_results = split(/:/,$listing);
                   4931:             } else {
                   4932:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4933:             }
                   4934:             return @listing_results;
1.253     stredwic 4935:         } elsif(!defined($alternateDirectoryRoot)) {
                   4936:             my $tryserver;
                   4937:             my %allusers=();
                   4938:             foreach $tryserver (keys %libserv) {
                   4939:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4940:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4941:                                       $udom, $tryserver);
1.605     matthew  4942:                     my @listing_results;
                   4943:                     if ($listing eq 'unknown_cmd') {
                   4944:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4945:                                        $udom, $tryserver);
                   4946:                         @listing_results = split(/:/,$listing);
                   4947:                     } else {
                   4948:                         @listing_results =
                   4949:                             map { &unescape($_); } split(/:/,$listing);
                   4950:                     }
                   4951:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4952:                         $listing_results[0] ne 'empty'       &&
                   4953:                         $listing_results[0] ne 'con_lost') {
                   4954:                         foreach (@listing_results) {
1.253     stredwic 4955:                             my ($entry,@stat)=split(/&/,$_);
                   4956:                             $allusers{$entry}=1;
                   4957:                         }
                   4958:                     }
1.191     harris41 4959:                 }
1.253     stredwic 4960:             }
                   4961:             my $alluserstr='';
                   4962:             foreach (sort keys %allusers) {
                   4963:                 $alluserstr.=$_.'&user:';
                   4964:             }
                   4965:             $alluserstr=~s/:$//;
                   4966:             return split(/:/,$alluserstr);
                   4967:         } else {
                   4968:             my @emptyResults = ();
                   4969:             push(@emptyResults, 'missing user name');
                   4970:             return split(':',@emptyResults);
                   4971:         }
                   4972:     } elsif(!defined($alternateDirectoryRoot)) {
                   4973:         my $tryserver;
                   4974:         my %alldom=();
                   4975:         foreach $tryserver (keys %libserv) {
                   4976:             $alldom{$hostdom{$tryserver}}=1;
                   4977:         }
                   4978:         my $alldomstr='';
                   4979:         foreach (sort keys %alldom) {
1.397     albertel 4980:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4981:         }
                   4982:         $alldomstr=~s/:$//;
                   4983:         return split(/:/,$alldomstr);       
                   4984:     } else {
                   4985:         my @emptyResults = ();
                   4986:         push(@emptyResults, 'missing domain');
                   4987:         return split(':',@emptyResults);
1.275     stredwic 4988:     }
                   4989: }
                   4990: 
                   4991: # --------------------------------------------- GetFileTimestamp
                   4992: # This function utilizes dirlist and returns the date stamp for
                   4993: # when it was last modified.  It will also return an error of -1
                   4994: # if an error occurs
                   4995: 
1.410     matthew  4996: ##
                   4997: ## FIXME: This subroutine assumes its caller knows something about the
                   4998: ## directory structure of the home server for the student ($root).
                   4999: ## Not a good assumption to make.  Since this is for looking up files
                   5000: ## in user directories, the full path should be constructed by lond, not
                   5001: ## whatever machine we request data from.
                   5002: ##
1.275     stredwic 5003: sub GetFileTimestamp {
                   5004:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5005:     $studentDomain=~s/\W//g;
                   5006:     $studentName=~s/\W//g;
                   5007:     my $subdir=$studentName.'__';
                   5008:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5009:     my $proname="$studentDomain/$subdir/$studentName";
                   5010:     $proname .= '/'.$filename;
1.375     matthew  5011:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5012:                                               $studentName, $root);
1.275     stredwic 5013:     my @stats = split('&', $fileStat);
                   5014:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5015:         # @stats contains first the filename, then the stat output
                   5016:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5017:     } else {
                   5018:         return -1;
1.253     stredwic 5019:     }
1.26      www      5020: }
                   5021: 
1.712     albertel 5022: sub stat_file {
                   5023:     my ($uri) = @_;
1.722     albertel 5024:     $uri = &clutter($uri);
                   5025: 
                   5026:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 5027:     if ($uri =~ m-^/adm/-) {
                   5028: 	$uri=~s-^/adm/wrapper/-/-;
                   5029: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 5030:     }
1.712     albertel 5031:     my ($udom,$uname,$file,$dir);
                   5032:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5033: 	($udom,$uname,$file) =
                   5034: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5035: 	$file = 'userfiles/'.$file;
1.740     www      5036: 	$dir = &propath($udom,$uname);
1.712     albertel 5037:     }
                   5038:     if ($uri =~ m-^/res/-) {
                   5039: 	($udom,$uname) = 
                   5040: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5041: 	$file = $uri;
                   5042:     }
                   5043: 
                   5044:     if (!$udom || !$uname || !$file) {
                   5045: 	# unable to handle the uri
                   5046: 	return ();
                   5047:     }
                   5048: 
                   5049:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5050:     my @stats = split('&', $result);
1.721     banghart 5051:     
1.712     albertel 5052:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5053: 	shift(@stats); #filename is first
                   5054: 	return @stats;
                   5055:     }
                   5056:     return ();
                   5057: }
                   5058: 
1.26      www      5059: # -------------------------------------------------------- Value of a Condition
                   5060: 
1.713     albertel 5061: # gets the value of a specific preevaluated condition
                   5062: #    stored in the string  $env{user.state.<cid>}
                   5063: # or looks up a condition reference in the bighash and if if hasn't
                   5064: # already been evaluated recurses into docondval to get the value of
                   5065: # the condition, then memoizing it to 
                   5066: #   $env{user.state.<cid>.<condition>}
1.40      www      5067: sub directcondval {
                   5068:     my $number=shift;
1.620     albertel 5069:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5070: 	&Apache::lonuserstate::evalstate();
                   5071:     }
1.713     albertel 5072:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5073: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5074:     } elsif ($number =~ /^_/) {
                   5075: 	my $sub_condition;
                   5076: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5077: 		&GDBM_READER(),0640)) {
                   5078: 	    $sub_condition=$bighash{'conditions'.$number};
                   5079: 	    untie(%bighash);
                   5080: 	}
                   5081: 	my $value = &docondval($sub_condition);
                   5082: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5083: 	return $value;
                   5084:     }
1.620     albertel 5085:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5086:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5087:     } else {
                   5088:        return 2;
                   5089:     }
                   5090: }
                   5091: 
1.713     albertel 5092: # get the collection of conditions for this resource
1.26      www      5093: sub condval {
                   5094:     my $condidx=shift;
1.54      www      5095:     my $allpathcond='';
1.713     albertel 5096:     foreach my $cond (split(/\|/,$condidx)) {
                   5097: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5098: 	    $allpathcond.=
                   5099: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5100: 	}
1.191     harris41 5101:     }
1.54      www      5102:     $allpathcond=~s/\|$//;
1.713     albertel 5103:     return &docondval($allpathcond);
                   5104: }
                   5105: 
                   5106: #evaluates an expression of conditions
                   5107: sub docondval {
                   5108:     my ($allpathcond) = @_;
                   5109:     my $result=0;
                   5110:     if ($env{'request.course.id'}
                   5111: 	&& defined($allpathcond)) {
                   5112: 	my $operand='|';
                   5113: 	my @stack;
                   5114: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5115: 	    if ($chunk eq '(') {
                   5116: 		push @stack,($operand,$result);
                   5117: 	    } elsif ($chunk eq ')') {
                   5118: 		my $before=pop @stack;
                   5119: 		if (pop @stack eq '&') {
                   5120: 		    $result=$result>$before?$before:$result;
                   5121: 		} else {
                   5122: 		    $result=$result>$before?$result:$before;
                   5123: 		}
                   5124: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5125: 		$operand=$chunk;
                   5126: 	    } else {
                   5127: 		my $new=directcondval($chunk);
                   5128: 		if ($operand eq '&') {
                   5129: 		    $result=$result>$new?$new:$result;
                   5130: 		} else {
                   5131: 		    $result=$result>$new?$result:$new;
                   5132: 		}
                   5133: 	    }
                   5134: 	}
1.26      www      5135:     }
                   5136:     return $result;
1.421     albertel 5137: }
                   5138: 
                   5139: # ---------------------------------------------------- Devalidate courseresdata
                   5140: 
                   5141: sub devalidatecourseresdata {
                   5142:     my ($coursenum,$coursedomain)=@_;
                   5143:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5144:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5145: }
                   5146: 
1.200     www      5147: # --------------------------------------------------- Course Resourcedata Query
                   5148: 
1.624     albertel 5149: sub get_courseresdata {
                   5150:     my ($coursenum,$coursedomain)=@_;
1.200     www      5151:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5152:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5153:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5154:     my %dumpreply;
1.417     albertel 5155:     unless (defined($cached)) {
1.624     albertel 5156: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5157: 	$result=\%dumpreply;
1.251     albertel 5158: 	my ($tmp) = keys(%dumpreply);
                   5159: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5160: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5161: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5162: 	    return $tmp;
1.416     albertel 5163: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5164: 	    $result=undef;
1.599     albertel 5165: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5166: 	}
                   5167:     }
1.624     albertel 5168:     return $result;
                   5169: }
                   5170: 
1.633     albertel 5171: sub devalidateuserresdata {
                   5172:     my ($uname,$udom)=@_;
                   5173:     my $hashid="$udom:$uname";
                   5174:     &devalidate_cache_new('userres',$hashid);
                   5175: }
                   5176: 
1.624     albertel 5177: sub get_userresdata {
                   5178:     my ($uname,$udom)=@_;
                   5179:     #most student don\'t have any data set, check if there is some data
                   5180:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5181: 
                   5182:     my $hashid="$udom:$uname";
                   5183:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5184:     if (!defined($cached)) {
                   5185: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5186: 	$result=\%resourcedata;
                   5187: 	&do_cache_new('userres',$hashid,$result,600);
                   5188:     }
                   5189:     my ($tmp)=keys(%$result);
                   5190:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5191: 	return $result;
                   5192:     }
                   5193:     #error 2 occurs when the .db doesn't exist
                   5194:     if ($tmp!~/error: 2 /) {
1.672     albertel 5195: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5196: 		 " Trying to get resource data for ".
                   5197: 		 $uname." at ".$udom.": ".
                   5198: 		 $tmp."</font>");
                   5199:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5200: 	#&EXT_cache_set($udom,$uname);
                   5201: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5202: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5203:     }
                   5204:     return $tmp;
                   5205: }
                   5206: 
                   5207: sub resdata {
                   5208:     my ($name,$domain,$type,@which)=@_;
                   5209:     my $result;
                   5210:     if ($type eq 'course') {
                   5211: 	$result=&get_courseresdata($name,$domain);
                   5212:     } elsif ($type eq 'user') {
                   5213: 	$result=&get_userresdata($name,$domain);
                   5214:     }
                   5215:     if (!ref($result)) { return $result; }    
1.251     albertel 5216:     foreach my $item (@which) {
1.417     albertel 5217: 	if (defined($result->{$item})) {
                   5218: 	    return $result->{$item};
1.251     albertel 5219: 	}
1.250     albertel 5220:     }
1.291     albertel 5221:     return undef;
1.200     www      5222: }
                   5223: 
1.379     matthew  5224: #
                   5225: # EXT resource caching routines
                   5226: #
                   5227: 
                   5228: sub clear_EXT_cache_status {
1.383     albertel 5229:     &delenv('cache.EXT.');
1.379     matthew  5230: }
                   5231: 
                   5232: sub EXT_cache_status {
                   5233:     my ($target_domain,$target_user) = @_;
1.383     albertel 5234:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5235:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5236:         # We know already the user has no data
                   5237:         return 1;
                   5238:     } else {
                   5239:         return 0;
                   5240:     }
                   5241: }
                   5242: 
                   5243: sub EXT_cache_set {
                   5244:     my ($target_domain,$target_user) = @_;
1.383     albertel 5245:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5246:     #&appenv($cachename => time);
1.379     matthew  5247: }
                   5248: 
1.28      www      5249: # --------------------------------------------------------- Value of a Variable
1.58      www      5250: sub EXT {
1.715     albertel 5251: 
1.395     albertel 5252:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5253:     unless ($varname) { return ''; }
1.218     albertel 5254:     #get real user name/domain, courseid and symb
                   5255:     my $courseid;
1.359     albertel 5256:     my $publicuser;
1.427     www      5257:     if ($symbparm) {
                   5258: 	$symbparm=&get_symb_from_alias($symbparm);
                   5259:     }
1.218     albertel 5260:     if (!($uname && $udom)) {
1.360     albertel 5261:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5262: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5263:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5264:     } else {
1.620     albertel 5265: 	$courseid=$env{'request.course.id'};
1.218     albertel 5266:     }
1.48      www      5267:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5268:     my $rest;
1.320     albertel 5269:     if (defined($therest[0])) {
1.48      www      5270:        $rest=join('.',@therest);
                   5271:     } else {
                   5272:        $rest='';
                   5273:     }
1.320     albertel 5274: 
1.57      www      5275:     my $qualifierrest=$qualifier;
                   5276:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5277:     my $spacequalifierrest=$space;
                   5278:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5279:     if ($realm eq 'user') {
1.48      www      5280: # --------------------------------------------------------------- user.resource
                   5281: 	if ($space eq 'resource') {
1.651     albertel 5282: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5283: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5284: 		 &&
1.744     albertel 5285: 		 ($symbparm eq &symbread()) ) {	
                   5286: 		# if we are in the middle of processing the resource the
                   5287: 		# get the value we are planning on committing
                   5288:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5289:                     return $Apache::lonhomework::results{$qualifierrest};
                   5290:                 } else {
                   5291:                     return $Apache::lonhomework::history{$qualifierrest};
                   5292:                 }
1.335     albertel 5293: 	    } else {
1.359     albertel 5294: 		my %restored;
1.620     albertel 5295: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5296: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5297: 		} else {
                   5298: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5299: 		}
1.335     albertel 5300: 		return $restored{$qualifierrest};
                   5301: 	    }
1.48      www      5302: # ----------------------------------------------------------------- user.access
                   5303:         } elsif ($space eq 'access') {
1.218     albertel 5304: 	    # FIXME - not supporting calls for a specific user
1.48      www      5305:             return &allowed($qualifier,$rest);
                   5306: # ------------------------------------------ user.preferences, user.environment
                   5307:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5308: 	    if (($uname eq $env{'user.name'}) &&
                   5309: 		($udom eq $env{'user.domain'})) {
                   5310: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5311: 	    } else {
1.359     albertel 5312: 		my %returnhash;
                   5313: 		if (!$publicuser) {
                   5314: 		    %returnhash=&userenvironment($udom,$uname,
                   5315: 						 $qualifierrest);
                   5316: 		}
1.218     albertel 5317: 		return $returnhash{$qualifierrest};
                   5318: 	    }
1.48      www      5319: # ----------------------------------------------------------------- user.course
                   5320:         } elsif ($space eq 'course') {
1.218     albertel 5321: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5322:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5323: # ------------------------------------------------------------------- user.role
                   5324:         } elsif ($space eq 'role') {
1.218     albertel 5325: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5326:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5327:             if ($qualifier eq 'value') {
                   5328: 		return $role;
                   5329:             } elsif ($qualifier eq 'extent') {
                   5330:                 return $where;
                   5331:             }
                   5332: # ----------------------------------------------------------------- user.domain
                   5333:         } elsif ($space eq 'domain') {
1.218     albertel 5334:             return $udom;
1.48      www      5335: # ------------------------------------------------------------------- user.name
                   5336:         } elsif ($space eq 'name') {
1.218     albertel 5337:             return $uname;
1.48      www      5338: # ---------------------------------------------------- Any other user namespace
1.29      www      5339:         } else {
1.359     albertel 5340: 	    my %reply;
                   5341: 	    if (!$publicuser) {
                   5342: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5343: 	    }
                   5344: 	    return $reply{$qualifierrest};
1.48      www      5345:         }
1.236     www      5346:     } elsif ($realm eq 'query') {
                   5347: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5348:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5349: 						[$spacequalifierrest]);
1.620     albertel 5350: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5351:    } elsif ($realm eq 'request') {
1.48      www      5352: # ------------------------------------------------------------- request.browser
                   5353:         if ($space eq 'browser') {
1.430     www      5354: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5355: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5356: 		    return 1;
                   5357: 		} else {
                   5358: 		    return 0;
                   5359: 		}
                   5360: 	    } else {
1.620     albertel 5361: 		return $env{'browser.'.$qualifier};
1.430     www      5362: 	    }
1.57      www      5363: # ------------------------------------------------------------ request.filename
                   5364:         } else {
1.620     albertel 5365:             return $env{'request.'.$spacequalifierrest};
1.29      www      5366:         }
1.28      www      5367:     } elsif ($realm eq 'course') {
1.48      www      5368: # ---------------------------------------------------------- course.description
1.620     albertel 5369:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5370:     } elsif ($realm eq 'resource') {
1.165     www      5371: 
1.620     albertel 5372: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5373: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5374: 	}
1.693     albertel 5375: 
                   5376: 	if ($space eq 'title') {
                   5377: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5378: 	    return &gettitle($symbparm);
                   5379: 	}
                   5380: 	
                   5381: 	if ($space eq 'map') {
                   5382: 	    my ($map) = &decode_symb($symbparm);
                   5383: 	    return &symbread($map);
                   5384: 	}
                   5385: 
                   5386: 	my ($section, $group, @groups);
1.593     albertel 5387: 	my ($courselevelm,$courselevel);
1.539     albertel 5388: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5389: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5390: 
1.218     albertel 5391: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5392: 
1.60      www      5393: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5394: 	    my $symbp=$symbparm;
1.735     albertel 5395: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5396: 
                   5397: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5398: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5399: 
1.620     albertel 5400: 	    if (($env{'user.name'} eq $uname) &&
                   5401: 		($env{'user.domain'} eq $udom)) {
                   5402: 		$section=$env{'request.course.sec'};
1.733     raeburn  5403:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5404:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5405: 	    } else {
1.539     albertel 5406: 		if (! defined($usection)) {
1.551     albertel 5407: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5408: 		} else {
                   5409: 		    $section = $usection;
                   5410: 		}
1.733     raeburn  5411:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5412: 	    }
                   5413: 
                   5414: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5415: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5416: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5417: 
1.593     albertel 5418: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5419: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5420: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5421: 
1.60      www      5422: # ----------------------------------------------------------- first, check user
1.624     albertel 5423: 
                   5424: 	    my $userreply=&resdata($uname,$udom,'user',
                   5425: 				       ($courselevelr,$courselevelm,
                   5426: 					$courselevel));
                   5427: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5428: 
1.594     albertel 5429: # ------------------------------------------------ second, check some of course
1.684     raeburn  5430:             my $coursereply;
1.691     raeburn  5431:             if (@groups > 0) {
                   5432:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5433:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5434:                 if (defined($coursereply)) { return $coursereply; }
                   5435:             }
1.96      www      5436: 
1.684     raeburn  5437: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5438: 				     $env{'course.'.$courseid.'.domain'},
                   5439: 				     'course',
                   5440: 				     ($seclevelr,$seclevelm,$seclevel,
                   5441: 				      $courselevelr));
1.287     albertel 5442: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5443: 
1.60      www      5444: # ------------------------------------------------------ third, check map parms
1.218     albertel 5445: 	    my %parmhash=();
                   5446: 	    my $thisparm='';
                   5447: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5448: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5449: 		    &GDBM_READER(),0640)) {
1.218     albertel 5450: 		$thisparm=$parmhash{$symbparm};
                   5451: 		untie(%parmhash);
                   5452: 	    }
                   5453: 	    if ($thisparm) { return $thisparm; }
                   5454: 	}
1.594     albertel 5455: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5456: 
1.218     albertel 5457: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5458: 	my $filename;
                   5459: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5460: 	if ($symbparm) {
1.409     www      5461: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5462: 	} else {
1.620     albertel 5463: 	    $filename=$env{'request.filename'};
1.282     albertel 5464: 	}
                   5465: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5466: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5467: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5468: 	if (defined($metadata)) { return $metadata; }
1.142     www      5469: 
1.594     albertel 5470: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5471: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5472: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5473: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5474: 				     $env{'course.'.$courseid.'.domain'},
                   5475: 				     'course',
                   5476: 				     ($courselevelm,$courselevel));
1.593     albertel 5477: 	    if (defined($coursereply)) { return $coursereply; }
                   5478: 	}
1.145     www      5479: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5480: 	unless ($space eq '0') {
1.336     albertel 5481: 	    my @parts=split(/_/,$space);
                   5482: 	    my $id=pop(@parts);
                   5483: 	    my $part=join('_',@parts);
                   5484: 	    if ($part eq '') { $part='0'; }
                   5485: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5486: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5487: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5488: 	}
1.395     albertel 5489: 	if ($recurse) { return undef; }
                   5490: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5491: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5492: 
1.48      www      5493: # ---------------------------------------------------- Any other user namespace
                   5494:     } elsif ($realm eq 'environment') {
                   5495: # ----------------------------------------------------------------- environment
1.620     albertel 5496: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5497: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5498: 	} else {
                   5499: 	    my %returnhash=&userenvironment($udom,$uname,
                   5500: 					    $spacequalifierrest);
                   5501: 	    return $returnhash{$spacequalifierrest};
                   5502: 	}
1.28      www      5503:     } elsif ($realm eq 'system') {
1.48      www      5504: # ----------------------------------------------------------------- system.time
                   5505: 	if ($space eq 'time') {
                   5506: 	    return time;
                   5507:         }
1.696     albertel 5508:     } elsif ($realm eq 'server') {
                   5509: # ----------------------------------------------------------------- system.time
                   5510: 	if ($space eq 'name') {
                   5511: 	    return $ENV{'SERVER_NAME'};
                   5512:         }
1.28      www      5513:     }
1.48      www      5514:     return '';
1.61      www      5515: }
                   5516: 
1.691     raeburn  5517: sub check_group_parms {
                   5518:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5519:     my @groupitems = ();
                   5520:     my $resultitem;
                   5521:     my @levels = ($symbparm,$mapparm,$what);
                   5522:     foreach my $group (@{$groups}) {
                   5523:         foreach my $level (@levels) {
                   5524:              my $item = $courseid.'.['.$group.'].'.$level;
                   5525:              push(@groupitems,$item);
                   5526:         }
                   5527:     }
                   5528:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5529:                             $env{'course.'.$courseid.'.domain'},
                   5530:                                      'course',@groupitems);
                   5531:     return $coursereply;
                   5532: }
                   5533: 
                   5534: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5535:     my ($courseid,@groups) = @_;
                   5536:     @groups = sort(@groups);
1.691     raeburn  5537:     return @groups;
                   5538: }
                   5539: 
1.395     albertel 5540: sub packages_tab_default {
                   5541:     my ($uri,$varname)=@_;
                   5542:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5543: 
                   5544:     my (@extension,@specifics,$do_default);
                   5545:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5546: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5547: 	if ($pack_type eq 'default') {
                   5548: 	    $do_default=1;
                   5549: 	} elsif ($pack_type eq 'extension') {
                   5550: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5551: 	} else {
                   5552: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5553: 	}
                   5554:     }
                   5555:     # first look for a package that matches the requested part id
                   5556:     foreach my $package (@specifics) {
                   5557: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5558: 	next if ($pack_part ne $part);
                   5559: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5560: 	    return $packagetab{"$pack_type&$name&default"};
                   5561: 	}
                   5562:     }
                   5563:     # look for any possible matching non extension_ package
                   5564:     foreach my $package (@specifics) {
                   5565: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5566: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5567: 	    return $packagetab{"$pack_type&$name&default"};
                   5568: 	}
1.585     albertel 5569: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5570: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5571: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5572: 	}
                   5573:     }
1.738     albertel 5574:     # look for any posible extension_ match
                   5575:     foreach my $package (@extension) {
                   5576: 	my ($package,$pack_type)=@{$package};
                   5577: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5578: 	    return $packagetab{"$pack_type&$name&default"};
                   5579: 	}
                   5580: 	if (defined($packagetab{$package."&$name&default"})) {
                   5581: 	    return $packagetab{$package."&$name&default"};
                   5582: 	}
                   5583:     }
                   5584:     # look for a global default setting
                   5585:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5586: 	return $packagetab{"default&$name&default"};
                   5587:     }
1.395     albertel 5588:     return undef;
                   5589: }
                   5590: 
1.334     albertel 5591: sub add_prefix_and_part {
                   5592:     my ($prefix,$part)=@_;
                   5593:     my $keyroot;
                   5594:     if (defined($prefix) && $prefix !~ /^__/) {
                   5595: 	# prefix that has a part already
                   5596: 	$keyroot=$prefix;
                   5597:     } elsif (defined($prefix)) {
                   5598: 	# prefix that is missing a part
                   5599: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5600:     } else {
                   5601: 	# no prefix at all
                   5602: 	if (defined($part)) { $keyroot='_'.$part; }
                   5603:     }
                   5604:     return $keyroot;
                   5605: }
                   5606: 
1.71      www      5607: # ---------------------------------------------------------------- Get metadata
                   5608: 
1.599     albertel 5609: my %metaentry;
1.71      www      5610: sub metadata {
1.176     www      5611:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5612:     $uri=&declutter($uri);
1.288     albertel 5613:     # if it is a non metadata possible uri return quickly
1.529     albertel 5614:     if (($uri eq '') || 
                   5615: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5616: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5617:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5618: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5619: 	return undef;
1.288     albertel 5620:     }
1.73      www      5621:     my $filename=$uri;
                   5622:     $uri=~s/\.meta$//;
1.172     www      5623: #
                   5624: # Is the metadata already cached?
1.177     www      5625: # Look at timestamp of caching
1.172     www      5626: # Everything is cached by the main uri, libraries are never directly cached
                   5627: #
1.428     albertel 5628:     if (!defined($liburi)) {
1.599     albertel 5629: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5630: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5631:     }
                   5632:     {
1.172     www      5633: #
                   5634: # Is this a recursive call for a library?
                   5635: #
1.599     albertel 5636: #	if (! exists($metacache{$uri})) {
                   5637: #	    $metacache{$uri}={};
                   5638: #	}
1.171     www      5639:         if ($liburi) {
                   5640: 	    $liburi=&declutter($liburi);
                   5641:             $filename=$liburi;
1.401     bowersj2 5642:         } else {
1.599     albertel 5643: 	    &devalidate_cache_new('meta',$uri);
                   5644: 	    undef(%metaentry);
1.401     bowersj2 5645: 	}
1.140     www      5646:         my %metathesekeys=();
1.73      www      5647:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5648: 	my $metastring;
1.609     banghart 5649: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 5650: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5651: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5652: 	    $metastring=&getfile($file);
1.489     albertel 5653: 	}
1.208     albertel 5654:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5655:         my $token;
1.140     www      5656:         undef %metathesekeys;
1.71      www      5657:         while ($token=$parser->get_token) {
1.339     albertel 5658: 	    if ($token->[0] eq 'S') {
                   5659: 		if (defined($token->[2]->{'package'})) {
1.172     www      5660: #
                   5661: # This is a package - get package info
                   5662: #
1.339     albertel 5663: 		    my $package=$token->[2]->{'package'};
                   5664: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5665: 		    if (defined($token->[2]->{'id'})) { 
                   5666: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5667: 		    }
1.599     albertel 5668: 		    if ($metaentry{':packages'}) {
                   5669: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5670: 		    } else {
1.599     albertel 5671: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5672: 		    }
1.736     albertel 5673: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5674: 			my $part=$keyroot;
                   5675: 			$part=~s/^\_//;
1.736     albertel 5676: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5677: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5678: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5679: 			    # ignore package.tab specified default values
                   5680:                             # here &package_tab_default() will fetch those
                   5681: 			    if ($subp eq 'default') { next; }
1.736     albertel 5682: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5683: 			    my $unikey;
                   5684: 			    if ($pack =~ /_0$/) {
                   5685: 				$unikey='parameter_0_'.$name;
                   5686: 				$part=0;
                   5687: 			    } else {
                   5688: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5689: 			    }
1.339     albertel 5690: 			    if ($subp eq 'display') {
                   5691: 				$value.=' [Part: '.$part.']';
                   5692: 			    }
1.599     albertel 5693: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5694: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5695: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5696: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5697: 			    }
1.599     albertel 5698: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5699: 				$metaentry{':'.$unikey}=
                   5700: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5701: 			    }
1.339     albertel 5702: 			}
                   5703: 		    }
                   5704: 		} else {
1.172     www      5705: #
                   5706: # This is not a package - some other kind of start tag
1.339     albertel 5707: #
                   5708: 		    my $entry=$token->[1];
                   5709: 		    my $unikey;
                   5710: 		    if ($entry eq 'import') {
                   5711: 			$unikey='';
                   5712: 		    } else {
                   5713: 			$unikey=$entry;
                   5714: 		    }
                   5715: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5716: 
                   5717: 		    if (defined($token->[2]->{'id'})) { 
                   5718: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5719: 		    }
1.175     www      5720: 
1.339     albertel 5721: 		    if ($entry eq 'import') {
1.175     www      5722: #
                   5723: # Importing a library here
1.339     albertel 5724: #
                   5725: 			if ($depthcount<20) {
                   5726: 			    my $location=$parser->get_text('/import');
                   5727: 			    my $dir=$filename;
                   5728: 			    $dir=~s|[^/]*$||;
                   5729: 			    $location=&filelocation($dir,$location);
1.736     albertel 5730: 			    my $metadata = 
                   5731: 				&metadata($uri,'keys', $location,$unikey,
                   5732: 					  $depthcount+1);
                   5733: 			    foreach my $meta (split(',',$metadata)) {
                   5734: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   5735: 				$metathesekeys{$meta}=1;
1.339     albertel 5736: 			    }
                   5737: 			}
                   5738: 		    } else { 
                   5739: 			
                   5740: 			if (defined($token->[2]->{'name'})) { 
                   5741: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5742: 			}
                   5743: 			$metathesekeys{$unikey}=1;
1.736     albertel 5744: 			foreach my $param (@{$token->[3]}) {
                   5745: 			    $metaentry{':'.$unikey.'.'.$param} =
                   5746: 				$token->[2]->{$param};
1.339     albertel 5747: 			}
                   5748: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5749: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5750: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5751: 		 # only ws inside the tag, and not in default, so use default
                   5752: 		 # as value
1.599     albertel 5753: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5754: 			} else {
1.321     albertel 5755: 		  # either something interesting inside the tag or default
                   5756:                   # uninteresting
1.599     albertel 5757: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5758: 			}
1.172     www      5759: # end of not-a-package not-a-library import
1.339     albertel 5760: 		    }
1.172     www      5761: # end of not-a-package start tag
1.339     albertel 5762: 		}
1.172     www      5763: # the next is the end of "start tag"
1.339     albertel 5764: 	    }
                   5765: 	}
1.483     albertel 5766: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 5767: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 5768: 	    #no specific packages #how's our extension
                   5769: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5770: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5771: 					 \%metathesekeys);
                   5772: 	}
1.599     albertel 5773: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 5774: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 5775: 		#no specific packages well let's get default then
                   5776: 		if ($key!~/^default&/) { next; }
1.488     albertel 5777: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5778: 					     \%metathesekeys);
                   5779: 	    }
                   5780: 	}
1.338     www      5781: # are there custom rights to evaluate
1.599     albertel 5782: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5783: 
1.338     www      5784:     #
                   5785:     # Importing a rights file here
1.339     albertel 5786:     #
                   5787: 	    unless ($depthcount) {
1.599     albertel 5788: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5789: 		my $dir=$filename;
                   5790: 		$dir=~s|[^/]*$||;
                   5791: 		$location=&filelocation($dir,$location);
1.736     albertel 5792: 		my $rights_metadata =
                   5793: 		    &metadata($uri,'keys',$location,'_rights',
                   5794: 			      $depthcount+1);
                   5795: 		foreach my $rights (split(',',$rights_metadata)) {
                   5796: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   5797: 		    $metathesekeys{$rights}=1;
1.339     albertel 5798: 		}
                   5799: 	    }
                   5800: 	}
1.737     albertel 5801: 	# uniqifiy package listing
                   5802: 	my %seen;
                   5803: 	my @uniq_packages =
                   5804: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   5805: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   5806: 
                   5807: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 5808: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5809: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 5810: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      5811: # this is the end of "was not already recently cached
1.71      www      5812:     }
1.599     albertel 5813:     return $metaentry{':'.$what};
1.261     albertel 5814: }
                   5815: 
1.488     albertel 5816: sub metadata_create_package_def {
1.483     albertel 5817:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5818:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5819:     if ($subp eq 'default') { next; }
                   5820:     
1.599     albertel 5821:     if (defined($metaentry{':packages'})) {
                   5822: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5823:     } else {
1.599     albertel 5824: 	$metaentry{':packages'}=$package;
1.483     albertel 5825:     }
                   5826:     my $value=$packagetab{$key};
                   5827:     my $unikey;
                   5828:     $unikey='parameter_0_'.$name;
1.599     albertel 5829:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5830:     $$metathesekeys{$unikey}=1;
1.599     albertel 5831:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5832: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5833:     }
1.599     albertel 5834:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5835: 	$metaentry{':'.$unikey}=
                   5836: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5837:     }
                   5838: }
                   5839: 
1.261     albertel 5840: sub metadata_generate_part0 {
                   5841:     my ($metadata,$metacache,$uri) = @_;
                   5842:     my %allnames;
1.737     albertel 5843:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 5844: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5845: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5846: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5847: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5848: 	    $allnames{$name}=$part;
                   5849: 	  }
                   5850: 	}
                   5851:     }
                   5852:     foreach my $name (keys(%allnames)) {
                   5853:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5854:       my $key=":parameter_0_$name";
1.261     albertel 5855:       $$metacache{"$key.part"}='0';
                   5856:       $$metacache{"$key.name"}=$name;
1.428     albertel 5857:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5858: 					   $allnames{$name}.'_'.$name.
                   5859: 					   '.type'};
1.428     albertel 5860:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5861: 			     '.display'};
1.644     www      5862:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5863:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5864:       $$metacache{"$key.display"}=$olddis;
                   5865:     }
1.71      www      5866: }
                   5867: 
1.301     www      5868: # ------------------------------------------------- Get the title of a resource
                   5869: 
                   5870: sub gettitle {
                   5871:     my $urlsymb=shift;
                   5872:     my $symb=&symbread($urlsymb);
1.534     albertel 5873:     if ($symb) {
1.620     albertel 5874: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5875: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5876: 	if (defined($cached)) { 
                   5877: 	    return $result;
                   5878: 	}
1.534     albertel 5879: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5880: 	my $title='';
                   5881: 	my %bighash;
1.620     albertel 5882: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5883: 		&GDBM_READER(),0640)) {
                   5884: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5885: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5886: 	    untie %bighash;
                   5887: 	}
                   5888: 	$title=~s/\&colon\;/\:/gs;
                   5889: 	if ($title) {
1.599     albertel 5890: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5891: 	}
                   5892: 	$urlsymb=$url;
                   5893:     }
                   5894:     my $title=&metadata($urlsymb,'title');
                   5895:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5896:     return $title;
1.301     www      5897: }
1.613     albertel 5898: 
1.614     albertel 5899: sub get_slot {
                   5900:     my ($which,$cnum,$cdom)=@_;
                   5901:     if (!$cnum || !$cdom) {
                   5902: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5903: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5904: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5905:     }
1.703     albertel 5906:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   5907:     my %slotinfo;
                   5908:     if (exists($remembered{$key})) {
                   5909: 	$slotinfo{$which} = $remembered{$key};
                   5910:     } else {
                   5911: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5912: 	&Apache::lonhomework::showhash(%slotinfo);
                   5913: 	my ($tmp)=keys(%slotinfo);
                   5914: 	if ($tmp=~/^error:/) { return (); }
                   5915: 	$remembered{$key} = $slotinfo{$which};
                   5916:     }
1.616     albertel 5917:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5918: 	return %{$slotinfo{$which}};
                   5919:     }
                   5920:     return $slotinfo{$which};
1.614     albertel 5921: }
1.31      www      5922: # ------------------------------------------------- Update symbolic store links
                   5923: 
                   5924: sub symblist {
                   5925:     my ($mapname,%newhash)=@_;
1.438     www      5926:     $mapname=&deversion(&declutter($mapname));
1.31      www      5927:     my %hash;
1.620     albertel 5928:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5929:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5930:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 5931: 	    foreach my $url (keys %newhash) {
                   5932: 		next if ($url eq 'last_known'
                   5933: 			 && $env{'form.no_update_last_known'});
                   5934: 		$hash{declutter($url)}=&encode_symb($mapname,
                   5935: 						    $newhash{$url}->[1],
                   5936: 						    $newhash{$url}->[0]);
1.191     harris41 5937:             }
1.31      www      5938:             if (untie(%hash)) {
                   5939: 		return 'ok';
                   5940:             }
                   5941:         }
                   5942:     }
                   5943:     return 'error';
1.212     www      5944: }
                   5945: 
                   5946: # --------------------------------------------------------------- Verify a symb
                   5947: 
                   5948: sub symbverify {
1.510     www      5949:     my ($symb,$thisurl)=@_;
                   5950:     my $thisfn=$thisurl;
                   5951: # wrapper not part of symbs
                   5952:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 5953:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      5954:     $thisfn=&declutter($thisfn);
1.215     www      5955: # direct jump to resource in page or to a sequence - will construct own symbs
                   5956:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5957: # check URL part
1.409     www      5958:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5959: 
1.431     www      5960:     unless ($url eq $thisfn) { return 0; }
1.213     www      5961: 
1.216     www      5962:     $symb=&symbclean($symb);
1.510     www      5963:     $thisurl=&deversion($thisurl);
1.439     www      5964:     $thisfn=&deversion($thisfn);
1.213     www      5965: 
                   5966:     my %bighash;
                   5967:     my $okay=0;
1.431     www      5968: 
1.620     albertel 5969:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5970:                             &GDBM_READER(),0640)) {
1.510     www      5971:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5972:         unless ($ids) { 
1.510     www      5973:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5974:         }
                   5975:         if ($ids) {
                   5976: # ------------------------------------------------------------------- Has ID(s)
                   5977: 	    foreach (split(/\,/,$ids)) {
1.644     www      5978: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5979:                if (
                   5980:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5981:    eq $symb) { 
1.620     albertel 5982: 		   if (($env{'request.role.adv'}) ||
                   5983: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5984: 		       $okay=1; 
                   5985: 		   }
                   5986: 	       }
1.216     www      5987: 	   }
                   5988:         }
1.213     www      5989: 	untie(%bighash);
                   5990:     }
                   5991:     return $okay;
1.31      www      5992: }
                   5993: 
1.210     www      5994: # --------------------------------------------------------------- Clean-up symb
                   5995: 
                   5996: sub symbclean {
                   5997:     my $symb=shift;
1.568     albertel 5998:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5999: # remove version from map
                   6000:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6001: 
1.210     www      6002: # remove version from URL
                   6003:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6004: 
1.507     www      6005: # remove wrapper
                   6006: 
1.510     www      6007:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6008:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6009:     return $symb;
1.409     www      6010: }
                   6011: 
                   6012: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6013: 
                   6014: sub encode_symb {
                   6015:     my ($map,$resid,$url)=@_;
                   6016:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6017: }
1.409     www      6018: 
                   6019: sub decode_symb {
1.568     albertel 6020:     my $symb=shift;
                   6021:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6022:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6023:     return (&fixversion($map),$resid,&fixversion($url));
                   6024: }
                   6025: 
                   6026: sub fixversion {
                   6027:     my $fn=shift;
1.609     banghart 6028:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6029:     my %bighash;
                   6030:     my $uri=&clutter($fn);
1.620     albertel 6031:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6032: # is this cached?
1.599     albertel 6033:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6034:     if (defined($cached)) { return $result; }
                   6035: # unfortunately not cached, or expired
1.620     albertel 6036:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6037: 	    &GDBM_READER(),0640)) {
                   6038:  	if ($bighash{'version_'.$uri}) {
                   6039:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6040:  	    unless (($version eq 'mostrecent') || 
                   6041: 		    ($version==&getversion($uri))) {
1.440     www      6042:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6043:  	    }
                   6044:  	}
                   6045:  	untie %bighash;
1.413     www      6046:     }
1.599     albertel 6047:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6048: }
                   6049: 
                   6050: sub deversion {
                   6051:     my $url=shift;
                   6052:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6053:     return $url;
1.210     www      6054: }
                   6055: 
1.31      www      6056: # ------------------------------------------------------ Return symb list entry
                   6057: 
                   6058: sub symbread {
1.249     www      6059:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6060:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6061:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6062: # no filename provided? try from environment
1.44      www      6063:     unless ($thisfn) {
1.620     albertel 6064:         if ($env{'request.symb'}) {
                   6065: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6066: 	}
1.620     albertel 6067: 	$thisfn=$env{'request.filename'};
1.44      www      6068:     }
1.569     albertel 6069:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6070: # is that filename actually a symb? Verify, clean, and return
                   6071:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6072: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6073: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6074: 	}
1.242     www      6075:     }
1.44      www      6076:     $thisfn=declutter($thisfn);
1.31      www      6077:     my %hash;
1.37      www      6078:     my %bighash;
                   6079:     my $syval='';
1.620     albertel 6080:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6081:         my $targetfn = $thisfn;
1.609     banghart 6082:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6083:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6084:         }
1.687     albertel 6085: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6086: 	    $targetfn=$1;
                   6087: 	}
1.620     albertel 6088:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6089:                       &GDBM_READER(),0640)) {
1.481     raeburn  6090: 	    $syval=$hash{$targetfn};
1.37      www      6091:             untie(%hash);
                   6092:         }
                   6093: # ---------------------------------------------------------- There was an entry
                   6094:         if ($syval) {
1.601     albertel 6095: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6096: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6097: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6098: 		    #return $env{$cache_str}='';
1.601     albertel 6099: 		#}    
                   6100: 		#$syval.=$1;
                   6101: 	    #}
1.37      www      6102:         } else {
                   6103: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6104:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6105:                             &GDBM_READER(),0640)) {
1.37      www      6106: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6107:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6108:               unless ($ids) { 
                   6109:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6110:               }
                   6111:               unless ($ids) {
                   6112: # alias?
                   6113: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6114:               }
1.37      www      6115:               if ($ids) {
                   6116: # ------------------------------------------------------------------- Has ID(s)
                   6117:                  my @possibilities=split(/\,/,$ids);
1.39      www      6118:                  if ($#possibilities==0) {
                   6119: # ----------------------------------------------- There is only one possibility
1.37      www      6120: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6121: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6122: 						    $resid,$thisfn);
1.249     www      6123:                  } elsif (!$donotrecurse) {
1.39      www      6124: # ------------------------------------------ There is more than one possibility
                   6125:                      my $realpossible=0;
1.191     harris41 6126:                      foreach (@possibilities) {
1.39      www      6127: 			 my $file=$bighash{'src_'.$_};
                   6128:                          if (&allowed('bre',$file)) {
                   6129:          		    my ($mapid,$resid)=split(/\./,$_);
                   6130:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6131: 				$realpossible++;
1.626     albertel 6132:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6133: 						    $resid,$thisfn);
1.39      www      6134:                             }
                   6135: 			 }
1.191     harris41 6136:                      }
1.39      www      6137: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6138:                  } else {
                   6139:                      $syval='';
1.37      www      6140:                  }
                   6141: 	      }
                   6142:               untie(%bighash)
1.481     raeburn  6143:            }
1.31      www      6144:         }
1.62      www      6145:         if ($syval) {
1.620     albertel 6146: 	    return $env{$cache_str}=$syval;
1.62      www      6147:         }
1.31      www      6148:     }
1.44      www      6149:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6150:     return $env{$cache_str}='';
1.31      www      6151: }
                   6152: 
                   6153: # ---------------------------------------------------------- Return random seed
                   6154: 
1.32      www      6155: sub numval {
                   6156:     my $txt=shift;
                   6157:     $txt=~tr/A-J/0-9/;
                   6158:     $txt=~tr/a-j/0-9/;
                   6159:     $txt=~tr/K-T/0-9/;
                   6160:     $txt=~tr/k-t/0-9/;
                   6161:     $txt=~tr/U-Z/0-5/;
                   6162:     $txt=~tr/u-z/0-5/;
                   6163:     $txt=~s/\D//g;
1.564     albertel 6164:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6165:     return int($txt);
1.368     albertel 6166: }
                   6167: 
1.484     albertel 6168: sub numval2 {
                   6169:     my $txt=shift;
                   6170:     $txt=~tr/A-J/0-9/;
                   6171:     $txt=~tr/a-j/0-9/;
                   6172:     $txt=~tr/K-T/0-9/;
                   6173:     $txt=~tr/k-t/0-9/;
                   6174:     $txt=~tr/U-Z/0-5/;
                   6175:     $txt=~tr/u-z/0-5/;
                   6176:     $txt=~s/\D//g;
                   6177:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6178:     my $total;
                   6179:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6180:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6181:     return int($total);
                   6182: }
                   6183: 
1.575     albertel 6184: sub numval3 {
                   6185:     use integer;
                   6186:     my $txt=shift;
                   6187:     $txt=~tr/A-J/0-9/;
                   6188:     $txt=~tr/a-j/0-9/;
                   6189:     $txt=~tr/K-T/0-9/;
                   6190:     $txt=~tr/k-t/0-9/;
                   6191:     $txt=~tr/U-Z/0-5/;
                   6192:     $txt=~tr/u-z/0-5/;
                   6193:     $txt=~s/\D//g;
                   6194:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6195:     my $total;
                   6196:     foreach my $val (@txts) { $total+=$val; }
                   6197:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6198:     return $total;
                   6199: }
                   6200: 
1.675     albertel 6201: sub digest {
                   6202:     my ($data)=@_;
                   6203:     my $digest=&Digest::MD5::md5($data);
                   6204:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6205:     my ($e,$f);
                   6206:     {
                   6207:         use integer;
                   6208:         $e=($a+$b);
                   6209:         $f=($c+$d);
                   6210:         if ($_64bit) {
                   6211:             $e=(($e<<32)>>32);
                   6212:             $f=(($f<<32)>>32);
                   6213:         }
                   6214:     }
                   6215:     if (wantarray) {
                   6216: 	return ($e,$f);
                   6217:     } else {
                   6218: 	my $g;
                   6219: 	{
                   6220: 	    use integer;
                   6221: 	    $g=($e+$f);
                   6222: 	    if ($_64bit) {
                   6223: 		$g=(($g<<32)>>32);
                   6224: 	    }
                   6225: 	}
                   6226: 	return $g;
                   6227:     }
                   6228: }
                   6229: 
1.368     albertel 6230: sub latest_rnd_algorithm_id {
1.675     albertel 6231:     return '64bit5';
1.366     albertel 6232: }
1.32      www      6233: 
1.503     albertel 6234: sub get_rand_alg {
                   6235:     my ($courseid)=@_;
                   6236:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6237:     if ($courseid) {
1.620     albertel 6238: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6239:     }
                   6240:     return &latest_rnd_algorithm_id();
                   6241: }
                   6242: 
1.562     albertel 6243: sub validCODE {
                   6244:     my ($CODE)=@_;
                   6245:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6246:     return 0;
                   6247: }
                   6248: 
1.491     albertel 6249: sub getCODE {
1.620     albertel 6250:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6251:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6252: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6253: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6254: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6255:     }
                   6256:     return undef;
                   6257: }
                   6258: 
1.31      www      6259: sub rndseed {
1.155     albertel 6260:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6261: 
                   6262:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6263:     if (!$symb) {
1.366     albertel 6264: 	unless ($symb=$wsymb) { return time; }
                   6265:     }
                   6266:     if (!$courseid) { $courseid=$wcourseid; }
                   6267:     if (!$domain) { $domain=$wdomain; }
                   6268:     if (!$username) { $username=$wusername }
1.503     albertel 6269:     my $which=&get_rand_alg();
1.491     albertel 6270:     if (defined(&getCODE())) {
1.675     albertel 6271: 	if ($which eq '64bit5') {
                   6272: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6273: 	} elsif ($which eq '64bit4') {
1.575     albertel 6274: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6275: 	} else {
                   6276: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6277: 	}
1.675     albertel 6278:     } elsif ($which eq '64bit5') {
                   6279: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6280:     } elsif ($which eq '64bit4') {
                   6281: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6282:     } elsif ($which eq '64bit3') {
                   6283: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6284:     } elsif ($which eq '64bit2') {
                   6285: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6286:     } elsif ($which eq '64bit') {
                   6287: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6288:     }
                   6289:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6290: }
                   6291: 
                   6292: sub rndseed_32bit {
                   6293:     my ($symb,$courseid,$domain,$username)=@_;
                   6294:     {
                   6295: 	use integer;
                   6296: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6297: 	my $symbseed=numval($symb) << 22;
                   6298: 	my $namechck=unpack("%32C*",$username) << 17;
                   6299: 	my $nameseed=numval($username) << 12;
                   6300: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6301: 	my $courseseed=unpack("%32C*",$courseid);
                   6302: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6303: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6304: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6305: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6306: 	return $num;
                   6307:     }
                   6308: }
                   6309: 
                   6310: sub rndseed_64bit {
                   6311:     my ($symb,$courseid,$domain,$username)=@_;
                   6312:     {
                   6313: 	use integer;
                   6314: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6315: 	my $symbseed=numval($symb) << 10;
                   6316: 	my $namechck=unpack("%32S*",$username);
                   6317: 	
                   6318: 	my $nameseed=numval($username) << 21;
                   6319: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6320: 	my $courseseed=unpack("%32S*",$courseid);
                   6321: 	
                   6322: 	my $num1=$symbchck+$symbseed+$namechck;
                   6323: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6324: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6325: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6326: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6327: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6328: 	return "$num1,$num2";
1.155     albertel 6329:     }
1.366     albertel 6330: }
                   6331: 
1.443     albertel 6332: sub rndseed_64bit2 {
                   6333:     my ($symb,$courseid,$domain,$username)=@_;
                   6334:     {
                   6335: 	use integer;
                   6336: 	# strings need to be an even # of cahracters long, it it is odd the
                   6337:         # last characters gets thrown away
                   6338: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6339: 	my $symbseed=numval($symb) << 10;
                   6340: 	my $namechck=unpack("%32S*",$username.' ');
                   6341: 	
                   6342: 	my $nameseed=numval($username) << 21;
1.501     albertel 6343: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6344: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6345: 	
                   6346: 	my $num1=$symbchck+$symbseed+$namechck;
                   6347: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6348: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6349: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6350: 	return "$num1,$num2";
                   6351:     }
                   6352: }
                   6353: 
                   6354: sub rndseed_64bit3 {
                   6355:     my ($symb,$courseid,$domain,$username)=@_;
                   6356:     {
                   6357: 	use integer;
                   6358: 	# strings need to be an even # of cahracters long, it it is odd the
                   6359:         # last characters gets thrown away
                   6360: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6361: 	my $symbseed=numval2($symb) << 10;
                   6362: 	my $namechck=unpack("%32S*",$username.' ');
                   6363: 	
                   6364: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6365: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6366: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6367: 	
                   6368: 	my $num1=$symbchck+$symbseed+$namechck;
                   6369: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6370: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6371: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6372: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6373: 	
1.503     albertel 6374: 	return "$num1:$num2";
1.443     albertel 6375:     }
                   6376: }
                   6377: 
1.575     albertel 6378: sub rndseed_64bit4 {
                   6379:     my ($symb,$courseid,$domain,$username)=@_;
                   6380:     {
                   6381: 	use integer;
                   6382: 	# strings need to be an even # of cahracters long, it it is odd the
                   6383:         # last characters gets thrown away
                   6384: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6385: 	my $symbseed=numval3($symb) << 10;
                   6386: 	my $namechck=unpack("%32S*",$username.' ');
                   6387: 	
                   6388: 	my $nameseed=numval3($username) << 21;
                   6389: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6390: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6391: 	
                   6392: 	my $num1=$symbchck+$symbseed+$namechck;
                   6393: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6394: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6395: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6396: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6397: 	
                   6398: 	return "$num1:$num2";
                   6399:     }
                   6400: }
                   6401: 
1.675     albertel 6402: sub rndseed_64bit5 {
                   6403:     my ($symb,$courseid,$domain,$username)=@_;
                   6404:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6405:     return "$num1:$num2";
                   6406: }
                   6407: 
1.366     albertel 6408: sub rndseed_CODE_64bit {
                   6409:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6410:     {
1.366     albertel 6411: 	use integer;
1.443     albertel 6412: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6413: 	my $symbseed=numval2($symb);
1.491     albertel 6414: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6415: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6416: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6417: 	my $num1=$symbseed+$CODEchck;
                   6418: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6419: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6420: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6421: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6422: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6423: 	return "$num1:$num2";
1.366     albertel 6424:     }
                   6425: }
                   6426: 
1.575     albertel 6427: sub rndseed_CODE_64bit4 {
                   6428:     my ($symb,$courseid,$domain,$username)=@_;
                   6429:     {
                   6430: 	use integer;
                   6431: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6432: 	my $symbseed=numval3($symb);
                   6433: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6434: 	my $CODEseed=numval3(&getCODE());
                   6435: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6436: 	my $num1=$symbseed+$CODEchck;
                   6437: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6438: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6439: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6440: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6441: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6442: 	return "$num1:$num2";
                   6443:     }
                   6444: }
                   6445: 
1.675     albertel 6446: sub rndseed_CODE_64bit5 {
                   6447:     my ($symb,$courseid,$domain,$username)=@_;
                   6448:     my $code = &getCODE();
                   6449:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6450:     return "$num1:$num2";
                   6451: }
                   6452: 
1.366     albertel 6453: sub setup_random_from_rndseed {
                   6454:     my ($rndseed)=@_;
1.503     albertel 6455:     if ($rndseed =~/([,:])/) {
                   6456: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6457: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6458:     } else {
                   6459: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6460:     }
1.36      albertel 6461: }
                   6462: 
1.474     albertel 6463: sub latest_receipt_algorithm_id {
                   6464:     return 'receipt2';
                   6465: }
                   6466: 
1.480     www      6467: sub recunique {
                   6468:     my $fucourseid=shift;
                   6469:     my $unique;
1.620     albertel 6470:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6471: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6472:     } else {
                   6473: 	$unique=$perlvar{'lonReceipt'};
                   6474:     }
                   6475:     return unpack("%32C*",$unique);
                   6476: }
                   6477: 
                   6478: sub recprefix {
                   6479:     my $fucourseid=shift;
                   6480:     my $prefix;
1.620     albertel 6481:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6482: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6483:     } else {
                   6484: 	$prefix=$perlvar{'lonHostID'};
                   6485:     }
                   6486:     return unpack("%32C*",$prefix);
                   6487: }
                   6488: 
1.76      www      6489: sub ireceipt {
1.474     albertel 6490:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6491:     my $cuname=unpack("%32C*",$funame);
                   6492:     my $cudom=unpack("%32C*",$fudom);
                   6493:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6494:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6495:     my $cunique=&recunique($fucourseid);
1.474     albertel 6496:     my $cpart=unpack("%32S*",$part);
1.480     www      6497:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6498:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6499: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6500: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6501: 			       " and ".($cpart%$cudom));
                   6502: 			       
                   6503: 	$return.= ($cunique%$cuname+
                   6504: 		   $cunique%$cudom+
                   6505: 		   $cusymb%$cuname+
                   6506: 		   $cusymb%$cudom+
                   6507: 		   $cucourseid%$cuname+
                   6508: 		   $cucourseid%$cudom+
                   6509: 		   $cpart%$cuname+
                   6510: 		   $cpart%$cudom);
                   6511:     } else {
                   6512: 	$return.= ($cunique%$cuname+
                   6513: 		   $cunique%$cudom+
                   6514: 		   $cusymb%$cuname+
                   6515: 		   $cusymb%$cudom+
                   6516: 		   $cucourseid%$cuname+
                   6517: 		   $cucourseid%$cudom);
                   6518:     }
                   6519:     return $return;
1.76      www      6520: }
                   6521: 
                   6522: sub receipt {
1.474     albertel 6523:     my ($part)=@_;
                   6524:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6525:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6526: }
1.260     ng       6527: 
1.36      albertel 6528: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6529: # returns either the contents of the file or 
                   6530: # -1 if the file doesn't exist
1.481     raeburn  6531: #
                   6532: # if the target is a file that was uploaded via DOCS, 
                   6533: # a check will be made to see if a current copy exists on the local server,
                   6534: # if it does this will be served, otherwise a copy will be retrieved from
                   6535: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6536: # the local server.   
1.472     albertel 6537: 
1.36      albertel 6538: sub getfile {
1.538     albertel 6539:     my ($file) = @_;
1.609     banghart 6540:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6541:     &repcopy($file);
                   6542:     return &readfile($file);
                   6543: }
                   6544: 
                   6545: sub repcopy_userfile {
                   6546:     my ($file)=@_;
1.609     banghart 6547:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6548:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6549:     my ($cdom,$cnum,$filename) = 
                   6550: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6551:     my ($info,$rtncode);
                   6552:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6553:     if (-e "$file") {
                   6554: 	my @fileinfo = stat($file);
                   6555: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6556: 	if ($lwpresp ne 'ok') {
                   6557: 	    if ($rtncode eq '404') {
1.538     albertel 6558: 		unlink($file);
1.482     albertel 6559: 	    }
1.517     albertel 6560: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6561: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6562: 	    #my $response=$ua->request($request);
                   6563: 	    #if ($response->is_success()) {
                   6564: 	#	return $response->content;
                   6565: 	#    } else {
                   6566: 	#	return -1;
                   6567: 	#    }
1.482     albertel 6568: 	    return -1;
                   6569: 	}
                   6570: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6571: 	    return 'ok';
1.482     albertel 6572: 	}
                   6573: 	$info = '';
1.538     albertel 6574: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6575: 	if ($lwpresp ne 'ok') {
                   6576: 	    return -1;
                   6577: 	}
                   6578:     } else {
1.538     albertel 6579: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6580: 	if ($lwpresp ne 'ok') {
1.517     albertel 6581: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6582: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6583: 	    my $response=$ua->request($request);
                   6584: 	    if ($response->is_success()) {
1.538     albertel 6585: 		$info=$response->content;
1.517     albertel 6586: 	    } else {
                   6587: 		return -1;
                   6588: 	    }
1.482     albertel 6589: 	}
                   6590: 	my @parts = ($cdom,$cnum); 
                   6591: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6592: 	    push @parts, split(/\//,$1);
1.518     albertel 6593: 	}
1.538     albertel 6594: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6595: 	foreach my $part (@parts) {
                   6596: 	    $path .= '/'.$part;
                   6597: 	    if (!-e $path) {
                   6598: 		mkdir($path,0770);
                   6599: 	    }
                   6600: 	}
                   6601:     }
1.538     albertel 6602:     open(FILE,">$file");
1.482     albertel 6603:     print FILE $info;
                   6604:     close(FILE);
1.607     raeburn  6605:     return 'ok';
1.481     raeburn  6606: }
                   6607: 
1.517     albertel 6608: sub tokenwrapper {
                   6609:     my $uri=shift;
1.552     albertel 6610:     $uri=~s|^http\://([^/]+)||;
                   6611:     $uri=~s|^/||;
1.620     albertel 6612:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6613:     my $token=$1;
1.552     albertel 6614:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6615:     if ($udom && $uname && $file) {
                   6616: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6617:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6618:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6619:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6620:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6621:     } else {
                   6622:         return '/adm/notfound.html';
                   6623:     }
                   6624: }
                   6625: 
1.481     raeburn  6626: sub getuploaded {
                   6627:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6628:     $uri=~s/^\///;
                   6629:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6630:     my $ua=new LWP::UserAgent;
                   6631:     my $request=new HTTP::Request($reqtype,$uri);
                   6632:     my $response=$ua->request($request);
                   6633:     $$rtncode = $response->code;
1.482     albertel 6634:     if (! $response->is_success()) {
                   6635: 	return 'failed';
                   6636:     }      
                   6637:     if ($reqtype eq 'HEAD') {
1.486     www      6638: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6639:     } elsif ($reqtype eq 'GET') {
                   6640: 	$$info = $response->content;
1.472     albertel 6641:     }
1.482     albertel 6642:     return 'ok';
1.36      albertel 6643: }
                   6644: 
1.481     raeburn  6645: sub readfile {
                   6646:     my $file = shift;
                   6647:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6648:     my $fh;
                   6649:     open($fh,"<$file");
                   6650:     my $a='';
                   6651:     while (<$fh>) { $a .=$_; }
                   6652:     return $a;
                   6653: }
                   6654: 
1.36      albertel 6655: sub filelocation {
1.590     banghart 6656:     my ($dir,$file) = @_;
                   6657:     my $location;
                   6658:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6659: 
                   6660:     if ($file =~ m-^/adm/-) {
                   6661: 	$file=~s-^/adm/wrapper/-/-;
                   6662: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6663:     }
1.590     banghart 6664:     if ($file=~m:^/~:) { # is a contruction space reference
                   6665:         $location = $file;
                   6666:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6667:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6668: 	# is a correct contruction space reference
                   6669:         $location = $file;
1.609     banghart 6670:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6671:         my ($udom,$uname,$filename)=
1.609     banghart 6672:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6673:         my $home=&homeserver($uname,$udom);
                   6674:         my $is_me=0;
                   6675:         my @ids=&current_machine_ids();
                   6676:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6677:         if ($is_me) {
1.740     www      6678:   	    $location=&propath($udom,$uname).
1.590     banghart 6679:   	      '/userfiles/'.$filename;
                   6680:         } else {
                   6681:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6682:   	      $udom.'/'.$uname.'/'.$filename;
                   6683:         }
                   6684:     } else {
                   6685:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6686:         $file=~s:^/res/:/:;
                   6687:         if ( !( $file =~ m:^/:) ) {
                   6688:             $location = $dir. '/'.$file;
                   6689:         } else {
                   6690:             $location = '/home/httpd/html/res'.$file;
                   6691:         }
1.59      albertel 6692:     }
1.590     banghart 6693:     $location=~s://+:/:g; # remove duplicate /
                   6694:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6695:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6696:     return $location;
1.46      www      6697: }
1.36      albertel 6698: 
1.46      www      6699: sub hreflocation {
                   6700:     my ($dir,$file)=@_;
1.460     albertel 6701:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6702: 	$file=filelocation($dir,$file);
1.700     albertel 6703:     } elsif ($file=~m-^/adm/-) {
                   6704: 	$file=~s-^/adm/wrapper/-/-;
                   6705: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6706:     }
                   6707:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6708: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6709:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6710: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6711:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6712: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6713: 	    -/uploaded/$1/$2/-x;
1.46      www      6714:     }
1.462     albertel 6715:     return $file;
1.465     albertel 6716: }
                   6717: 
                   6718: sub current_machine_domains {
                   6719:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6720:     my @domains;
                   6721:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6722: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6723: 	if ($hostname eq $name) {
                   6724: 	    push(@domains,$hostdom{$id});
                   6725: 	}
                   6726:     }
                   6727:     return @domains;
                   6728: }
                   6729: 
                   6730: sub current_machine_ids {
                   6731:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6732:     my @ids;
                   6733:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6734: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6735: 	if ($hostname eq $name) {
                   6736: 	    push(@ids,$id);
                   6737: 	}
                   6738:     }
                   6739:     return @ids;
1.31      www      6740: }
                   6741: 
                   6742: # ------------------------------------------------------------- Declutters URLs
                   6743: 
                   6744: sub declutter {
                   6745:     my $thisfn=shift;
1.569     albertel 6746:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6747:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6748:     $thisfn=~s/^\///;
1.697     albertel 6749:     $thisfn=~s|^adm/wrapper/||;
                   6750:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      6751:     $thisfn=~s/^res\///;
1.235     www      6752:     $thisfn=~s/\?.+$//;
1.268     www      6753:     return $thisfn;
                   6754: }
                   6755: 
                   6756: # ------------------------------------------------------------- Clutter up URLs
                   6757: 
                   6758: sub clutter {
                   6759:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6760:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6761:        $thisfn='/res'.$thisfn; 
                   6762:     }
1.694     albertel 6763:     if ($thisfn !~m|/adm|) {
1.695     albertel 6764: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 6765: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 6766: 	} else {
                   6767: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   6768: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 6769: 	    if ($embstyle eq 'ssi'
                   6770: 		|| ($embstyle eq 'hdn')
                   6771: 		|| ($embstyle eq 'rat')
                   6772: 		|| ($embstyle eq 'prv')
                   6773: 		|| ($embstyle eq 'ign')) {
                   6774: 		#do nothing with these
                   6775: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 6776: 		|| ($embstyle eq 'emb')
                   6777: 		|| ($embstyle eq 'wrp')) {
                   6778: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 6779: 	    } elsif ($embstyle eq 'unk'
                   6780: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 6781: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 6782: 	    } else {
1.718     www      6783: #		&logthis("Got a blank emb style");
1.695     albertel 6784: 	    }
1.694     albertel 6785: 	}
                   6786:     }
1.31      www      6787:     return $thisfn;
1.12      www      6788: }
                   6789: 
1.557     albertel 6790: sub freeze_escape {
                   6791:     my ($value)=@_;
                   6792:     if (ref($value)) {
                   6793: 	$value=&nfreeze($value);
                   6794: 	return '__FROZEN__'.&escape($value);
                   6795:     }
                   6796:     return &escape($value);
                   6797: }
                   6798: 
1.11      www      6799: 
1.557     albertel 6800: sub thaw_unescape {
                   6801:     my ($value)=@_;
                   6802:     if ($value =~ /^__FROZEN__/) {
                   6803: 	substr($value,0,10,undef);
                   6804: 	$value=&unescape($value);
                   6805: 	return &thaw($value);
                   6806:     }
                   6807:     return &unescape($value);
                   6808: }
                   6809: 
1.436     albertel 6810: sub correct_line_ends {
                   6811:     my ($result)=@_;
                   6812:     $$result =~s/\r\n/\n/mg;
                   6813:     $$result =~s/\r/\n/mg;
1.415     albertel 6814: }
1.1       albertel 6815: # ================================================================ Main Program
                   6816: 
1.184     www      6817: sub goodbye {
1.204     albertel 6818:    &logthis("Starting Shut down");
1.443     albertel 6819: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6820:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6821: #converted
1.599     albertel 6822: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6823:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6824: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6825: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6826: #1.1 only
1.599     albertel 6827: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6828: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6829: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6830: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6831:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6832:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6833:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6834:    &flushcourselogs();
                   6835:    &logthis("Shutting down");
                   6836: }
                   6837: 
1.179     www      6838: BEGIN {
1.228     harris41 6839: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6840:     unless ($readit) {
1.217     harris41 6841: {
1.581     matthew  6842:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6843:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6844: 
                   6845:     while (my $configline=<$config>) {
1.484     albertel 6846:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6847: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6848:            chomp($varvalue);
1.1       albertel 6849:            $perlvar{$varname}=$varvalue;
                   6850:         }
                   6851:     }
1.448     albertel 6852:     close($config);
1.1       albertel 6853: }
1.227     harris41 6854: {
1.448     albertel 6855:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6856: 
                   6857:     while (my $configline=<$config>) {
                   6858:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6859: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6860:            chomp($varvalue);
                   6861:            $perlvar{$varname}=$varvalue;
                   6862:         }
                   6863:     }
1.448     albertel 6864:     close($config);
1.227     harris41 6865: }
1.1       albertel 6866: 
1.327     albertel 6867: # ------------------------------------------------------------ Read domain file
                   6868: {
                   6869:     %domaindescription = ();
                   6870:     %domain_auth_def = ();
                   6871:     %domain_auth_arg_def = ();
1.448     albertel 6872:     my $fh;
                   6873:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6874:        while (<$fh>) {
1.390     matthew  6875:            next if (/^(\#|\s*$)/);
                   6876: #           next if /^\#/;
1.327     albertel 6877:            chomp;
1.403     www      6878:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  6879: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      6880: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6881:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6882: 	   $domaindescription{$domain}=$domain_description;
                   6883: 	   $domain_lang_def{$domain}=$def_lang;
                   6884: 	   $domain_city{$domain}=$city;
                   6885: 	   $domain_longi{$domain}=$longi;
                   6886: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  6887:            $domain_primary{$domain}=$primary;
1.403     www      6888: 
1.448     albertel 6889:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6890: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6891: 	}
1.327     albertel 6892:     }
1.448     albertel 6893:     close ($fh);
1.327     albertel 6894: }
                   6895: 
                   6896: 
1.1       albertel 6897: # ------------------------------------------------------------- Read hosts file
                   6898: {
1.448     albertel 6899:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6900: 
                   6901:     while (my $configline=<$config>) {
1.303     matthew  6902:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6903:        chomp($configline);
1.595     albertel 6904:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6905:        $name=~s/\s//g;
1.595     albertel 6906:        if ($id && $domain && $role && $name) {
1.252     albertel 6907: 	 $hostname{$id}=$name;
                   6908: 	 $hostdom{$id}=$domain;
                   6909: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6910:        }
1.1       albertel 6911:     }
1.448     albertel 6912:     close($config);
1.619     albertel 6913:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 6914:     #&get_iphost();
1.1       albertel 6915: }
                   6916: 
1.598     albertel 6917: sub get_iphost {
                   6918:     if (%iphost) { return %iphost; }
1.653     albertel 6919:     my %name_to_ip;
1.598     albertel 6920:     foreach my $id (keys(%hostname)) {
                   6921: 	my $name=$hostname{$id};
1.653     albertel 6922: 	my $ip;
                   6923: 	if (!exists($name_to_ip{$name})) {
                   6924: 	    $ip = gethostbyname($name);
                   6925: 	    if (!$ip || length($ip) ne 4) {
                   6926: 		&logthis("Skipping host $id name $name no IP found\n");
                   6927: 		next;
                   6928: 	    }
                   6929: 	    $ip=inet_ntoa($ip);
                   6930: 	    $name_to_ip{$name} = $ip;
                   6931: 	} else {
                   6932: 	    $ip = $name_to_ip{$name};
1.598     albertel 6933: 	}
                   6934: 	push(@{$iphost{$ip}},$id);
                   6935:     }
                   6936:     return %iphost;
                   6937: }
                   6938: 
1.1       albertel 6939: # ------------------------------------------------------ Read spare server file
                   6940: {
1.448     albertel 6941:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 6942: 
                   6943:     while (my $configline=<$config>) {
                   6944:        chomp($configline);
1.284     matthew  6945:        if ($configline) {
1.1       albertel 6946:           $spareid{$configline}=1;
                   6947:        }
                   6948:     }
1.448     albertel 6949:     close($config);
1.1       albertel 6950: }
1.11      www      6951: # ------------------------------------------------------------ Read permissions
                   6952: {
1.448     albertel 6953:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      6954: 
                   6955:     while (my $configline=<$config>) {
1.448     albertel 6956: 	chomp($configline);
                   6957: 	if ($configline) {
                   6958: 	    my ($role,$perm)=split(/ /,$configline);
                   6959: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   6960: 	}
1.11      www      6961:     }
1.448     albertel 6962:     close($config);
1.11      www      6963: }
                   6964: 
                   6965: # -------------------------------------------- Read plain texts for permissions
                   6966: {
1.448     albertel 6967:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      6968: 
                   6969:     while (my $configline=<$config>) {
1.448     albertel 6970: 	chomp($configline);
                   6971: 	if ($configline) {
1.742     raeburn  6972: 	    my ($short,@plain)=split(/:/,$configline);
                   6973:             %{$prp{$short}} = ();
                   6974: 	    if (@plain > 0) {
                   6975:                 $prp{$short}{'std'} = $plain[0];
                   6976:                 for (my $i=1; $i<@plain; $i++) {
                   6977:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   6978:                 }
                   6979:             }
1.448     albertel 6980: 	}
1.135     www      6981:     }
1.448     albertel 6982:     close($config);
1.135     www      6983: }
                   6984: 
                   6985: # ---------------------------------------------------------- Read package table
                   6986: {
1.448     albertel 6987:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      6988: 
                   6989:     while (my $configline=<$config>) {
1.483     albertel 6990: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 6991: 	chomp($configline);
                   6992: 	my ($short,$plain)=split(/:/,$configline);
                   6993: 	my ($pack,$name)=split(/\&/,$short);
                   6994: 	if ($plain ne '') {
                   6995: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   6996: 	    $packagetab{$short}=$plain; 
                   6997: 	}
1.11      www      6998:     }
1.448     albertel 6999:     close($config);
1.329     matthew  7000: }
                   7001: 
                   7002: # ------------- set up temporary directory
                   7003: {
                   7004:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7005: 
1.11      www      7006: }
                   7007: 
1.599     albertel 7008: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7009: 
1.281     www      7010: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7011: $dumpcount=0;
1.22      www      7012: 
1.163     harris41 7013: &logtouch();
1.672     albertel 7014: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7015: $readit=1;
1.564     albertel 7016:     {
                   7017: 	use integer;
                   7018: 	my $test=(2**32)+1;
1.568     albertel 7019: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7020: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7021:     }
1.195     www      7022: }
1.1       albertel 7023: }
1.179     www      7024: 
1.1       albertel 7025: 1;
1.191     harris41 7026: __END__
                   7027: 
1.243     albertel 7028: =pod
                   7029: 
1.191     harris41 7030: =head1 NAME
                   7031: 
1.243     albertel 7032: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7033: 
                   7034: =head1 SYNOPSIS
                   7035: 
1.243     albertel 7036: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7037: 
                   7038:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7039: 
1.243     albertel 7040: Common parameters:
                   7041: 
                   7042: =over 4
                   7043: 
                   7044: =item *
                   7045: 
                   7046: $uname : an internal username (if $cname expecting a course Id specifically)
                   7047: 
                   7048: =item *
                   7049: 
                   7050: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7051: 
                   7052: =item *
                   7053: 
                   7054: $symb : a resource instance identifier
                   7055: 
                   7056: =item *
                   7057: 
                   7058: $namespace : the name of a .db file that contains the data needed or
                   7059: being set.
                   7060: 
                   7061: =back
                   7062: 
1.394     bowersj2 7063: =head1 OVERVIEW
1.191     harris41 7064: 
1.394     bowersj2 7065: lonnet provides subroutines which interact with the
                   7066: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7067: about classes, users, and resources.
1.243     albertel 7068: 
                   7069: For many of these objects you can also use this to store data about
                   7070: them or modify them in various ways.
1.191     harris41 7071: 
1.394     bowersj2 7072: =head2 Symbs
1.191     harris41 7073: 
1.394     bowersj2 7074: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7075: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7076: map, the resource number of the resource in the map, and the URL of
                   7077: the resource itself. The latter is somewhat redundant, but might help
                   7078: if maps change.
                   7079: 
                   7080: An example is
                   7081: 
                   7082:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7083: 
                   7084: The respective map entry is
                   7085: 
                   7086:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7087:   title="Problem 2">
                   7088:  </resource>
                   7089: 
                   7090: Symbs are used by the random number generator, as well as to store and
                   7091: restore data specific to a certain instance of for example a problem.
                   7092: 
                   7093: =head2 Storing And Retrieving Data
                   7094: 
                   7095: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7096: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7097: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7098: is is the non-critical message twin of cstore. These functions are for
                   7099: handlers to store a perl hash to a user's permanent data space in an
                   7100: easy manner, and to retrieve it again on another call. It is expected
                   7101: that a handler would use this once at the beginning to retrieve data,
                   7102: and then again once at the end to send only the new data back.
                   7103: 
                   7104: The data is stored in the user's data directory on the user's
                   7105: homeserver under the ID of the course.
                   7106: 
                   7107: The hash that is returned by restore will have all of the previous
                   7108: value for all of the elements of the hash.
                   7109: 
                   7110: Example:
                   7111: 
                   7112:  #creating a hash
                   7113:  my %hash;
                   7114:  $hash{'foo'}='bar';
                   7115: 
                   7116:  #storing it
                   7117:  &Apache::lonnet::cstore(\%hash);
                   7118: 
                   7119:  #changing a value
                   7120:  $hash{'foo'}='notbar';
                   7121: 
                   7122:  #adding a new value
                   7123:  $hash{'bar'}='foo';
                   7124:  &Apache::lonnet::cstore(\%hash);
                   7125: 
                   7126:  #retrieving the hash
                   7127:  my %history=&Apache::lonnet::restore();
                   7128: 
                   7129:  #print the hash
                   7130:  foreach my $key (sort(keys(%history))) {
                   7131:    print("\%history{$key} = $history{$key}");
                   7132:  }
                   7133: 
                   7134: Will print out:
1.191     harris41 7135: 
1.394     bowersj2 7136:  %history{1:foo} = bar
                   7137:  %history{1:keys} = foo:timestamp
                   7138:  %history{1:timestamp} = 990455579
                   7139:  %history{2:bar} = foo
                   7140:  %history{2:foo} = notbar
                   7141:  %history{2:keys} = foo:bar:timestamp
                   7142:  %history{2:timestamp} = 990455580
                   7143:  %history{bar} = foo
                   7144:  %history{foo} = notbar
                   7145:  %history{timestamp} = 990455580
                   7146:  %history{version} = 2
                   7147: 
                   7148: Note that the special hash entries C<keys>, C<version> and
                   7149: C<timestamp> were added to the hash. C<version> will be equal to the
                   7150: total number of versions of the data that have been stored. The
                   7151: C<timestamp> attribute will be the UNIX time the hash was
                   7152: stored. C<keys> is available in every historical section to list which
                   7153: keys were added or changed at a specific historical revision of a
                   7154: hash.
                   7155: 
                   7156: B<Warning>: do not store the hash that restore returns directly. This
                   7157: will cause a mess since it will restore the historical keys as if the
                   7158: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7159: 
1.394     bowersj2 7160: Calling convention:
1.191     harris41 7161: 
1.394     bowersj2 7162:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7163:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7164: 
1.394     bowersj2 7165: For more detailed information, see lonnet specific documentation.
1.191     harris41 7166: 
1.394     bowersj2 7167: =head1 RETURN MESSAGES
1.191     harris41 7168: 
1.394     bowersj2 7169: =over 4
1.191     harris41 7170: 
1.394     bowersj2 7171: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7172: 
1.394     bowersj2 7173: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7174: when the connection is brought back up
1.191     harris41 7175: 
1.394     bowersj2 7176: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7177: for later delivery
1.191     harris41 7178: 
1.394     bowersj2 7179: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7180: 
1.394     bowersj2 7181: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7182: that was requested
1.191     harris41 7183: 
1.243     albertel 7184: =back
1.191     harris41 7185: 
1.243     albertel 7186: =head1 PUBLIC SUBROUTINES
1.191     harris41 7187: 
1.243     albertel 7188: =head2 Session Environment Functions
1.191     harris41 7189: 
1.243     albertel 7190: =over 4
1.191     harris41 7191: 
1.394     bowersj2 7192: =item * 
                   7193: X<appenv()>
                   7194: B<appenv(%hash)>: the value of %hash is written to
                   7195: the user envirnoment file, and will be restored for each access this
1.620     albertel 7196: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7197: process
1.191     harris41 7198: 
                   7199: =item *
1.394     bowersj2 7200: X<delenv()>
                   7201: B<delenv($regexp)>: removes all items from the session
                   7202: environment file that matches the regular expression in $regexp. The
1.620     albertel 7203: values are also delted from the current processes %env.
1.191     harris41 7204: 
1.243     albertel 7205: =back
                   7206: 
                   7207: =head2 User Information
1.191     harris41 7208: 
1.243     albertel 7209: =over 4
1.191     harris41 7210: 
                   7211: =item *
1.394     bowersj2 7212: X<queryauthenticate()>
                   7213: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7214: authentication scheme
                   7215: 
                   7216: =item *
1.394     bowersj2 7217: X<authenticate()>
                   7218: B<authenticate($uname,$upass,$udom)>: try to
                   7219: authenticate user from domain's lib servers (first use the current
                   7220: one). C<$upass> should be the users password.
1.191     harris41 7221: 
                   7222: =item *
1.394     bowersj2 7223: X<homeserver()>
                   7224: B<homeserver($uname,$udom)>: find the server which has
                   7225: the user's directory and files (there must be only one), this caches
                   7226: the answer, and also caches if there is a borken connection.
1.191     harris41 7227: 
                   7228: =item *
1.394     bowersj2 7229: X<idget()>
                   7230: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7231: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7232: username, and only 1 username per ID in a specific domain) (returns
                   7233: hash: id=>name,id=>name)
1.191     harris41 7234: 
                   7235: =item *
1.394     bowersj2 7236: X<idrget()>
                   7237: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7238: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7239: 
                   7240: =item *
1.394     bowersj2 7241: X<idput()>
                   7242: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7243: 
                   7244: =item *
1.394     bowersj2 7245: X<rolesinit()>
                   7246: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7247: 
                   7248: =item *
1.551     albertel 7249: X<getsection()>
                   7250: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7251: course $cname, return section name/number or '' for "not in course"
                   7252: and '-1' for "no section"
                   7253: 
                   7254: =item *
1.394     bowersj2 7255: X<userenvironment()>
                   7256: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7257: passed in @what from the requested user's environment, returns a hash
                   7258: 
                   7259: =back
                   7260: 
                   7261: =head2 User Roles
                   7262: 
                   7263: =over 4
                   7264: 
                   7265: =item *
                   7266: 
                   7267: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7268: actions
                   7269:  F: full access
                   7270:  U,I,K: authentication modes (cxx only)
                   7271:  '': forbidden
                   7272:  1: user needs to choose course
                   7273:  2: browse allowed
                   7274: 
                   7275: =item *
                   7276: 
                   7277: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7278: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7279: and course level
                   7280: 
                   7281: =item *
                   7282: 
                   7283: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7284: explanation of a user role term
                   7285: 
                   7286: =back
                   7287: 
                   7288: =head2 User Modification
                   7289: 
                   7290: =over 4
                   7291: 
                   7292: =item *
                   7293: 
                   7294: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7295: user for the level given by URL.  Optional start and end dates (leave empty
                   7296: string or zero for "no date")
1.191     harris41 7297: 
                   7298: =item *
                   7299: 
1.243     albertel 7300: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7301: change a users, password, possible return values are: ok,
                   7302: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7303: refused
1.191     harris41 7304: 
                   7305: =item *
                   7306: 
1.243     albertel 7307: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7308: 
                   7309: =item *
                   7310: 
1.243     albertel 7311: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7312: modify user
1.191     harris41 7313: 
                   7314: =item *
                   7315: 
1.286     matthew  7316: modifystudent
                   7317: 
                   7318: modify a students enrollment and identification information.
                   7319: The course id is resolved based on the current users environment.  
                   7320: This means the envoking user must be a course coordinator or otherwise
                   7321: associated with a course.
                   7322: 
1.297     matthew  7323: This call is essentially a wrapper for lonnet::modifyuser and
                   7324: lonnet::modify_student_enrollment
1.286     matthew  7325: 
                   7326: Inputs: 
                   7327: 
                   7328: =over 4
                   7329: 
                   7330: =item B<$udom> Students loncapa domain
                   7331: 
                   7332: =item B<$uname> Students loncapa login name
                   7333: 
                   7334: =item B<$uid> Students id/student number
                   7335: 
                   7336: =item B<$umode> Students authentication mode
                   7337: 
                   7338: =item B<$upass> Students password
                   7339: 
                   7340: =item B<$first> Students first name
                   7341: 
                   7342: =item B<$middle> Students middle name
                   7343: 
                   7344: =item B<$last> Students last name
                   7345: 
                   7346: =item B<$gene> Students generation
                   7347: 
                   7348: =item B<$usec> Students section in course
                   7349: 
                   7350: =item B<$end> Unix time of the roles expiration
                   7351: 
                   7352: =item B<$start> Unix time of the roles start date
                   7353: 
                   7354: =item B<$forceid> If defined, allow $uid to be changed
                   7355: 
                   7356: =item B<$desiredhome> server to use as home server for student
                   7357: 
                   7358: =back
1.297     matthew  7359: 
                   7360: =item *
                   7361: 
                   7362: modify_student_enrollment
                   7363: 
                   7364: Change a students enrollment status in a class.  The environment variable
                   7365: 'role.request.course' must be defined for this function to proceed.
                   7366: 
                   7367: Inputs:
                   7368: 
                   7369: =over 4
                   7370: 
                   7371: =item $udom, students domain
                   7372: 
                   7373: =item $uname, students name
                   7374: 
                   7375: =item $uid, students user id
                   7376: 
                   7377: =item $first, students first name
                   7378: 
                   7379: =item $middle
                   7380: 
                   7381: =item $last
                   7382: 
                   7383: =item $gene
                   7384: 
                   7385: =item $usec
                   7386: 
                   7387: =item $end
                   7388: 
                   7389: =item $start
                   7390: 
                   7391: =back
                   7392: 
1.191     harris41 7393: 
                   7394: =item *
                   7395: 
1.243     albertel 7396: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7397: custom role; give a custom role to a user for the level given by URL.  Specify
                   7398: name and domain of role author, and role name
1.191     harris41 7399: 
                   7400: =item *
                   7401: 
1.243     albertel 7402: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7403: 
                   7404: =item *
                   7405: 
1.243     albertel 7406: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7407: 
                   7408: =back
                   7409: 
                   7410: =head2 Course Infomation
                   7411: 
                   7412: =over 4
1.191     harris41 7413: 
                   7414: =item *
                   7415: 
1.631     albertel 7416: coursedescription($courseid) : returns a hash of information about the
                   7417: specified course id, including all environment settings for the
                   7418: course, the description of the course will be in the hash under the
                   7419: key 'description'
1.191     harris41 7420: 
                   7421: =item *
                   7422: 
1.624     albertel 7423: resdata($name,$domain,$type,@which) : request for current parameter
                   7424: setting for a specific $type, where $type is either 'course' or 'user',
                   7425: @what should be a list of parameters to ask about. This routine caches
                   7426: answers for 5 minutes.
1.243     albertel 7427: 
                   7428: =back
                   7429: 
                   7430: =head2 Course Modification
                   7431: 
                   7432: =over 4
1.191     harris41 7433: 
                   7434: =item *
                   7435: 
1.243     albertel 7436: writecoursepref($courseid,%prefs) : write preferences (environment
                   7437: database) for a course
1.191     harris41 7438: 
                   7439: =item *
                   7440: 
1.243     albertel 7441: createcourse($udom,$description,$url) : make/modify course
                   7442: 
                   7443: =back
                   7444: 
                   7445: =head2 Resource Subroutines
                   7446: 
                   7447: =over 4
1.191     harris41 7448: 
                   7449: =item *
                   7450: 
1.243     albertel 7451: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7452: 
                   7453: =item *
                   7454: 
1.243     albertel 7455: repcopy($filename) : subscribes to the requested file, and attempts to
                   7456: replicate from the owning library server, Might return
1.607     raeburn  7457: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7458: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7459: resource. Expects the local filesystem pathname
                   7460: (/home/httpd/html/res/....)
                   7461: 
                   7462: =back
                   7463: 
                   7464: =head2 Resource Information
                   7465: 
                   7466: =over 4
1.191     harris41 7467: 
                   7468: =item *
                   7469: 
1.243     albertel 7470: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7471: a vairety of different possible values, $varname should be a request
                   7472: string, and the other parameters can be used to specify who and what
                   7473: one is asking about.
                   7474: 
                   7475: Possible values for $varname are environment.lastname (or other item
                   7476: from the envirnment hash), user.name (or someother aspect about the
                   7477: user), resource.0.maxtries (or some other part and parameter of a
                   7478: resource)
1.204     albertel 7479: 
                   7480: =item *
                   7481: 
1.243     albertel 7482: directcondval($number) : get current value of a condition; reads from a state
                   7483: string
1.204     albertel 7484: 
                   7485: =item *
                   7486: 
1.243     albertel 7487: condval($condidx) : value of condition index based on state
1.204     albertel 7488: 
                   7489: =item *
                   7490: 
1.243     albertel 7491: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7492: resource's metadata, $what should be either a specific key, or either
                   7493: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7494: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7495: 
                   7496: this function automatically caches all requests
1.191     harris41 7497: 
                   7498: =item *
                   7499: 
1.243     albertel 7500: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7501: network of library servers; returns file handle of where SQL and regex results
                   7502: will be stored for query
1.191     harris41 7503: 
                   7504: =item *
                   7505: 
1.243     albertel 7506: symbread($filename) : return symbolic list entry (filename argument optional);
                   7507: returns the data handle
1.191     harris41 7508: 
                   7509: =item *
                   7510: 
1.243     albertel 7511: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7512: a possible symb for the URL in $thisfn, and if is an encryypted
                   7513: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7514: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7515: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7516: 
1.191     harris41 7517: 
                   7518: =item *
                   7519: 
1.243     albertel 7520: symbclean($symb) : removes versions numbers from a symb, returns the
                   7521: cleaned symb
1.191     harris41 7522: 
                   7523: =item *
                   7524: 
1.243     albertel 7525: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7526: course map, user must be in a course for it to work.
1.191     harris41 7527: 
                   7528: =item *
                   7529: 
1.243     albertel 7530: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7531: 
                   7532: =item *
                   7533: 
1.243     albertel 7534: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7535: a random seed, all arguments are optional, if they aren't sent it uses the
                   7536: environment to derive them. Note: if symb isn't sent and it can't get one
                   7537: from &symbread it will use the current time as its return value
1.191     harris41 7538: 
                   7539: =item *
                   7540: 
1.243     albertel 7541: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7542: unfakeable, receipt
1.191     harris41 7543: 
                   7544: =item *
                   7545: 
1.620     albertel 7546: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7547: 
                   7548: =item *
                   7549: 
1.243     albertel 7550: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7551: 
                   7552: =item *
                   7553: 
1.243     albertel 7554: 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 7555: 
                   7556: =item *
                   7557: 
1.243     albertel 7558: 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 7559: 
                   7560: =item *
                   7561: 
1.243     albertel 7562: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7563: 
                   7564: =item *
                   7565: 
1.243     albertel 7566: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7567: forcing spreadsheet to reevaluate the resource scores next time.
                   7568: 
                   7569: =back
                   7570: 
                   7571: =head2 Storing/Retreiving Data
                   7572: 
                   7573: =over 4
1.191     harris41 7574: 
                   7575: =item *
                   7576: 
1.243     albertel 7577: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7578: for this url; hashref needs to be given and should be a \%hashname; the
                   7579: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7580: be derived from the env
1.191     harris41 7581: 
                   7582: =item *
                   7583: 
1.243     albertel 7584: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7585: uses critical subroutine
1.191     harris41 7586: 
                   7587: =item *
                   7588: 
1.243     albertel 7589: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7590: all args are optional
1.191     harris41 7591: 
                   7592: =item *
                   7593: 
1.717     albertel 7594: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7595: dumps the complete (or key matching regexp) namespace into a hash
                   7596: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7597: normally &store()ed into
                   7598: 
                   7599: $range should be either an integer '100' (give me the first 100
                   7600:                                            matching records)
                   7601:               or be  two integers sperated by a - with no spaces
                   7602:                  '30-50' (give me the 30th through the 50th matching
                   7603:                           records)
                   7604: 
                   7605: 
                   7606: =item *
                   7607: 
                   7608: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7609: replaces a &store() version of data with a replacement set of data
                   7610: for a particular resource in a namespace passed in the $storehash hash 
                   7611: reference
                   7612: 
                   7613: =item *
                   7614: 
1.243     albertel 7615: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7616: works very similar to store/cstore, but all data is stored in a
                   7617: temporary location and can be reset using tmpreset, $storehash should
                   7618: be a hash reference, returns nothing on success
1.191     harris41 7619: 
                   7620: =item *
                   7621: 
1.243     albertel 7622: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7623: similar to restore, but all data is stored in a temporary location and
                   7624: can be reset using tmpreset. Returns a hash of values on success,
                   7625: error string otherwise.
1.191     harris41 7626: 
                   7627: =item *
                   7628: 
1.243     albertel 7629: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7630: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7631: 
                   7632: =item *
                   7633: 
1.243     albertel 7634: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7635: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7636: 
                   7637: =item *
                   7638: 
1.243     albertel 7639: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7640: namesp ($udom and $uname are optional)
1.191     harris41 7641: 
                   7642: =item *
                   7643: 
1.702     albertel 7644: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7645: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7646: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7647: 
1.702     albertel 7648: $range should be either an integer '100' (give me the first 100
                   7649:                                            matching records)
                   7650:               or be  two integers sperated by a - with no spaces
                   7651:                  '30-50' (give me the 30th through the 50th matching
                   7652:                           records)
1.449     matthew  7653: =item *
                   7654: 
                   7655: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7656: $store can be a scalar, an array reference, or if the amount to be 
                   7657: incremented is > 1, a hash reference.
                   7658: 
                   7659: ($udom and $uname are optional)
1.191     harris41 7660: 
                   7661: =item *
                   7662: 
1.243     albertel 7663: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7664: ($udom and $uname are optional)
1.191     harris41 7665: 
                   7666: =item *
                   7667: 
1.243     albertel 7668: cput($namespace,$storehash,$udom,$uname) : critical put
                   7669: ($udom and $uname are optional)
1.191     harris41 7670: 
                   7671: =item *
                   7672: 
1.748     albertel 7673: newput($namespace,$storehash,$udom,$uname) :
                   7674: 
                   7675: Attempts to store the items in the $storehash, but only if they don't
                   7676: currently exist, if this succeeds you can be certain that you have 
                   7677: successfully created a new key value pair in the $namespace db.
                   7678: 
                   7679: 
                   7680: Args:
                   7681:  $namespace: name of database to store values to
                   7682:  $storehash: hashref to store to the db
                   7683:  $udom: (optional) domain of user containing the db
                   7684:  $uname: (optional) name of user caontaining the db
                   7685: 
                   7686: Returns:
                   7687:  'ok' -> succeeded in storing all keys of $storehash
                   7688:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7689:                         least <key> already existed in the db (other
                   7690:                         requested keys may also already exist)
                   7691:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7692:  'con_lost' -> unable to contact request server
                   7693:  'refused' -> action was not allowed by remote machine
                   7694: 
                   7695: 
                   7696: =item *
                   7697: 
1.243     albertel 7698: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7699: reference filled in from namesp (encrypts the return communication)
                   7700: ($udom and $uname are optional)
1.191     harris41 7701: 
                   7702: =item *
                   7703: 
1.243     albertel 7704: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7705: critical subroutine
                   7706: 
                   7707: =back
                   7708: 
                   7709: =head2 Network Status Functions
                   7710: 
                   7711: =over 4
1.191     harris41 7712: 
                   7713: =item *
                   7714: 
                   7715: dirlist($uri) : return directory list based on URI
                   7716: 
                   7717: =item *
                   7718: 
1.243     albertel 7719: spareserver() : find server with least workload from spare.tab
                   7720: 
                   7721: =back
                   7722: 
                   7723: =head2 Apache Request
                   7724: 
                   7725: =over 4
1.191     harris41 7726: 
                   7727: =item *
                   7728: 
1.243     albertel 7729: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7730: localhost, posts hash
                   7731: 
                   7732: =back
                   7733: 
                   7734: =head2 Data to String to Data
                   7735: 
                   7736: =over 4
1.191     harris41 7737: 
                   7738: =item *
                   7739: 
1.243     albertel 7740: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7741: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7742: 
                   7743: =item *
                   7744: 
1.243     albertel 7745: hashref2str($hashref) : convert a hashref into a string complete with
                   7746: escaping and '=' and '&' separators, supports elements that are
                   7747: arrayrefs and hashrefs
1.191     harris41 7748: 
                   7749: =item *
                   7750: 
1.243     albertel 7751: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7752: with escaping and '&' separators, supports elements that are arrayrefs
                   7753: and hashrefs
1.191     harris41 7754: 
                   7755: =item *
                   7756: 
1.243     albertel 7757: str2hash($string) : convert string to hash using unescaping and
                   7758: splitting on '=' and '&', supports elements that are arrayrefs and
                   7759: hashrefs
1.191     harris41 7760: 
                   7761: =item *
                   7762: 
1.243     albertel 7763: str2array($string) : convert string to hash using unescaping and
                   7764: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7765: 
                   7766: =back
                   7767: 
                   7768: =head2 Logging Routines
                   7769: 
                   7770: =over 4
                   7771: 
                   7772: These routines allow one to make log messages in the lonnet.log and
                   7773: lonnet.perm logfiles.
1.191     harris41 7774: 
                   7775: =item *
                   7776: 
1.243     albertel 7777: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 7778: 
                   7779: =item *
                   7780: 
1.243     albertel 7781: logthis() : append message to the normal lonnet.log file, it gets
                   7782: preiodically rolled over and deleted.
1.191     harris41 7783: 
                   7784: =item *
                   7785: 
1.243     albertel 7786: logperm() : append a permanent message to lonnet.perm.log, this log
                   7787: file never gets deleted by any automated portion of the system, only
                   7788: messages of critical importance should go in here.
                   7789: 
                   7790: =back
                   7791: 
                   7792: =head2 General File Helper Routines
                   7793: 
                   7794: =over 4
1.191     harris41 7795: 
                   7796: =item *
                   7797: 
1.481     raeburn  7798: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7799: (a) files in /uploaded
                   7800:   (i) If a local copy of the file exists - 
                   7801:       compares modification date of local copy with last-modified date for 
                   7802:       definitive version stored on home server for course. If local copy is 
                   7803:       stale, requests a new version from the home server and stores it. 
                   7804:       If the original has been removed from the home server, then local copy 
                   7805:       is unlinked.
                   7806:   (ii) If local copy does not exist -
                   7807:       requests the file from the home server and stores it. 
                   7808:   
                   7809:   If $caller is 'uploadrep':  
                   7810:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7811:     for request for files originally uploaded via DOCS. 
                   7812:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7813:   
                   7814:   Otherwise:
                   7815:      This indicates a call from the content generation phase of the request.
                   7816:      -  returns the entire contents of the file or -1.
                   7817:      
                   7818: (b) files in /res
                   7819:    - returns the entire contents of a file or -1; 
                   7820:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7821: 
1.712     albertel 7822: 
                   7823: =item *
                   7824: 
                   7825: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   7826:                   reference
                   7827: 
                   7828: returns either a stat() list of data about the file or an empty list
                   7829: if the file doesn't exist or couldn't find out about it (connection
                   7830: problems or user unknown)
                   7831: 
1.191     harris41 7832: =item *
                   7833: 
1.243     albertel 7834: filelocation($dir,$file) : returns file system location of a file
                   7835: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7836: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7837: and a file of ../bob will become /a/bob)
1.191     harris41 7838: 
                   7839: =item *
                   7840: 
                   7841: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7842: filelocation except for hrefs
                   7843: 
                   7844: =item *
                   7845: 
                   7846: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7847: 
1.243     albertel 7848: =back
                   7849: 
1.608     albertel 7850: =head2 Usererfile file routines (/uploaded*)
                   7851: 
                   7852: =over 4
                   7853: 
                   7854: =item *
                   7855: 
                   7856: userfileupload(): main rotine for putting a file in a user or course's
                   7857:                   filespace, arguments are,
                   7858: 
1.620     albertel 7859:  formname - required - this is the name of the element in $env where the
1.608     albertel 7860:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7861:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7862:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7863:  coursedoc - if true, store the file in the course of the active role
                   7864:              of the current user
                   7865:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7866:          if undefined, it will be placed in "unknown"
                   7867: 
                   7868:  (This routine calls clean_filename() to remove any dangerous
                   7869:  characters from the filename, and then calls finuserfileupload() to
                   7870:  complete the transaction)
                   7871: 
                   7872:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7873:  and /adm/notfound.html if unsuccessful
                   7874: 
                   7875: =item *
                   7876: 
                   7877: clean_filename(): routine for cleaing a filename up for storage in
                   7878:                  userfile space, argument is:
                   7879: 
                   7880:  filename - proposed filename
                   7881: 
                   7882: returns: the new clean filename
                   7883: 
                   7884: =item *
                   7885: 
                   7886: finishuserfileupload(): routine that creaes and sends the file to
                   7887: userspace, probably shouldn't be called directly
                   7888: 
                   7889:   docuname: username or courseid of destination for the file
                   7890:   docudom: domain of user/course of destination for the file
                   7891:   formname: same as for userfileupload()
                   7892:   fname: filename (inculding subdirectories) for the file
                   7893: 
                   7894:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7895:  and /adm/notfound.html if unsuccessful
                   7896: 
                   7897: =item *
                   7898: 
                   7899: renameuserfile(): renames an existing userfile to a new name
                   7900: 
                   7901:   Args:
                   7902:    docuname: username or courseid of destination for the file
                   7903:    docudom: domain of user/course of destination for the file
                   7904:    old: current file name (including any subdirs under userfiles)
                   7905:    new: desired file name (including any subdirs under userfiles)
                   7906: 
                   7907: =item *
                   7908: 
                   7909: mkdiruserfile(): creates a directory is a userfiles dir
                   7910: 
                   7911:   Args:
                   7912:    docuname: username or courseid of destination for the file
                   7913:    docudom: domain of user/course of destination for the file
                   7914:    dir: dir to create (including any subdirs under userfiles)
                   7915: 
                   7916: =item *
                   7917: 
                   7918: removeuserfile(): removes a file that exists in userfiles
                   7919: 
                   7920:   Args:
                   7921:    docuname: username or courseid of destination for the file
                   7922:    docudom: domain of user/course of destination for the file
                   7923:    fname: filname to delete (including any subdirs under userfiles)
                   7924: 
                   7925: =item *
                   7926: 
                   7927: removeuploadedurl(): convience function for removeuserfile()
                   7928: 
                   7929:   Args:
                   7930:    url:  a full /uploaded/... url to delete
                   7931: 
1.747     albertel 7932: =item * 
                   7933: 
                   7934: get_portfile_permissions():
                   7935:   Args:
                   7936:     domain: domain of user or course contain the portfolio files
                   7937:     user: name of user or num of course contain the portfolio files
                   7938:   Returns:
                   7939:     hashref of a dump of the proper file_permissions.db
                   7940:    
                   7941: 
                   7942: =item * 
                   7943: 
                   7944: get_access_controls():
                   7945: 
                   7946: Args:
                   7947:   current_permissions: the hash ref returned from get_portfile_permissions()
                   7948:   group: (optional) the group you want the files associated with
                   7949:   file: (optional) the file you want access info on
                   7950: 
                   7951: Returns:
1.749     raeburn  7952:     a hash (keys are file names) of hashes containing
                   7953:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   7954:         values are XML containing access control settings (see below) 
1.747     albertel 7955: 
                   7956: Internal notes:
                   7957: 
1.749     raeburn  7958:  access controls are stored in file_permissions.db as key=value pairs.
                   7959:     key -> path to file/file_name\0uniqueID:scope_end_start
                   7960:         where scope -> public,guest,course,group,domains or users.
                   7961:               end -> UNIX time for end of access (0 -> no end date)
                   7962:               start -> UNIX time for start of access
                   7963: 
                   7964:     value -> XML description of access control
                   7965:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   7966:             <start></start>
                   7967:             <end></end>
                   7968: 
                   7969:             <password></password>  for scope type = guest
                   7970: 
                   7971:             <domain></domain>     for scope type = course or group
                   7972:             <number></number>
                   7973:             <roles id="">
                   7974:              <role></role>
                   7975:              <access></access>
                   7976:              <section></section>
                   7977:              <group></group>
                   7978:             </roles>
                   7979: 
                   7980:             <dom></dom>         for scope type = domains
                   7981: 
                   7982:             <users>             for scope type = users
                   7983:              <user>
                   7984:               <uname></uname>
                   7985:               <udom></udom>
                   7986:              </user>
                   7987:             </users>
                   7988:            </scope> 
                   7989:               
                   7990:  Access data is also aggregated for each file in an additional key=value pair:
                   7991:  key -> path to file/file_name\0accesscontrol 
                   7992:  value -> reference to hash
                   7993:           hash contains key = value pairs
                   7994:           where key = uniqueID:scope_end_start
                   7995:                 value = UNIX time record was last updated
                   7996: 
                   7997:           Used to improve speed of look-ups of access controls for each file.  
                   7998:  
                   7999:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8000: 
                   8001: parse_access_controls():
                   8002: 
                   8003: Parses XML of an access control record
                   8004: Args
                   8005: 1. Text string (XML) of access comtrol record
                   8006: 
                   8007: Returns:
                   8008: 1. Hash of access control settings. 
                   8009: 
                   8010: modify_access_controls():
                   8011: 
                   8012: Modifies access controls for a portfolio file
                   8013: Args
                   8014: 1. file name
                   8015: 2. reference to hash of required changes,
                   8016: 3. domain
                   8017: 4. username
                   8018:   where domain,username are the domain of the portfolio owner 
                   8019:   (either a user or a course) 
                   8020: 
                   8021: Returns:
                   8022: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8023: 2. result of deletions ('ok' or 'error', with error message).
                   8024: 3. reference to hash of any new or updated access controls.
                   8025: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8026:    key = integer (inbound ID)
                   8027:    value = uniqueID  
1.747     albertel 8028: 
1.608     albertel 8029: =back
                   8030: 
1.243     albertel 8031: =head2 HTTP Helper Routines
                   8032: 
                   8033: =over 4
                   8034: 
1.191     harris41 8035: =item *
                   8036: 
                   8037: escape() : unpack non-word characters into CGI-compatible hex codes
                   8038: 
                   8039: =item *
                   8040: 
                   8041: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8042: 
1.243     albertel 8043: =back
                   8044: 
                   8045: =head1 PRIVATE SUBROUTINES
                   8046: 
                   8047: =head2 Underlying communication routines (Shouldn't call)
                   8048: 
                   8049: =over 4
                   8050: 
                   8051: =item *
                   8052: 
                   8053: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8054: 
                   8055: =item *
                   8056: 
                   8057: reply() : uses subreply to send a message to remote machine, logs all failures
                   8058: 
                   8059: =item *
                   8060: 
                   8061: critical() : passes a critical message to another server; if cannot
                   8062: get through then place message in connection buffer directory and
                   8063: returns con_delayed, if incapable of saving message, returns
                   8064: con_failed
                   8065: 
                   8066: =item *
                   8067: 
                   8068: reconlonc() : tries to reconnect lonc client processes.
                   8069: 
                   8070: =back
                   8071: 
                   8072: =head2 Resource Access Logging
                   8073: 
                   8074: =over 4
                   8075: 
                   8076: =item *
                   8077: 
                   8078: flushcourselogs() : flush (save) buffer logs and access logs
                   8079: 
                   8080: =item *
                   8081: 
                   8082: courselog($what) : save message for course in hash
                   8083: 
                   8084: =item *
                   8085: 
                   8086: courseacclog($what) : save message for course using &courselog().  Perform
                   8087: special processing for specific resource types (problems, exams, quizzes, etc).
                   8088: 
1.191     harris41 8089: =item *
                   8090: 
                   8091: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8092: as a PerlChildExitHandler
1.243     albertel 8093: 
                   8094: =back
                   8095: 
                   8096: =head2 Other
                   8097: 
                   8098: =over 4
                   8099: 
                   8100: =item *
                   8101: 
                   8102: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8103: 
                   8104: =back
                   8105: 
                   8106: =cut

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