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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.907   ! albertel    4: # $Id: lonnet.pm,v 1.906 2007/08/10 23:02:36 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.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.891     albertel  217:     my ($lonid) = @_;
                    218:     my $hostname = &hostname($lonid);
                    219:     if ($lonid) {
                    220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    221: 	if ($hostname && -e $peerfile) {
                    222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    224: 					     Type    => SOCK_STREAM,
                    225: 					     Timeout => 10);
                    226: 	    if ($client) {
                    227: 		print $client ("reset_retries\n");
                    228: 		my $answer=<$client>;
                    229: 		#reset just this one.
                    230: 	    }
                    231: 	}
                    232: 	return;
                    233:     }
                    234: 
1.836     www       235:     &logthis("Trying to reconnect lonc");
1.1       albertel  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  237:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  238: 	my $loncpid=<$fh>;
                    239:         chomp($loncpid);
                    240:         if (kill 0 => $loncpid) {
                    241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    242:             kill USR1 => $loncpid;
                    243:             sleep 1;
1.836     www       244:          } else {
1.12      www       245: 	    &logthis(
1.672     albertel  246:                "<font color=\"blue\">WARNING:".
1.12      www       247:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  248:         }
                    249:     } else {
1.836     www       250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  251:     }
                    252: }
                    253: 
                    254: # ------------------------------------------------------ Critical communication
1.12      www       255: 
1.1       albertel  256: sub critical {
                    257:     my ($cmd,$server)=@_;
1.838     albertel  258:     unless (&hostname($server)) {
1.672     albertel  259:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       260:                " Critical message to unknown server ($server)</font>");
                    261:         return 'no_such_host';
                    262:     }
1.1       albertel  263:     my $answer=reply($cmd,$server);
                    264:     if ($answer eq 'con_lost') {
                    265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  266: 	my $answer=reply($cmd,$server);
1.1       albertel  267:         if ($answer eq 'con_lost') {
                    268:             my $now=time;
                    269:             my $middlename=$cmd;
1.5       www       270:             $middlename=substr($middlename,0,16);
1.1       albertel  271:             $middlename=~s/\W//g;
                    272:             my $dfilename=
1.305     www       273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    274:             $dumpcount++;
1.1       albertel  275:             {
1.448     albertel  276: 		my $dfh;
                    277: 		if (open($dfh,">$dfilename")) {
                    278: 		    print $dfh "$cmd\n"; 
                    279: 		    close($dfh);
                    280: 		}
1.1       albertel  281:             }
                    282:             sleep 2;
                    283:             my $wcmd='';
                    284:             {
1.448     albertel  285: 		my $dfh;
                    286: 		if (open($dfh,"<$dfilename")) {
                    287: 		    $wcmd=<$dfh>; 
                    288: 		    close($dfh);
                    289: 		}
1.1       albertel  290:             }
                    291:             chomp($wcmd);
1.7       www       292:             if ($wcmd eq $cmd) {
1.672     albertel  293: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       294:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  295:                 &logperm("D:$server:$cmd");
                    296: 	        return 'con_delayed';
                    297:             } else {
1.672     albertel  298:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       299:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  300:                 &logperm("F:$server:$cmd");
                    301:                 return 'con_failed';
                    302:             }
                    303:         }
                    304:     }
                    305:     return $answer;
1.405     albertel  306: }
                    307: 
1.755     albertel  308: # ------------------------------------------- check if return value is an error
                    309: 
                    310: sub error {
                    311:     my ($result) = @_;
1.756     albertel  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  313: 	if ($2 == 2) { return undef; }
                    314: 	return $1;
                    315:     }
                    316:     return undef;
                    317: }
                    318: 
1.783     albertel  319: sub convert_and_load_session_env {
                    320:     my ($lonidsdir,$handle)=@_;
                    321:     my @profile;
                    322:     {
                    323: 	open(my $idf,"$lonidsdir/$handle.id");
                    324: 	flock($idf,LOCK_SH);
                    325: 	@profile=<$idf>;
                    326: 	close($idf);
                    327:     }
                    328:     my %temp_env;
                    329:     foreach my $line (@profile) {
1.786     albertel  330: 	if ($line !~ m/=/) {
                    331: 	    return 0;
                    332: 	}
1.783     albertel  333: 	chomp($line);
                    334: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    335: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    336:     }
                    337:     unlink("$lonidsdir/$handle.id");
                    338:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    339: 	    0640)) {
                    340: 	%disk_env = %temp_env;
                    341: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    342: 	untie(%disk_env);
                    343:     }
1.786     albertel  344:     return 1;
1.783     albertel  345: }
                    346: 
1.374     www       347: # ------------------------------------------- Transfer profile into environment
1.780     albertel  348: my $env_loaded;
                    349: sub transfer_profile_to_env {
1.788     albertel  350:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    351:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       352: 
1.720     albertel  353:     if (!defined($lonidsdir)) {
                    354: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    355:     }
                    356:     if (!defined($handle)) {
                    357:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    358:     }
                    359: 
1.786     albertel  360:     my $convert;
                    361:     {
                    362:     	open(my $idf,"$lonidsdir/$handle.id");
                    363: 	flock($idf,LOCK_SH);
                    364: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    365: 		&GDBM_READER(),0640)) {
                    366: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    367: 	    untie(%disk_env);
                    368: 	} else {
                    369: 	    $convert = 1;
                    370: 	}
                    371:     }
                    372:     if ($convert) {
                    373: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    374: 	    &logthis("Failed to load session, or convert session.");
                    375: 	}
1.374     www       376:     }
1.783     albertel  377: 
1.786     albertel  378:     my %remove;
1.783     albertel  379:     while ( my $envname = each(%env) ) {
1.433     matthew   380:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    381:             if ($time < time-300) {
1.783     albertel  382:                 $remove{$key}++;
1.433     matthew   383:             }
                    384:         }
                    385:     }
1.783     albertel  386: 
1.619     albertel  387:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  388:     $env_loaded=1;
1.783     albertel  389:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   390:         &delenv($expired_key);
1.374     www       391:     }
1.1       albertel  392: }
                    393: 
1.830     albertel  394: sub timed_flock {
                    395:     my ($file,$lock_type) = @_;
                    396:     my $failed=0;
                    397:     eval {
                    398: 	local $SIG{__DIE__}='DEFAULT';
                    399: 	local $SIG{ALRM}=sub {
                    400: 	    $failed=1;
                    401: 	    die("failed lock");
                    402: 	};
                    403: 	alarm(13);
                    404: 	flock($file,$lock_type);
                    405: 	alarm(0);
                    406:     };
                    407:     if ($failed) {
                    408: 	return undef;
                    409:     } else {
                    410: 	return 1;
                    411:     }
                    412: }
                    413: 
1.5       www       414: # ---------------------------------------------------------- Append Environment
                    415: 
                    416: sub appenv {
1.6       www       417:     my %newenv=@_;
1.692     albertel  418:     foreach my $key (keys(%newenv)) {
                    419: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  420:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  421:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       422:                 .'</font>');
1.692     albertel  423: 	    delete($newenv{$key});
1.35      www       424:         } else {
1.692     albertel  425:             $env{$key}=$newenv{$key};
1.35      www       426:         }
1.191     harris41  427:     }
1.830     albertel  428:     open(my $env_file,$env{'user.environment'});
                    429:     if (&timed_flock($env_file,LOCK_EX)
                    430: 	&&
                    431: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    432: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  433: 	while (my ($key,$value) = each(%newenv)) {
                    434: 	    $disk_env{$key} = $value;
1.448     albertel  435: 	}
1.783     albertel  436: 	untie(%disk_env);
1.56      www       437:     }
                    438:     return 'ok';
                    439: }
                    440: # ----------------------------------------------------- Delete from Environment
                    441: 
                    442: sub delenv {
                    443:     my $delthis=shift;
                    444:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  445:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       446:                 "Attempt to delete from environment ".$delthis);
                    447:         return 'error';
                    448:     }
1.830     albertel  449:     open(my $env_file,$env{'user.environment'});
                    450:     if (&timed_flock($env_file,LOCK_EX)
                    451: 	&&
                    452: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    453: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  454: 	foreach my $key (keys(%disk_env)) {
                    455: 	    if ($key=~/^$delthis/) { 
1.619     albertel  456:                 delete($env{$key});
1.783     albertel  457:                 delete($disk_env{$key});
1.473     matthew   458:             }
1.448     albertel  459: 	}
1.783     albertel  460: 	untie(%disk_env);
1.5       www       461:     }
                    462:     return 'ok';
1.369     albertel  463: }
                    464: 
1.790     albertel  465: sub get_env_multiple {
                    466:     my ($name) = @_;
                    467:     my @values;
                    468:     if (defined($env{$name})) {
                    469:         # exists is it an array
                    470:         if (ref($env{$name})) {
                    471:             @values=@{ $env{$name} };
                    472:         } else {
                    473:             $values[0]=$env{$name};
                    474:         }
                    475:     }
                    476:     return(@values);
                    477: }
                    478: 
1.369     albertel  479: # ------------------------------------------ Find out current server userload
                    480: # there is a copy in lond
                    481: sub userload {
                    482:     my $numusers=0;
                    483:     {
                    484: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    485: 	my $filename;
                    486: 	my $curtime=time;
                    487: 	while ($filename=readdir(LONIDS)) {
                    488: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  489: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  490: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  491: 	}
                    492: 	closedir(LONIDS);
                    493:     }
                    494:     my $userloadpercent=0;
                    495:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    496:     if ($maxuserload) {
1.371     albertel  497: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  498:     }
1.372     albertel  499:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  500:     return $userloadpercent;
1.283     www       501: }
                    502: 
                    503: # ------------------------------------------ Fight off request when overloaded
                    504: 
                    505: sub overloaderror {
                    506:     my ($r,$checkserver)=@_;
                    507:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    508:     my $loadavg;
                    509:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  510:        open(my $loadfile,'/proc/loadavg');
1.283     www       511:        $loadavg=<$loadfile>;
                    512:        $loadavg =~ s/\s.*//g;
1.285     matthew   513:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  514:        close($loadfile);
1.283     www       515:     } else {
                    516:        $loadavg=&reply('load',$checkserver);
                    517:     }
1.285     matthew   518:     my $overload=$loadavg-100;
1.283     www       519:     if ($overload>0) {
1.285     matthew   520: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       521:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       522:         return 413;
1.283     www       523:     }    
                    524:     return '';
1.5       www       525: }
1.1       albertel  526: 
                    527: # ------------------------------ Find server with least workload from spare.tab
1.11      www       528: 
1.1       albertel  529: sub spareserver {
1.670     albertel  530:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  531:     my $spare_server;
1.370     albertel  532:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  533:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    534:                                                      :  $userloadpercent;
                    535:     
                    536:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    537: 	($spare_server, $lowest_load) =
                    538: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    539:     }
                    540: 
                    541:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    542: 
                    543:     if (!$found_server) {
                    544: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    545: 	    ($spare_server, $lowest_load) =
                    546: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    547: 	}
                    548:     }
                    549: 
                    550:     if (!$want_server_name) {
1.838     albertel  551: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  552:     }
                    553:     return $spare_server;
                    554: }
                    555: 
                    556: sub compare_server_load {
                    557:     my ($try_server, $spare_server, $lowest_load) = @_;
                    558: 
                    559:     my $loadans     = &reply('load',    $try_server);
                    560:     my $userloadans = &reply('userload',$try_server);
                    561: 
                    562:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    563: 	next; #didn't get a number from the server
                    564:     }
                    565: 
                    566:     my $load;
                    567:     if ($loadans =~ /\d/) {
                    568: 	if ($userloadans =~ /\d/) {
                    569: 	    #both are numbers, pick the bigger one
                    570: 	    $load = ($loadans > $userloadans) ? $loadans 
                    571: 		                              : $userloadans;
1.411     albertel  572: 	} else {
1.784     albertel  573: 	    $load = $loadans;
1.411     albertel  574: 	}
1.784     albertel  575:     } else {
                    576: 	$load = $userloadans;
                    577:     }
                    578: 
                    579:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    580: 	$spare_server = $try_server;
                    581: 	$lowest_load  = $load;
1.370     albertel  582:     }
1.784     albertel  583:     return ($spare_server,$lowest_load);
1.202     matthew   584: }
                    585: # --------------------------------------------- Try to change a user's password
                    586: 
                    587: sub changepass {
1.799     raeburn   588:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   589:     $currentpass = &escape($currentpass);
                    590:     $newpass     = &escape($newpass);
1.799     raeburn   591:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   592: 		       $server);
                    593:     if (! $answer) {
                    594: 	&logthis("No reply on password change request to $server ".
                    595: 		 "by $uname in domain $udom.");
                    596:     } elsif ($answer =~ "^ok") {
                    597:         &logthis("$uname in $udom successfully changed their password ".
                    598: 		 "on $server.");
                    599:     } elsif ($answer =~ "^pwchange_failure") {
                    600: 	&logthis("$uname in $udom was unable to change their password ".
                    601: 		 "on $server.  The action was blocked by either lcpasswd ".
                    602: 		 "or pwchange");
                    603:     } elsif ($answer =~ "^non_authorized") {
                    604:         &logthis("$uname in $udom did not get their password correct when ".
                    605: 		 "attempting to change it on $server.");
                    606:     } elsif ($answer =~ "^auth_mode_error") {
                    607:         &logthis("$uname in $udom attempted to change their password despite ".
                    608: 		 "not being locally or internally authenticated on $server.");
                    609:     } elsif ($answer =~ "^unknown_user") {
                    610:         &logthis("$uname in $udom attempted to change their password ".
                    611: 		 "on $server but were unable to because $server is not ".
                    612: 		 "their home server.");
                    613:     } elsif ($answer =~ "^refused") {
                    614: 	&logthis("$server refused to change $uname in $udom password because ".
                    615: 		 "it was sent an unencrypted request to change the password.");
                    616:     }
                    617:     return $answer;
1.1       albertel  618: }
                    619: 
1.169     harris41  620: # ----------------------- Try to determine user's current authentication scheme
                    621: 
                    622: sub queryauthenticate {
                    623:     my ($uname,$udom)=@_;
1.456     albertel  624:     my $uhome=&homeserver($uname,$udom);
                    625:     if (!$uhome) {
                    626: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    627: 	return 'no_host';
                    628:     }
                    629:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    630:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    631: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  632:     }
1.456     albertel  633:     return $answer;
1.169     harris41  634: }
                    635: 
1.1       albertel  636: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       637: 
1.1       albertel  638: sub authenticate {
                    639:     my ($uname,$upass,$udom)=@_;
1.807     albertel  640:     $upass=&escape($upass);
                    641:     $uname= &LONCAPA::clean_username($uname);
1.836     www       642:     my $uhome=&homeserver($uname,$udom,1);
                    643:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    644: # Maybe the machine was offline and only re-appeared again recently?
                    645:         &reconlonc();
                    646: # One more
                    647: 	my $uhome=&homeserver($uname,$udom,1);
                    648: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    649: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    650: 	}
1.471     albertel  651: 	return 'no_host';
1.1       albertel  652:     }
1.471     albertel  653:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    654:     if ($answer eq 'authorized') {
                    655: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    656: 	return $uhome; 
                    657:     }
                    658:     if ($answer eq 'non_authorized') {
                    659: 	&logthis("User $uname at $udom rejected by $uhome");
                    660: 	return 'no_host'; 
1.9       www       661:     }
1.471     albertel  662:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  663:     return 'no_host';
                    664: }
                    665: 
                    666: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       667: 
1.599     albertel  668: my %homecache;
1.1       albertel  669: sub homeserver {
1.230     stredwic  670:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  671:     my $index="$uname:$udom";
1.426     albertel  672: 
1.599     albertel  673:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  674: 
                    675:     my %servers = &get_servers($udom,'library');
                    676:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  677:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  678: 		 exists($badServerCache{$tryserver}));
1.841     albertel  679: 
                    680: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    681: 	if ($answer eq 'found') {
                    682: 	    delete($badServerCache{$tryserver}); 
                    683: 	    return $homecache{$index}=$tryserver;
                    684: 	} elsif ($answer eq 'no_host') {
                    685: 	    $badServerCache{$tryserver}=1;
                    686: 	}
1.1       albertel  687:     }    
                    688:     return 'no_host';
1.70      www       689: }
                    690: 
                    691: # ------------------------------------- Find the usernames behind a list of IDs
                    692: 
                    693: sub idget {
                    694:     my ($udom,@ids)=@_;
                    695:     my %returnhash=();
                    696:     
1.841     albertel  697:     my %servers = &get_servers($udom,'library');
                    698:     foreach my $tryserver (keys(%servers)) {
                    699: 	my $idlist=join('&',@ids);
                    700: 	$idlist=~tr/A-Z/a-z/; 
                    701: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    702: 	my @answer=();
                    703: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    704: 	    @answer=split(/\&/,$reply);
                    705: 	}                    ;
                    706: 	my $i;
                    707: 	for ($i=0;$i<=$#ids;$i++) {
                    708: 	    if ($answer[$i]) {
                    709: 		$returnhash{$ids[$i]}=$answer[$i];
                    710: 	    } 
                    711: 	}
                    712:     } 
1.70      www       713:     return %returnhash;
                    714: }
                    715: 
                    716: # ------------------------------------- Find the IDs behind a list of usernames
                    717: 
                    718: sub idrget {
                    719:     my ($udom,@unames)=@_;
                    720:     my %returnhash=();
1.800     albertel  721:     foreach my $uname (@unames) {
                    722:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  723:     }
1.70      www       724:     return %returnhash;
                    725: }
                    726: 
                    727: # ------------------------------- Store away a list of names and associated IDs
                    728: 
                    729: sub idput {
                    730:     my ($udom,%ids)=@_;
                    731:     my %servers=();
1.800     albertel  732:     foreach my $uname (keys(%ids)) {
                    733: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    734:         my $uhom=&homeserver($uname,$udom);
1.70      www       735:         if ($uhom ne 'no_host') {
1.800     albertel  736:             my $id=&escape($ids{$uname});
1.70      www       737:             $id=~tr/A-Z/a-z/;
1.800     albertel  738:             my $esc_unam=&escape($uname);
1.70      www       739: 	    if ($servers{$uhom}) {
1.800     albertel  740: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       741:             } else {
1.800     albertel  742:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       743:             }
                    744:         }
1.191     harris41  745:     }
1.800     albertel  746:     foreach my $server (keys(%servers)) {
                    747:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  748:     }
1.344     www       749: }
                    750: 
1.806     raeburn   751: # ------------------------------------------- get items from domain db files   
                    752: 
                    753: sub get_dom {
1.860     raeburn   754:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   755:     my $items='';
                    756:     foreach my $item (@$storearr) {
                    757:         $items.=&escape($item).'&';
                    758:     }
                    759:     $items=~s/\&$//;
1.860     raeburn   760:     if (!$udom) {
                    761:         $udom=$env{'user.domain'};
                    762:         if (defined(&domain($udom,'primary'))) {
                    763:             $uhome=&domain($udom,'primary');
                    764:         } else {
1.874     albertel  765:             undef($uhome);
1.860     raeburn   766:         }
                    767:     } else {
                    768:         if (!$uhome) {
                    769:             if (defined(&domain($udom,'primary'))) {
                    770:                 $uhome=&domain($udom,'primary');
                    771:             }
                    772:         }
                    773:     }
                    774:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   775:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   776:         my %returnhash;
1.875     albertel  777:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   778:             return %returnhash;
                    779:         }
1.806     raeburn   780:         my @pairs=split(/\&/,$rep);
                    781:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    782:             return @pairs;
                    783:         }
                    784:         my $i=0;
                    785:         foreach my $item (@$storearr) {
                    786:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    787:             $i++;
                    788:         }
                    789:         return %returnhash;
                    790:     } else {
1.880     banghart  791:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   792:     }
                    793: }
                    794: 
                    795: # -------------------------------------------- put items in domain db files 
                    796: 
                    797: sub put_dom {
1.860     raeburn   798:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    799:     if (!$udom) {
                    800:         $udom=$env{'user.domain'};
                    801:         if (defined(&domain($udom,'primary'))) {
                    802:             $uhome=&domain($udom,'primary');
                    803:         } else {
1.874     albertel  804:             undef($uhome);
1.860     raeburn   805:         }
                    806:     } else {
                    807:         if (!$uhome) {
                    808:             if (defined(&domain($udom,'primary'))) {
                    809:                 $uhome=&domain($udom,'primary');
                    810:             }
                    811:         }
                    812:     } 
                    813:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   814:         my $items='';
                    815:         foreach my $item (keys(%$storehash)) {
                    816:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    817:         }
                    818:         $items=~s/\&$//;
                    819:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    820:     } else {
1.860     raeburn   821:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   822:     }
                    823: }
                    824: 
1.837     raeburn   825: sub retrieve_inst_usertypes {
                    826:     my ($udom) = @_;
                    827:     my (%returnhash,@order);
1.846     albertel  828:     if (defined(&domain($udom,'primary'))) {
                    829:         my $uhome=&domain($udom,'primary');
1.837     raeburn   830:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    831:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    832:         my @pairs=split(/\&/,$hashitems);
                    833:         foreach my $item (@pairs) {
                    834:             my ($key,$value)=split(/=/,$item,2);
                    835:             $key = &unescape($key);
                    836:             next if ($key =~ /^error: 2 /);
                    837:             $returnhash{$key}=&thaw_unescape($value);
                    838:         }
                    839:         my @esc_order = split(/\&/,$orderitems);
                    840:         foreach my $item (@esc_order) {
                    841:             push(@order,&unescape($item));
                    842:         }
                    843:     } else {
                    844:         &logthis("get_dom failed - no primary domain server for $udom");
                    845:     }
                    846:     return (\%returnhash,\@order);
                    847: }
                    848: 
1.868     raeburn   849: sub is_domainimage {
                    850:     my ($url) = @_;
                    851:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    852:         if (&domain($1) ne '') {
                    853:             return '1';
                    854:         }
                    855:     }
                    856:     return;
                    857: }
                    858: 
1.899     raeburn   859: sub inst_directory_query {
                    860:     my ($srch) = @_;
                    861:     my $udom = $srch->{'srchdomain'};
                    862:     my %results;
                    863:     my $homeserver = &domain($udom,'primary');
                    864:     if ($homeserver ne '') {
1.904     albertel  865: 	my $queryid=&reply("querysend:instdirsearch:".
                    866: 			   &escape($srch->{'srchby'}).':'.
                    867: 			   &escape($srch->{'srchterm'}).':'.
                    868: 			   &escape($srch->{'srchtype'}),$homeserver);
                    869: 	my $host=&hostname($homeserver);
                    870: 	if ($queryid !~/^\Q$host\E\_/) {
                    871: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    872: 	    return;
                    873: 	}
                    874: 	my $response = &get_query_reply($queryid);
                    875: 	my $maxtries = 5;
                    876: 	my $tries = 1;
                    877: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    878: 	    $response = &get_query_reply($queryid);
                    879: 	    $tries ++;
                    880: 	}
                    881: 
                    882:         if (!&error($response) && $response ne 'refused') {
                    883:             my @matches = split(/\n/,$response);
1.899     raeburn   884:             foreach my $match (@matches) {
                    885:                 my ($key,$value) = split(/=/,$match);
1.904     albertel  886:                 $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1.899     raeburn   887:             }
                    888:         }
                    889:     }
                    890:     return %results;
                    891: }
                    892: 
                    893: sub usersearch {
                    894:     my ($srch) = @_;
                    895:     my $dom = $srch->{'srchdomain'};
                    896:     my %results;
                    897:     my %libserv = &all_library();
                    898:     my $query = 'usersearch';
                    899:     foreach my $tryserver (keys(%libserv)) {
                    900:         if (&host_domain($tryserver) eq $dom) {
                    901:             my $host=&hostname($tryserver);
                    902:             my $queryid=
                    903:                 &reply("querysend:".&escape($query).':'.&escape($dom).':'.
                    904:                        &escape($srch->{'srchby'}).'%%'.
                    905:                        &escape($srch->{'srchtype'}).':'.
                    906:                        &escape($srch->{'srchterm'}),$tryserver);
                    907:             if ($queryid !~/^\Q$host\E\_/) {
                    908:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   909:                 next;
1.899     raeburn   910:             }
                    911:             my $reply = &get_query_reply($queryid);
                    912:             my $maxtries = 1;
                    913:             my $tries = 1;
                    914:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    915:                 $reply = &get_query_reply($queryid);
                    916:                 $tries ++;
                    917:             }
                    918:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    919:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    920:             } else {
1.900     albertel  921:                 my @matches = split(/&/,$reply);
1.899     raeburn   922:                 foreach my $match (@matches) {
                    923:                     my @items = split(/:/,$match);
                    924:                     my ($uname,$udom,%userhash);
                    925:                     foreach my $entry (@items) {
                    926:                         my ($key,$value) = split(/=/,$entry);
                    927:                         $key = &unescape($key);
                    928:                         $value = &unescape($value);
                    929:                         $userhash{$key} = $value;
                    930:                         if ($key eq 'username') {
                    931:                             $uname = $value;
                    932:                         } elsif ($key eq 'domain') {
                    933:                             $udom = $value;
                    934:                         } 
                    935:                     }
                    936:                     $results{$uname.':'.$udom} = \%userhash;
                    937:                 }
                    938:             }
                    939:         }
                    940:     }
                    941:     return %results;
                    942: }
                    943: 
1.344     www       944: # --------------------------------------------------- Assign a key to a student
                    945: 
                    946: sub assign_access_key {
1.364     www       947: #
                    948: # a valid key looks like uname:udom#comments
                    949: # comments are being appended
                    950: #
1.498     www       951:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    952:     $kdom=
1.620     albertel  953:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       954:     $knum=
1.620     albertel  955:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       956:     $cdom=
1.620     albertel  957:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       958:     $cnum=
1.620     albertel  959:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    960:     $udom=$env{'user.name'} unless (defined($udom));
                    961:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       962:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       963:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  964:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       965:                                                   # assigned to this person
                    966:                                                   # - this should not happen,
1.345     www       967:                                                   # unless something went wrong
                    968:                                                   # the first time around
                    969: # ready to assign
1.364     www       970:         $logentry=$1.'; '.$logentry;
1.496     www       971:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       972:                                                  $kdom,$knum) eq 'ok') {
1.345     www       973: # key now belongs to user
1.346     www       974: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       975:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    976:                 &appenv('environment.'.$envkey => $ckey);
                    977:                 return 'ok';
                    978:             } else {
                    979:                 return 
                    980:   'error: Count not permanently assign key, will need to be re-entered later.';
                    981: 	    }
                    982:         } else {
                    983:             return 'error: Could not assign key, try again later.';
                    984:         }
1.364     www       985:     } elsif (!$existing{$ckey}) {
1.345     www       986: # the key does not exist
                    987: 	return 'error: The key does not exist';
                    988:     } else {
                    989: # the key is somebody else's
                    990: 	return 'error: The key is already in use';
                    991:     }
1.344     www       992: }
                    993: 
1.364     www       994: # ------------------------------------------ put an additional comment on a key
                    995: 
                    996: sub comment_access_key {
                    997: #
                    998: # a valid key looks like uname:udom#comments
                    999: # comments are being appended
                   1000: #
                   1001:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1002:     $cdom=
1.620     albertel 1003:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1004:     $cnum=
1.620     albertel 1005:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1006:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1007:     if ($existing{$ckey}) {
                   1008:         $existing{$ckey}.='; '.$logentry;
                   1009: # ready to assign
1.367     www      1010:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1011:                                                  $cdom,$cnum) eq 'ok') {
                   1012: 	    return 'ok';
                   1013:         } else {
                   1014: 	    return 'error: Count not store comment.';
                   1015:         }
                   1016:     } else {
                   1017: # the key does not exist
                   1018: 	return 'error: The key does not exist';
                   1019:     }
                   1020: }
                   1021: 
1.344     www      1022: # ------------------------------------------------------ Generate a set of keys
                   1023: 
                   1024: sub generate_access_keys {
1.364     www      1025:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1026:     $cdom=
1.620     albertel 1027:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1028:     $cnum=
1.620     albertel 1029:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1030:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1031:     unless (($cdom) && ($cnum)) { return 0; }
                   1032:     if ($number>10000) { return 0; }
                   1033:     sleep(2); # make sure don't get same seed twice
                   1034:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1035:     my $total=0;
                   1036:     for (my $i=1;$i<=$number;$i++) {
                   1037:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1038:                   sprintf("%lx",int(100000*rand)).'-'.
                   1039:                   sprintf("%lx",int(100000*rand));
                   1040:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1041:        $newkey=~s/0/h/g; # and also 0 and O
                   1042:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1043:        if ($existing{$newkey}) {
                   1044:            $i--;
                   1045:        } else {
1.364     www      1046: 	  if (&put('accesskeys',
                   1047:               { $newkey => '# generated '.localtime().
1.620     albertel 1048:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1049:                            '; '.$logentry },
                   1050: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1051:               $total++;
                   1052: 	  }
                   1053:        }
                   1054:     }
1.620     albertel 1055:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1056:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1057:     return $total;
                   1058: }
                   1059: 
                   1060: # ------------------------------------------------------- Validate an accesskey
                   1061: 
                   1062: sub validate_access_key {
                   1063:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1064:     $cdom=
1.620     albertel 1065:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1066:     $cnum=
1.620     albertel 1067:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1068:     $udom=$env{'user.domain'} unless (defined($udom));
                   1069:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1070:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1071:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1072: }
                   1073: 
                   1074: # ------------------------------------- Find the section of student in a course
1.652     albertel 1075: sub devalidate_getsection_cache {
                   1076:     my ($udom,$unam,$courseid)=@_;
                   1077:     my $hashid="$udom:$unam:$courseid";
                   1078:     &devalidate_cache_new('getsection',$hashid);
                   1079: }
1.298     matthew  1080: 
1.815     albertel 1081: sub courseid_to_courseurl {
                   1082:     my ($courseid) = @_;
                   1083:     #already url style courseid
                   1084:     return $courseid if ($courseid =~ m{^/});
                   1085: 
                   1086:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1087: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1088: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1089: 	return "/$cdom/$cnum";
                   1090:     }
                   1091: 
                   1092:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1093:     if (exists($courseinfo{'num'})) {
                   1094: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1095:     }
                   1096: 
                   1097:     return undef;
                   1098: }
                   1099: 
1.298     matthew  1100: sub getsection {
                   1101:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1102:     my $cachetime=1800;
1.551     albertel 1103: 
                   1104:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1105:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1106:     if (defined($cached)) { return $result; }
                   1107: 
1.298     matthew  1108:     my %Pending; 
                   1109:     my %Expired;
                   1110:     #
                   1111:     # Each role can either have not started yet (pending), be active, 
                   1112:     #    or have expired.
                   1113:     #
                   1114:     # If there is an active role, we are done.
                   1115:     #
                   1116:     # If there is more than one role which has not started yet, 
                   1117:     #     choose the one which will start sooner
                   1118:     # If there is one role which has not started yet, return it.
                   1119:     #
                   1120:     # If there is more than one expired role, choose the one which ended last.
                   1121:     # If there is a role which has expired, return it.
                   1122:     #
1.815     albertel 1123:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1124:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1125:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1126:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1127:         my $section=$1;
                   1128:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1129:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1130:         my $now=time;
1.548     albertel 1131:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1132:             $Expired{$end}=$section;
                   1133:             next;
                   1134:         }
1.548     albertel 1135:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1136:             $Pending{$start}=$section;
                   1137:             next;
                   1138:         }
1.599     albertel 1139:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1140:     }
                   1141:     #
                   1142:     # Presumedly there will be few matching roles from the above
                   1143:     # loop and the sorting time will be negligible.
                   1144:     if (scalar(keys(%Pending))) {
                   1145:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1146:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1147:     } 
                   1148:     if (scalar(keys(%Expired))) {
                   1149:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1150:         my $time = pop(@sorted);
1.599     albertel 1151:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1152:     }
1.599     albertel 1153:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1154: }
1.70      www      1155: 
1.599     albertel 1156: sub save_cache {
                   1157:     &purge_remembered();
1.722     albertel 1158:     #&Apache::loncommon::validate_page();
1.620     albertel 1159:     undef(%env);
1.780     albertel 1160:     undef($env_loaded);
1.599     albertel 1161: }
1.452     albertel 1162: 
1.599     albertel 1163: my $to_remember=-1;
                   1164: my %remembered;
                   1165: my %accessed;
                   1166: my $kicks=0;
                   1167: my $hits=0;
1.849     albertel 1168: sub make_key {
                   1169:     my ($name,$id) = @_;
1.872     albertel 1170:     if (length($id) > 65 
                   1171: 	&& length(&escape($id)) > 200) {
                   1172: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1173:     }
1.849     albertel 1174:     return &escape($name.':'.$id);
                   1175: }
                   1176: 
1.599     albertel 1177: sub devalidate_cache_new {
                   1178:     my ($name,$id,$debug) = @_;
                   1179:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1180:     $id=&make_key($name,$id);
1.599     albertel 1181:     $memcache->delete($id);
                   1182:     delete($remembered{$id});
                   1183:     delete($accessed{$id});
                   1184: }
                   1185: 
                   1186: sub is_cached_new {
                   1187:     my ($name,$id,$debug) = @_;
1.849     albertel 1188:     $id=&make_key($name,$id);
1.599     albertel 1189:     if (exists($remembered{$id})) {
                   1190: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1191: 	$accessed{$id}=[&gettimeofday()];
                   1192: 	$hits++;
                   1193: 	return ($remembered{$id},1);
                   1194:     }
                   1195:     my $value = $memcache->get($id);
                   1196:     if (!(defined($value))) {
                   1197: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1198: 	return (undef,undef);
1.416     albertel 1199:     }
1.599     albertel 1200:     if ($value eq '__undef__') {
                   1201: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1202: 	$value=undef;
                   1203:     }
                   1204:     &make_room($id,$value,$debug);
                   1205:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1206:     return ($value,1);
                   1207: }
                   1208: 
                   1209: sub do_cache_new {
                   1210:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1211:     $id=&make_key($name,$id);
1.599     albertel 1212:     my $setvalue=$value;
                   1213:     if (!defined($setvalue)) {
                   1214: 	$setvalue='__undef__';
                   1215:     }
1.623     albertel 1216:     if (!defined($time) ) {
                   1217: 	$time=600;
                   1218:     }
1.599     albertel 1219:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.872     albertel 1220:     if (!($memcache->set($id,$setvalue,$time))) {
                   1221: 	&logthis("caching of id -> $id  failed");
                   1222:     }
1.600     albertel 1223:     # need to make a copy of $value
                   1224:     #&make_room($id,$value,$debug);
1.599     albertel 1225:     return $value;
                   1226: }
                   1227: 
                   1228: sub make_room {
                   1229:     my ($id,$value,$debug)=@_;
                   1230:     $remembered{$id}=$value;
                   1231:     if ($to_remember<0) { return; }
                   1232:     $accessed{$id}=[&gettimeofday()];
                   1233:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1234:     my $to_kick;
                   1235:     my $max_time=0;
                   1236:     foreach my $other (keys(%accessed)) {
                   1237: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1238: 	    $to_kick=$other;
                   1239: 	    $max_time=&tv_interval($accessed{$other});
                   1240: 	}
                   1241:     }
                   1242:     delete($remembered{$to_kick});
                   1243:     delete($accessed{$to_kick});
                   1244:     $kicks++;
                   1245:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1246:     return;
                   1247: }
                   1248: 
1.599     albertel 1249: sub purge_remembered {
1.604     albertel 1250:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1251:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1252:     undef(%remembered);
                   1253:     undef(%accessed);
1.428     albertel 1254: }
1.70      www      1255: # ------------------------------------- Read an entry from a user's environment
                   1256: 
                   1257: sub userenvironment {
                   1258:     my ($udom,$unam,@what)=@_;
                   1259:     my %returnhash=();
                   1260:     my @answer=split(/\&/,
                   1261:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1262:                       &homeserver($unam,$udom)));
                   1263:     my $i;
                   1264:     for ($i=0;$i<=$#what;$i++) {
                   1265: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1266:     }
                   1267:     return %returnhash;
1.1       albertel 1268: }
                   1269: 
1.617     albertel 1270: # ---------------------------------------------------------- Get a studentphoto
                   1271: sub studentphoto {
                   1272:     my ($udom,$unam,$ext) = @_;
                   1273:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1274:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1275:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1276:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1277:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1278:             } else {
                   1279:                 my ($result,$perm_reqd)=
1.707     albertel 1280: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1281:                 if ($result eq 'ok') {
                   1282:                     if (!($perm_reqd eq 'yes')) {
                   1283:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1284:                     }
                   1285:                 }
                   1286:             }
                   1287:         }
                   1288:     } else {
                   1289:         my ($result,$perm_reqd) = 
1.707     albertel 1290: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1291:         if ($result eq 'ok') {
                   1292:             if (!($perm_reqd eq 'yes')) {
                   1293:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1294:             }
                   1295:         }
                   1296:     }
                   1297:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1298: }
                   1299: 
                   1300: sub retrievestudentphoto {
                   1301:     my ($udom,$unam,$ext,$type) = @_;
                   1302:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1303:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1304:     if ($ret eq 'ok') {
                   1305:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1306:         if ($type eq 'thumbnail') {
                   1307:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1308:         }
                   1309:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1310:         return $tokenurl;
                   1311:     } else {
                   1312:         if ($type eq 'thumbnail') {
                   1313:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1314:         } else { 
                   1315:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1316:         }
1.617     albertel 1317:     }
                   1318: }
                   1319: 
1.263     www      1320: # -------------------------------------------------------------------- New chat
                   1321: 
                   1322: sub chatsend {
1.724     raeburn  1323:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1324:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1325:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1326:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1327:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1328: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1329: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1330: }
                   1331: 
                   1332: # ------------------------------------------ Find current version of a resource
                   1333: 
                   1334: sub getversion {
                   1335:     my $fname=&clutter(shift);
                   1336:     unless ($fname=~/^\/res\//) { return -1; }
                   1337:     return &currentversion(&filelocation('',$fname));
                   1338: }
                   1339: 
                   1340: sub currentversion {
                   1341:     my $fname=shift;
1.599     albertel 1342:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1343:     if (defined($cached)) { return $result; }
1.292     www      1344:     my $author=$fname;
                   1345:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1346:     my ($udom,$uname)=split(/\//,$author);
                   1347:     my $home=homeserver($uname,$udom);
                   1348:     if ($home eq 'no_host') { 
                   1349:         return -1; 
                   1350:     }
                   1351:     my $answer=reply("currentversion:$fname",$home);
                   1352:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1353: 	return -1;
                   1354:     }
1.599     albertel 1355:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1356: }
                   1357: 
1.1       albertel 1358: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1359: 
1.1       albertel 1360: sub subscribe {
                   1361:     my $fname=shift;
1.761     raeburn  1362:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1363:     $fname=~s/[\n\r]//g;
1.1       albertel 1364:     my $author=$fname;
                   1365:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1366:     my ($udom,$uname)=split(/\//,$author);
                   1367:     my $home=homeserver($uname,$udom);
1.335     albertel 1368:     if ($home eq 'no_host') {
                   1369:         return 'not_found';
1.1       albertel 1370:     }
                   1371:     my $answer=reply("sub:$fname",$home);
1.64      www      1372:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1373: 	$answer.=' by '.$home;
                   1374:     }
1.1       albertel 1375:     return $answer;
                   1376: }
                   1377:     
1.8       www      1378: # -------------------------------------------------------------- Replicate file
                   1379: 
                   1380: sub repcopy {
                   1381:     my $filename=shift;
1.23      www      1382:     $filename=~s/\/+/\//g;
1.607     raeburn  1383:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1384:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1385:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1386: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1387: 	return &repcopy_userfile($filename);
                   1388:     }
1.532     albertel 1389:     $filename=~s/[\n\r]//g;
1.8       www      1390:     my $transname="$filename.in.transfer";
1.828     www      1391: # FIXME: this should flock
1.607     raeburn  1392:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1393:     my $remoteurl=subscribe($filename);
1.64      www      1394:     if ($remoteurl =~ /^con_lost by/) {
                   1395: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1396:            return 'unavailable';
1.8       www      1397:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1398: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1399: 	   return 'not_found';
1.64      www      1400:     } elsif ($remoteurl =~ /^rejected by/) {
                   1401: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1402:            return 'forbidden';
1.20      www      1403:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1404:            return 'ok';
1.8       www      1405:     } else {
1.290     www      1406:         my $author=$filename;
                   1407:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1408:         my ($udom,$uname)=split(/\//,$author);
                   1409:         my $home=homeserver($uname,$udom);
                   1410:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1411:            my @parts=split(/\//,$filename);
                   1412:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1413:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1414:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1415: 	       return 'bad_request';
1.8       www      1416:            }
                   1417:            my $count;
                   1418:            for ($count=5;$count<$#parts;$count++) {
                   1419:                $path.="/$parts[$count]";
                   1420:                if ((-e $path)!=1) {
                   1421: 		   mkdir($path,0777);
                   1422:                }
                   1423:            }
                   1424:            my $ua=new LWP::UserAgent;
                   1425:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1426:            my $response=$ua->request($request,$transname);
                   1427:            if ($response->is_error()) {
                   1428: 	       unlink($transname);
                   1429:                my $message=$response->status_line;
1.672     albertel 1430:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1431:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1432:                return 'unavailable';
1.8       www      1433:            } else {
1.16      www      1434: 	       if ($remoteurl!~/\.meta$/) {
                   1435:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1436:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1437:                   if ($mresponse->is_error()) {
                   1438: 		      unlink($filename.'.meta');
                   1439:                       &logthis(
1.672     albertel 1440:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1441:                   }
                   1442: 	       }
1.8       www      1443:                rename($transname,$filename);
1.607     raeburn  1444:                return 'ok';
1.8       www      1445:            }
1.290     www      1446:        }
1.8       www      1447:     }
1.330     www      1448: }
                   1449: 
                   1450: # ------------------------------------------------ Get server side include body
                   1451: sub ssi_body {
1.381     albertel 1452:     my ($filelink,%form)=@_;
1.606     matthew  1453:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1454:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1455:     }
1.330     www      1456:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1457:                                      &ssi($filelink,%form));
1.778     albertel 1458:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1459:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1460:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1461:     return $output;
1.8       www      1462: }
                   1463: 
1.15      www      1464: # --------------------------------------------------------- Server Side Include
                   1465: 
1.782     albertel 1466: sub absolute_url {
                   1467:     my ($host_name) = @_;
                   1468:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1469:     if ($host_name eq '') {
                   1470: 	$host_name = $ENV{'SERVER_NAME'};
                   1471:     }
                   1472:     return $protocol.$host_name;
                   1473: }
                   1474: 
1.15      www      1475: sub ssi {
                   1476: 
1.23      www      1477:     my ($fn,%form)=@_;
1.15      www      1478: 
                   1479:     my $ua=new LWP::UserAgent;
1.23      www      1480:     
                   1481:     my $request;
1.711     albertel 1482: 
                   1483:     $form{'no_update_last_known'}=1;
1.895     albertel 1484:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1485:     if (%form) {
1.782     albertel 1486:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1487:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1488:     } else {
1.782     albertel 1489:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1490:     }
                   1491: 
1.15      www      1492:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1493:     my $response=$ua->request($request);
                   1494: 
1.324     www      1495:     return $response->content;
                   1496: }
                   1497: 
                   1498: sub externalssi {
                   1499:     my ($url)=@_;
                   1500:     my $ua=new LWP::UserAgent;
                   1501:     my $request=new HTTP::Request('GET',$url);
                   1502:     my $response=$ua->request($request);
1.15      www      1503:     return $response->content;
                   1504: }
1.254     www      1505: 
1.492     albertel 1506: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1507: 
                   1508: sub allowuploaded {
                   1509:     my ($srcurl,$url)=@_;
                   1510:     $url=&clutter(&declutter($url));
                   1511:     my $dir=$url;
                   1512:     $dir=~s/\/[^\/]+$//;
                   1513:     my %httpref=();
                   1514:     my $httpurl=&hreflocation('',$url);
                   1515:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1516:     &Apache::lonnet::appenv(%httpref);
1.254     www      1517: }
1.477     raeburn  1518: 
1.478     albertel 1519: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1520: # input: action, courseID, current domain, intended
1.637     raeburn  1521: #        path to file, source of file, instruction to parse file for objects,
                   1522: #        ref to hash for embedded objects,
                   1523: #        ref to hash for codebase of java objects.
                   1524: #
1.485     raeburn  1525: # output: url to file (if action was uploaddoc), 
                   1526: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1527: #
1.478     albertel 1528: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1529: # course.
1.477     raeburn  1530: #
1.478     albertel 1531: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1532: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1533: #          course's home server.
1.477     raeburn  1534: #
1.478     albertel 1535: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1536: #          be copied from $source (current location) to 
                   1537: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1538: #         and will then be copied to
                   1539: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1540: #         course's home server.
1.485     raeburn  1541: #
1.481     raeburn  1542: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1543: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1544: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1545: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1546: #         in course's home server.
1.637     raeburn  1547: #
1.477     raeburn  1548: 
                   1549: sub process_coursefile {
1.638     albertel 1550:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1551:     my $fetchresult;
1.638     albertel 1552:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1553:     if ($action eq 'propagate') {
1.638     albertel 1554:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1555: 			     $home);
1.481     raeburn  1556:     } else {
1.477     raeburn  1557:         my $fpath = '';
                   1558:         my $fname = $file;
1.478     albertel 1559:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1560:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1561:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1562:         if ($action eq 'copy') {
                   1563:             if ($source eq '') {
                   1564:                 $fetchresult = 'no source file';
                   1565:                 return $fetchresult;
                   1566:             } else {
                   1567:                 my $destination = $filepath.'/'.$fname;
                   1568:                 rename($source,$destination);
                   1569:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1570:                                  $home);
1.481     raeburn  1571:             }
                   1572:         } elsif ($action eq 'uploaddoc') {
                   1573:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1574:             print $fh $env{'form.'.$source};
1.481     raeburn  1575:             close($fh);
1.637     raeburn  1576:             if ($parser eq 'parse') {
                   1577:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1578:                 unless ($parse_result eq 'ok') {
                   1579:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1580:                 }
                   1581:             }
1.477     raeburn  1582:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1583:                                  $home);
1.481     raeburn  1584:             if ($fetchresult eq 'ok') {
                   1585:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1586:             } else {
                   1587:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1588:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1589:                 return '/adm/notfound.html';
                   1590:             }
1.477     raeburn  1591:         }
                   1592:     }
1.485     raeburn  1593:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1594:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1595:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1596:     }
                   1597:     return $fetchresult;
                   1598: }
                   1599: 
1.637     raeburn  1600: sub build_filepath {
                   1601:     my ($fpath) = @_;
                   1602:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1603:     unless ($fpath eq '') {
                   1604:         my @parts=split('/',$fpath);
                   1605:         foreach my $part (@parts) {
                   1606:             $filepath.= '/'.$part;
                   1607:             if ((-e $filepath)!=1) {
                   1608:                 mkdir($filepath,0777);
                   1609:             }
                   1610:         }
                   1611:     }
                   1612:     return $filepath;
                   1613: }
                   1614: 
                   1615: sub store_edited_file {
1.638     albertel 1616:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1617:     my $file = $primary_url;
                   1618:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1619:     my $fpath = '';
                   1620:     my $fname = $file;
                   1621:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1622:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1623:     my $filepath = &build_filepath($fpath);
                   1624:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1625:     print $fh $content;
                   1626:     close($fh);
1.638     albertel 1627:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1628:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1629: 			  $home);
1.637     raeburn  1630:     if ($$fetchresult eq 'ok') {
                   1631:         return '/uploaded/'.$fpath.'/'.$fname;
                   1632:     } else {
1.638     albertel 1633:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1634: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1635:         return '/adm/notfound.html';
                   1636:     }
                   1637: }
                   1638: 
1.531     albertel 1639: sub clean_filename {
1.831     albertel 1640:     my ($fname,$args)=@_;
1.315     www      1641: # Replace Windows backslashes by forward slashes
1.257     www      1642:     $fname=~s/\\/\//g;
1.831     albertel 1643:     if (!$args->{'keep_path'}) {
                   1644:         # Get rid of everything but the actual filename
                   1645: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1646:     }
1.315     www      1647: # Replace spaces by underscores
                   1648:     $fname=~s/\s+/\_/g;
                   1649: # Replace all other weird characters by nothing
1.831     albertel 1650:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1651: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1652: # numbers
                   1653:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1654:     return $fname;
                   1655: }
                   1656: 
1.608     albertel 1657: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1658: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1659: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1660: #        $coursedoc - if true up to the current course
                   1661: #                     if false
                   1662: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1663: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1664: #        $allfiles - reference to hash for embedded objects
                   1665: #        $codebase - reference to hash for codebase of java objects
                   1666: #        $desuname - username for permanent storage of uploaded file
                   1667: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1668: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1669: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1670: # 
1.686     albertel 1671: # output: url of file in userspace, or error: <message> 
                   1672: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1673: 
                   1674: 
1.531     albertel 1675: sub userfileupload {
1.860     raeburn  1676:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1677:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1678:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1679:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1680:     $fname=&clean_filename($fname);
1.315     www      1681: # See if there is anything left
1.257     www      1682:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1683:     chop($env{'form.'.$formname});
1.523     raeburn  1684:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1685:         my $now = time;
                   1686:         my $filepath = 'tmp/helprequests/'.$now;
                   1687:         my @parts=split(/\//,$filepath);
                   1688:         my $fullpath = $perlvar{'lonDaemons'};
                   1689:         for (my $i=0;$i<@parts;$i++) {
                   1690:             $fullpath .= '/'.$parts[$i];
                   1691:             if ((-e $fullpath)!=1) {
                   1692:                 mkdir($fullpath,0777);
                   1693:             }
                   1694:         }
                   1695:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1696:         print $fh $env{'form.'.$formname};
1.523     raeburn  1697:         close($fh);
1.741     raeburn  1698:         return $fullpath.'/'.$fname;
                   1699:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1700:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1701:                        '_'.$env{'user.domain'}.'/pending';
                   1702:         my @parts=split(/\//,$filepath);
                   1703:         my $fullpath = $perlvar{'lonDaemons'};
                   1704:         for (my $i=0;$i<@parts;$i++) {
                   1705:             $fullpath .= '/'.$parts[$i];
                   1706:             if ((-e $fullpath)!=1) {
                   1707:                 mkdir($fullpath,0777);
                   1708:             }
                   1709:         }
                   1710:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1711:         print $fh $env{'form.'.$formname};
                   1712:         close($fh);
                   1713:         return $fullpath.'/'.$fname;
1.523     raeburn  1714:     }
1.719     banghart 1715:     
1.258     www      1716: # Create the directory if not present
1.493     albertel 1717:     $fname="$subdir/$fname";
1.259     www      1718:     if ($coursedoc) {
1.638     albertel 1719: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1720: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1721:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1722:             return &finishuserfileupload($docuname,$docudom,
                   1723: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1724: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1725:         } else {
1.620     albertel 1726:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1727:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1728: 				       $fname,$formname,$parser,
                   1729: 				       $allfiles,$codebase);
1.481     raeburn  1730:         }
1.719     banghart 1731:     } elsif (defined($destuname)) {
                   1732:         my $docuname=$destuname;
                   1733:         my $docudom=$destudom;
1.860     raeburn  1734: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1735: 				     $parser,$allfiles,$codebase,
                   1736:                                      $thumbwidth,$thumbheight);
1.719     banghart 1737:         
1.259     www      1738:     } else {
1.638     albertel 1739:         my $docuname=$env{'user.name'};
                   1740:         my $docudom=$env{'user.domain'};
1.714     raeburn  1741:         if (exists($env{'form.group'})) {
                   1742:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1743:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1744:         }
1.860     raeburn  1745: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1746: 				     $parser,$allfiles,$codebase,
                   1747:                                      $thumbwidth,$thumbheight);
1.259     www      1748:     }
1.271     www      1749: }
                   1750: 
                   1751: sub finishuserfileupload {
1.860     raeburn  1752:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1753:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1754:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1755:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1756:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1757:     $file=$fname;
                   1758:     if ($fname=~m|/|) {
                   1759:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1760: 	$path.=$fnamepath.'/';
                   1761:     }
1.259     www      1762:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1763:     my $count;
                   1764:     for ($count=4;$count<=$#parts;$count++) {
                   1765:         $filepath.="/$parts[$count]";
                   1766:         if ((-e $filepath)!=1) {
                   1767: 	    mkdir($filepath,0777);
                   1768:         }
                   1769:     }
                   1770: # Save the file
                   1771:     {
1.701     albertel 1772: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1773: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1774: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1775: 	    return '/adm/notfound.html';
                   1776: 	}
                   1777: 	if (!print FH ($env{'form.'.$formname})) {
                   1778: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1779: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1780: 	    return '/adm/notfound.html';
                   1781: 	}
1.570     albertel 1782: 	close(FH);
1.258     www      1783:     }
1.637     raeburn  1784:     if ($parser eq 'parse') {
1.638     albertel 1785:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1786: 						   $codebase);
1.637     raeburn  1787:         unless ($parse_result eq 'ok') {
1.638     albertel 1788:             &logthis('Failed to parse '.$filepath.$file.
                   1789: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1790:         }
                   1791:     }
1.860     raeburn  1792:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1793:         my $input = $filepath.'/'.$file;
                   1794:         my $output = $filepath.'/'.'tn-'.$file;
                   1795:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1796:         system("convert -sample $thumbsize $input $output");
                   1797:         if (-e $filepath.'/'.'tn-'.$file) {
                   1798:             $fetchthumb  = 1; 
                   1799:         }
                   1800:     }
1.858     raeburn  1801:  
1.259     www      1802: # Notify homeserver to grep it
                   1803: #
1.638     albertel 1804:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1805:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1806:     if ($fetchresult eq 'ok') {
1.860     raeburn  1807:         if ($fetchthumb) {
                   1808:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1809:             if ($thumbresult ne 'ok') {
                   1810:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1811:                          $docuhome.': '.$thumbresult);
                   1812:             }
                   1813:         }
1.259     www      1814: #
1.258     www      1815: # Return the URL to it
1.494     albertel 1816:         return '/uploaded/'.$path.$file;
1.263     www      1817:     } else {
1.494     albertel 1818:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1819: 		 ': '.$fetchresult);
1.263     www      1820:         return '/adm/notfound.html';
1.858     raeburn  1821:     }
1.493     albertel 1822: }
                   1823: 
1.637     raeburn  1824: sub extract_embedded_items {
1.648     raeburn  1825:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1826:     my @state = ();
                   1827:     my %javafiles = (
                   1828:                       codebase => '',
                   1829:                       code => '',
                   1830:                       archive => ''
                   1831:                     );
                   1832:     my %mediafiles = (
                   1833:                       src => '',
                   1834:                       movie => '',
                   1835:                      );
1.648     raeburn  1836:     my $p;
                   1837:     if ($content) {
                   1838:         $p = HTML::LCParser->new($content);
                   1839:     } else {
                   1840:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1841:     }
1.641     albertel 1842:     while (my $t=$p->get_token()) {
1.640     albertel 1843: 	if ($t->[0] eq 'S') {
                   1844: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1845: 	    push(@state, $tagname);
1.648     raeburn  1846:             if (lc($tagname) eq 'allow') {
                   1847:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1848:             }
1.640     albertel 1849: 	    if (lc($tagname) eq 'img') {
                   1850: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1851: 	    }
1.886     albertel 1852: 	    if (lc($tagname) eq 'a') {
                   1853: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1854: 	    }
1.645     raeburn  1855:             if (lc($tagname) eq 'script') {
                   1856:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1857:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1858:                 } else {
                   1859:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1860:                 }
                   1861:             }
                   1862:             if (lc($tagname) eq 'link') {
                   1863:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1864:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1865:                 }
                   1866:             }
1.640     albertel 1867: 	    if (lc($tagname) eq 'object' ||
                   1868: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1869: 		foreach my $item (keys(%javafiles)) {
                   1870: 		    $javafiles{$item} = '';
                   1871: 		}
                   1872: 	    }
                   1873: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1874: 		my $name = lc($attr->{'name'});
                   1875: 		foreach my $item (keys(%javafiles)) {
                   1876: 		    if ($name eq $item) {
                   1877: 			$javafiles{$item} = $attr->{'value'};
                   1878: 			last;
                   1879: 		    }
                   1880: 		}
                   1881: 		foreach my $item (keys(%mediafiles)) {
                   1882: 		    if ($name eq $item) {
                   1883: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1884: 			last;
                   1885: 		    }
                   1886: 		}
                   1887: 	    }
                   1888: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1889: 		foreach my $item (keys(%javafiles)) {
                   1890: 		    if ($attr->{$item}) {
                   1891: 			$javafiles{$item} = $attr->{$item};
                   1892: 			last;
                   1893: 		    }
                   1894: 		}
                   1895: 		foreach my $item (keys(%mediafiles)) {
                   1896: 		    if ($attr->{$item}) {
                   1897: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1898: 			last;
                   1899: 		    }
                   1900: 		}
                   1901: 	    }
                   1902: 	} elsif ($t->[0] eq 'E') {
                   1903: 	    my ($tagname) = ($t->[1]);
                   1904: 	    if ($javafiles{'codebase'} ne '') {
                   1905: 		$javafiles{'codebase'} .= '/';
                   1906: 	    }  
                   1907: 	    if (lc($tagname) eq 'applet' ||
                   1908: 		lc($tagname) eq 'object' ||
                   1909: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1910: 		) {
                   1911: 		foreach my $item (keys(%javafiles)) {
                   1912: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1913: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1914: 			&add_filetype($allfiles,$file,$item);
                   1915: 		    }
                   1916: 		}
                   1917: 	    } 
                   1918: 	    pop @state;
                   1919: 	}
                   1920:     }
1.637     raeburn  1921:     return 'ok';
                   1922: }
                   1923: 
1.639     albertel 1924: sub add_filetype {
                   1925:     my ($allfiles,$file,$type)=@_;
                   1926:     if (exists($allfiles->{$file})) {
                   1927: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1928: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1929: 	}
                   1930:     } else {
                   1931: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1932:     }
                   1933: }
                   1934: 
1.493     albertel 1935: sub removeuploadedurl {
                   1936:     my ($url)=@_;
                   1937:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1938:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1939: }
                   1940: 
                   1941: sub removeuserfile {
                   1942:     my ($docuname,$docudom,$fname)=@_;
                   1943:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1944:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1945:     if ($result eq 'ok') {
                   1946:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1947:             my $metafile = $fname.'.meta';
                   1948:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1949: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1950:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1951:             my $sqlresult = 
1.823     albertel 1952:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1953:                                         'portfolio_metadata',$group,
                   1954:                                         'delete');
1.798     raeburn  1955:         }
                   1956:     }
                   1957:     return $result;
1.257     www      1958: }
1.15      www      1959: 
1.530     albertel 1960: sub mkdiruserfile {
                   1961:     my ($docuname,$docudom,$dir)=@_;
                   1962:     my $home=&homeserver($docuname,$docudom);
                   1963:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1964: }
                   1965: 
1.531     albertel 1966: sub renameuserfile {
                   1967:     my ($docuname,$docudom,$old,$new)=@_;
                   1968:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1969:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1970:                         &escape("$old").':'.&escape("$new"),$home);
                   1971:     if ($result eq 'ok') {
                   1972:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1973:             my $oldmeta = $old.'.meta';
                   1974:             my $newmeta = $new.'.meta';
                   1975:             my $metaresult = 
                   1976:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1977: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1978:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1979:             my $sqlresult = 
1.823     albertel 1980:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1981:                                         'portfolio_metadata',$group,
                   1982:                                         'delete');
1.798     raeburn  1983:         }
                   1984:     }
                   1985:     return $result;
1.531     albertel 1986: }
                   1987: 
1.14      www      1988: # ------------------------------------------------------------------------- Log
                   1989: 
                   1990: sub log {
                   1991:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1992:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1993: }
                   1994: 
                   1995: # ------------------------------------------------------------------ Course Log
1.352     www      1996: #
                   1997: # This routine flushes several buffers of non-mission-critical nature
                   1998: #
1.157     www      1999: 
                   2000: sub flushcourselogs {
1.352     www      2001:     &logthis('Flushing log buffers');
                   2002: #
                   2003: # course logs
                   2004: # This is a log of all transactions in a course, which can be used
                   2005: # for data mining purposes
                   2006: #
                   2007: # It also collects the courseid database, which lists last transaction
                   2008: # times and course titles for all courseids
                   2009: #
                   2010:     my %courseidbuffer=();
1.800     albertel 2011:     foreach my $crsid (keys %courselogs) {
1.352     www      2012:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2013: 		          &escape($courselogs{$crsid}),
                   2014: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2015: 	    delete $courselogs{$crsid};
                   2016:         } else {
                   2017:             &logthis('Failed to flush log buffer for '.$crsid);
                   2018:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2019:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2020:                         " exceeded maximum size, deleting.</font>");
                   2021:                delete $courselogs{$crsid};
                   2022:             }
1.352     www      2023:         }
                   2024:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2025:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2026: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2027:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2028:         } else {
                   2029:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2030: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2031:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2032:         }
1.191     harris41 2033:     }
1.352     www      2034: #
                   2035: # Write course id database (reverse lookup) to homeserver of courses 
                   2036: # Is used in pickcourse
                   2037: #
1.840     albertel 2038:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2039:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2040: 		     $crs_home);
1.352     www      2041:     }
                   2042: #
                   2043: # File accesses
                   2044: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2045: #
1.449     matthew  2046:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2047:         if ($entry =~ /___count$/) {
                   2048:             my ($dom,$name);
1.807     albertel 2049:             ($dom,$name,undef)=
1.811     albertel 2050: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2051:             if (! defined($dom) || $dom eq '' || 
                   2052:                 ! defined($name) || $name eq '') {
1.620     albertel 2053:                 my $cid = $env{'request.course.id'};
                   2054:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2055:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2056:             }
1.450     matthew  2057:             my $value = $accesshash{$entry};
                   2058:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2059:             my %temphash=($url => $value);
1.449     matthew  2060:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2061:             if ($result eq 'ok') {
                   2062:                 delete $accesshash{$entry};
                   2063:             } elsif ($result eq 'unknown_cmd') {
                   2064:                 # Target server has old code running on it.
1.450     matthew  2065:                 my %temphash=($entry => $value);
1.449     matthew  2066:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2067:                     delete $accesshash{$entry};
                   2068:                 }
                   2069:             }
                   2070:         } else {
1.811     albertel 2071:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2072:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2073:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2074:                 delete $accesshash{$entry};
                   2075:             }
1.185     www      2076:         }
1.191     harris41 2077:     }
1.352     www      2078: #
                   2079: # Roles
                   2080: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2081: #
1.800     albertel 2082:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2083:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2084: 	    split(/\:/,$entry);
                   2085:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2086:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2087:                 $rudom,$runame) eq 'ok') {
                   2088: 	    delete $userrolehash{$entry};
                   2089:         }
                   2090:     }
1.662     raeburn  2091: #
                   2092: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2093: #
                   2094:     my %domrolebuffer = ();
                   2095:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2096:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2097:         if ($domrolebuffer{$rudom}) {
                   2098:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2099:                       '='.&escape($domainrolehash{$entry});
                   2100:         } else {
                   2101:             $domrolebuffer{$rudom}.=&escape($entry).
                   2102:                       '='.&escape($domainrolehash{$entry});
                   2103:         }
                   2104:         delete $domainrolehash{$entry};
                   2105:     }
                   2106:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2107: 	my %servers = &get_servers($dom,'library');
                   2108: 	foreach my $tryserver (keys(%servers)) {
                   2109: 	    unless (&reply('domroleput:'.$dom.':'.
                   2110: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2111: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2112: 	    }
1.662     raeburn  2113:         }
                   2114:     }
1.186     www      2115:     $dumpcount++;
1.157     www      2116: }
                   2117: 
                   2118: sub courselog {
                   2119:     my $what=shift;
1.158     www      2120:     $what=time.':'.$what;
1.620     albertel 2121:     unless ($env{'request.course.id'}) { return ''; }
                   2122:     $coursedombuf{$env{'request.course.id'}}=
                   2123:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2124:     $coursenumbuf{$env{'request.course.id'}}=
                   2125:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2126:     $coursehombuf{$env{'request.course.id'}}=
                   2127:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2128:     $coursedescrbuf{$env{'request.course.id'}}=
                   2129:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2130:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2131:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2132:     $courseownerbuf{$env{'request.course.id'}}=
                   2133:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2134:     $coursetypebuf{$env{'request.course.id'}}=
                   2135:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2136:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2137: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2138:     } else {
1.620     albertel 2139: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2140:     }
1.620     albertel 2141:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2142: 	&flushcourselogs();
                   2143:     }
1.158     www      2144: }
                   2145: 
                   2146: sub courseacclog {
                   2147:     my $fnsymb=shift;
1.620     albertel 2148:     unless ($env{'request.course.id'}) { return ''; }
                   2149:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2150:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2151:         $what.=':POST';
1.583     matthew  2152:         # FIXME: Probably ought to escape things....
1.800     albertel 2153: 	foreach my $key (keys(%env)) {
                   2154:             if ($key=~/^form\.(.*)/) {
                   2155: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2156:             }
1.191     harris41 2157:         }
1.583     matthew  2158:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2159:         # FIXME: We should not be depending on a form parameter that someone
                   2160:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2161:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2162:             $what.= ':POST';
                   2163:             # FIXME: Probably ought to escape things....
                   2164:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2165:                                  'crsdiscuss') {
1.620     albertel 2166:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2167:             }
                   2168:         }
1.158     www      2169:     }
                   2170:     &courselog($what);
1.149     www      2171: }
                   2172: 
1.185     www      2173: sub countacc {
                   2174:     my $url=&declutter(shift);
1.458     matthew  2175:     return if (! defined($url) || $url eq '');
1.620     albertel 2176:     unless ($env{'request.course.id'}) { return ''; }
                   2177:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2178:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2179:     $accesshash{$key}++;
1.185     www      2180: }
1.349     www      2181: 
1.361     www      2182: sub linklog {
                   2183:     my ($from,$to)=@_;
                   2184:     $from=&declutter($from);
                   2185:     $to=&declutter($to);
                   2186:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2187:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2188: }
                   2189:   
1.349     www      2190: sub userrolelog {
                   2191:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2192:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2193:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2194:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2195:         ($trole=~/^ta/)) {
1.350     www      2196:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2197:        $userrolehash
                   2198:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2199:                     =$tend.':'.$tstart;
1.662     raeburn  2200:     }
1.898     albertel 2201:     if (($env{'request.role'} =~ /dc\./) &&
                   2202: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2203: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2204: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2205:        $userrolehash
                   2206:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2207:                     =$tend.':'.$tstart;
                   2208:     }
1.662     raeburn  2209:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2210:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2211:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2212:         ($trole=~/^sc/)) {
                   2213:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2214:        $domainrolehash
                   2215:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2216:                     = $tend.':'.$tstart;
                   2217:     }
1.351     www      2218: }
                   2219: 
                   2220: sub get_course_adv_roles {
                   2221:     my $cid=shift;
1.620     albertel 2222:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2223:     my %coursehash=&coursedescription($cid);
1.470     www      2224:     my %nothide=();
1.800     albertel 2225:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2226: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2227:     }
1.351     www      2228:     my %returnhash=();
                   2229:     my %dumphash=
                   2230:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2231:     my $now=time;
1.800     albertel 2232:     foreach my $entry (keys %dumphash) {
                   2233: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2234:         if (($tstart) && ($tstart<0)) { next; }
                   2235:         if (($tend) && ($tend<$now)) { next; }
                   2236:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2237:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2238: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2239: 	if ((&privileged($username,$domain)) && 
                   2240: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2241: 	if ($role eq 'cr') { next; }
1.351     www      2242:         my $key=&plaintext($role);
                   2243:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2244:         if ($returnhash{$key}) {
                   2245: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2246:         } else {
                   2247:             $returnhash{$key}=$username.':'.$domain;
                   2248:         }
1.400     www      2249:      }
                   2250:     return %returnhash;
                   2251: }
                   2252: 
                   2253: sub get_my_roles {
1.858     raeburn  2254:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2255:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2256:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2257:     my %dumphash;
                   2258:     if ($context eq 'userroles') { 
                   2259:         %dumphash = &dump('roles',$udom,$uname);
                   2260:     } else {
                   2261:         %dumphash=
1.400     www      2262:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2263:     }
1.400     www      2264:     my %returnhash=();
                   2265:     my $now=time;
1.800     albertel 2266:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2267:         my ($role,$tend,$tstart);
                   2268:         if ($context eq 'userroles') {
                   2269: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2270:         } else {
                   2271:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2272:         }
1.400     www      2273:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2274:         my $status = 'active';
                   2275:         if (($tend) && ($tend<$now)) {
                   2276:             $status = 'previous';
                   2277:         } 
                   2278:         if (($tstart) && ($now<$tstart)) {
                   2279:             $status = 'future';
                   2280:         }
                   2281:         if (ref($types) eq 'ARRAY') {
                   2282:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2283:                 next;
                   2284:             } 
                   2285:         } else {
                   2286:             if ($status ne 'active') {
                   2287:                 next;
                   2288:             }
                   2289:         }
1.867     raeburn  2290:         my ($rolecode,$username,$domain,$section,$area);
                   2291:         if ($context eq 'userroles') {
                   2292:             ($area,$rolecode) = split(/_/,$entry);
                   2293:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2294:         } else {
                   2295:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2296:         }
1.832     raeburn  2297:         if (ref($roledoms) eq 'ARRAY') {
                   2298:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2299:                 next;
                   2300:             }
                   2301:         }
                   2302:         if (ref($roles) eq 'ARRAY') {
                   2303:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2304:                 next;
                   2305:             }
1.867     raeburn  2306:         }
1.400     www      2307: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2308:     }
1.373     www      2309:     return %returnhash;
1.399     www      2310: }
                   2311: 
                   2312: # ----------------------------------------------------- Frontpage Announcements
                   2313: #
                   2314: #
                   2315: 
                   2316: sub postannounce {
                   2317:     my ($server,$text)=@_;
1.844     albertel 2318:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2319:     unless ($text=~/\w/) { $text=''; }
                   2320:     return &reply('setannounce:'.&escape($text),$server);
                   2321: }
                   2322: 
                   2323: sub getannounce {
1.448     albertel 2324: 
                   2325:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2326: 	my $announcement='';
1.800     albertel 2327: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2328: 	close($fh);
1.399     www      2329: 	if ($announcement=~/\w/) { 
                   2330: 	    return 
                   2331:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2332:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2333: 	} else {
                   2334: 	    return '';
                   2335: 	}
                   2336:     } else {
                   2337: 	return '';
                   2338:     }
1.351     www      2339: }
1.353     www      2340: 
                   2341: # ---------------------------------------------------------- Course ID routines
                   2342: # Deal with domain's nohist_courseid.db files
                   2343: #
                   2344: 
                   2345: sub courseidput {
                   2346:     my ($domain,$what,$coursehome)=@_;
                   2347:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2348: }
                   2349: 
                   2350: sub courseiddump {
1.791     raeburn  2351:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2352:     my %returnhash=();
1.355     www      2353:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2354:     my %libserv = &all_library();
                   2355:     foreach my $tryserver (keys(%libserv)) {
                   2356:         if ( (  $hostidflag == 1 
                   2357: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2358: 	     || (!defined($hostidflag)) ) {
                   2359: 
                   2360: 	    if ($domfilter eq ''
                   2361: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2362: 	        foreach my $line (
1.844     albertel 2363:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2364: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2365:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2366:                                $tryserver))) {
1.800     albertel 2367: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2368:                     if (($key) && ($value)) {
1.516     raeburn  2369: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2370:                     }
1.353     www      2371:                 }
                   2372:             }
                   2373:         }
                   2374:     }
                   2375:     return %returnhash;
                   2376: }
                   2377: 
1.658     raeburn  2378: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2379: 
                   2380: sub dcmailput {
1.685     raeburn  2381:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2382:     my $status = &Apache::lonnet::critical(
1.740     www      2383:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2384:        &escape($message),$server);
1.662     raeburn  2385:     return $status;
                   2386: }
                   2387: 
1.658     raeburn  2388: sub dcmaildump {
                   2389:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2390:     my %returnhash=();
1.846     albertel 2391: 
                   2392:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2393:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2394:                                                          &escape($enddate).':';
                   2395: 	my @esc_senders=map { &escape($_)} @$senders;
                   2396: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2397: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2398:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2399:             if (($key) && ($value)) {
                   2400:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2401:             }
                   2402:         }
                   2403:     }
                   2404:     return %returnhash;
                   2405: }
1.662     raeburn  2406: # ---------------------------------------------------------- Domain roles
                   2407: 
                   2408: sub get_domain_roles {
                   2409:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2410:     if (undef($startdate) || $startdate eq '') {
                   2411:         $startdate = '.';
                   2412:     }
                   2413:     if (undef($enddate) || $enddate eq '') {
                   2414:         $enddate = '.';
                   2415:     }
                   2416:     my $rolelist = join(':',@{$roles});
                   2417:     my %personnel = ();
1.841     albertel 2418: 
                   2419:     my %servers = &get_servers($dom,'library');
                   2420:     foreach my $tryserver (keys(%servers)) {
                   2421: 	%{$personnel{$tryserver}}=();
                   2422: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2423: 					    &escape($startdate).':'.
                   2424: 					    &escape($enddate).':'.
                   2425: 					    &escape($rolelist), $tryserver))) {
                   2426: 	    my ($key,$value) = split(/\=/,$line,2);
                   2427: 	    if (($key) && ($value)) {
                   2428: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2429: 	    }
                   2430: 	}
1.662     raeburn  2431:     }
                   2432:     return %personnel;
                   2433: }
1.658     raeburn  2434: 
1.149     www      2435: # ----------------------------------------------------------- Check out an item
                   2436: 
1.504     albertel 2437: sub get_first_access {
                   2438:     my ($type,$argsymb)=@_;
1.790     albertel 2439:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2440:     if ($argsymb) { $symb=$argsymb; }
                   2441:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2442:     if ($type eq 'map') {
                   2443: 	$res=&symbread($map);
                   2444:     } else {
                   2445: 	$res=$symb;
                   2446:     }
                   2447:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2448:     return $times{"$courseid\0$res"};
1.504     albertel 2449: }
                   2450: 
                   2451: sub set_first_access {
                   2452:     my ($type)=@_;
1.790     albertel 2453:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2454:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2455:     if ($type eq 'map') {
                   2456: 	$res=&symbread($map);
                   2457:     } else {
                   2458: 	$res=$symb;
                   2459:     }
                   2460:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2461:     if (!$firstaccess) {
1.588     albertel 2462: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2463:     }
                   2464:     return 'already_set';
1.504     albertel 2465: }
                   2466: 
1.149     www      2467: sub checkout {
                   2468:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2469:     my $now=time;
                   2470:     my $lonhost=$perlvar{'lonHostID'};
                   2471:     my $infostr=&escape(
1.234     www      2472:                  'CHECKOUTTOKEN&'.
1.149     www      2473:                  $tuname.'&'.
                   2474:                  $tudom.'&'.
                   2475:                  $tcrsid.'&'.
                   2476:                  $symb.'&'.
                   2477: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2478:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2479:     if ($token=~/^error\:/) { 
1.672     albertel 2480:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2481:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2482:                  "</font>");
                   2483:         return ''; 
                   2484:     }
                   2485: 
1.149     www      2486:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2487:     $token=~tr/a-z/A-Z/;
                   2488: 
1.153     www      2489:     my %infohash=('resource.0.outtoken' => $token,
                   2490:                   'resource.0.checkouttime' => $now,
                   2491:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2492: 
                   2493:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2494:        return '';
1.151     www      2495:     } else {
1.672     albertel 2496:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2497:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2498:                  "</font>");
1.149     www      2499:     }    
                   2500: 
                   2501:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2502:                          &escape('Checkout '.$infostr.' - '.
                   2503:                                                  $token)) ne 'ok') {
                   2504: 	return '';
1.151     www      2505:     } else {
1.672     albertel 2506:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2507:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2508:                  "</font>");
1.149     www      2509:     }
1.151     www      2510:     return $token;
1.149     www      2511: }
                   2512: 
                   2513: # ------------------------------------------------------------ Check in an item
                   2514: 
                   2515: sub checkin {
                   2516:     my $token=shift;
1.150     www      2517:     my $now=time;
                   2518:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2519:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2520:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2521:     $dtoken=~s/\W/\_/g;
1.234     www      2522:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2523:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2524: 
1.154     www      2525:     unless (($tuname) && ($tudom)) {
                   2526:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2527:         return '';
                   2528:     }
                   2529:     
                   2530:     unless (&allowed('mgr',$tcrsid)) {
                   2531:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2532:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2533:         return '';
                   2534:     }
                   2535: 
1.153     www      2536:     my %infohash=('resource.0.intoken' => $token,
                   2537:                   'resource.0.checkintime' => $now,
                   2538:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2539: 
                   2540:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2541:        return '';
                   2542:     }    
                   2543: 
                   2544:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2545:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2546: 	return '';
                   2547:     }
                   2548: 
                   2549:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2550: }
                   2551: 
                   2552: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2553: 
                   2554: sub expirespread {
                   2555:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2556:     my $cid=$env{'request.course.id'}; 
1.110     www      2557:     if ($cid) {
                   2558:        my $now=time;
                   2559:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2560:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2561:                             $env{'course.'.$cid.'.num'}.
1.110     www      2562: 	        	    ':nohist_expirationdates:'.
                   2563:                             &escape($key).'='.$now,
1.620     albertel 2564:                             $env{'course.'.$cid.'.home'})
1.110     www      2565:     }
                   2566:     return 'ok';
1.14      www      2567: }
                   2568: 
1.109     www      2569: # ----------------------------------------------------- Devalidate Spreadsheets
                   2570: 
                   2571: sub devalidate {
1.325     www      2572:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2573:     my $cid=$env{'request.course.id'}; 
1.109     www      2574:     if ($cid) {
1.391     matthew  2575:         # delete the stored spreadsheets for
                   2576:         # - the student level sheet of this user in course's homespace
                   2577:         # - the assessment level sheet for this resource 
                   2578:         #   for this user in user's homespace
1.553     albertel 2579: 	# - current conditional state info
1.325     www      2580: 	my $key=$uname.':'.$udom.':';
1.109     www      2581:         my $status=
1.299     matthew  2582: 	    &del('nohist_calculatedsheets',
1.391     matthew  2583: 		 [$key.'studentcalc:'],
1.620     albertel 2584: 		 $env{'course.'.$cid.'.domain'},
                   2585: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2586: 		.' '.
                   2587: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2588: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2589:         unless ($status eq 'ok ok') {
                   2590:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2591:                     $uname.' at '.$udom.' for '.
1.109     www      2592: 		    $symb.': '.$status);
1.133     albertel 2593:         }
1.553     albertel 2594: 	&delenv('user.state.'.$cid);
1.109     www      2595:     }
                   2596: }
                   2597: 
1.265     albertel 2598: sub get_scalar {
                   2599:     my ($string,$end) = @_;
                   2600:     my $value;
                   2601:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2602: 	$value = $1;
                   2603:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2604: 	$value = $1;
                   2605:     }
                   2606:     return &unescape($value);
                   2607: }
                   2608: 
                   2609: sub array2str {
                   2610:   my (@array) = @_;
                   2611:   my $result=&arrayref2str(\@array);
                   2612:   $result=~s/^__ARRAY_REF__//;
                   2613:   $result=~s/__END_ARRAY_REF__$//;
                   2614:   return $result;
                   2615: }
                   2616: 
1.204     albertel 2617: sub arrayref2str {
                   2618:   my ($arrayref) = @_;
1.265     albertel 2619:   my $result='__ARRAY_REF__';
1.204     albertel 2620:   foreach my $elem (@$arrayref) {
1.265     albertel 2621:     if(ref($elem) eq 'ARRAY') {
                   2622:       $result.=&arrayref2str($elem).'&';
                   2623:     } elsif(ref($elem) eq 'HASH') {
                   2624:       $result.=&hashref2str($elem).'&';
                   2625:     } elsif(ref($elem)) {
                   2626:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2627:     } else {
                   2628:       $result.=&escape($elem).'&';
                   2629:     }
                   2630:   }
                   2631:   $result=~s/\&$//;
1.265     albertel 2632:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2633:   return $result;
                   2634: }
                   2635: 
1.168     albertel 2636: sub hash2str {
1.204     albertel 2637:   my (%hash) = @_;
                   2638:   my $result=&hashref2str(\%hash);
1.265     albertel 2639:   $result=~s/^__HASH_REF__//;
                   2640:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2641:   return $result;
                   2642: }
                   2643: 
                   2644: sub hashref2str {
                   2645:   my ($hashref)=@_;
1.265     albertel 2646:   my $result='__HASH_REF__';
1.800     albertel 2647:   foreach my $key (sort(keys(%$hashref))) {
                   2648:     if (ref($key) eq 'ARRAY') {
                   2649:       $result.=&arrayref2str($key).'=';
                   2650:     } elsif (ref($key) eq 'HASH') {
                   2651:       $result.=&hashref2str($key).'=';
                   2652:     } elsif (ref($key)) {
1.265     albertel 2653:       $result.='=';
1.800     albertel 2654:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2655:     } else {
1.800     albertel 2656: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2657:     }
                   2658: 
1.800     albertel 2659:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2660:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2661:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2662:       $result.=&hashref2str($hashref->{$key}).'&';
                   2663:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2664:        $result.='&';
1.800     albertel 2665:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2666:     } else {
1.800     albertel 2667:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2668:     }
                   2669:   }
1.168     albertel 2670:   $result=~s/\&$//;
1.265     albertel 2671:   $result .= '__END_HASH_REF__';
1.168     albertel 2672:   return $result;
                   2673: }
                   2674: 
                   2675: sub str2hash {
1.265     albertel 2676:     my ($string)=@_;
                   2677:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2678:     return %$hash;
                   2679: }
                   2680: 
                   2681: sub str2hashref {
1.168     albertel 2682:   my ($string) = @_;
1.265     albertel 2683: 
                   2684:   my %hash;
                   2685: 
                   2686:   if($string !~ /^__HASH_REF__/) {
                   2687:       if (! ($string eq '' || !defined($string))) {
                   2688: 	  $hash{'error'}='Not hash reference';
                   2689:       }
                   2690:       return (\%hash, $string);
                   2691:   }
                   2692: 
                   2693:   $string =~ s/^__HASH_REF__//;
                   2694: 
                   2695:   while($string !~ /^__END_HASH_REF__/) {
                   2696:       #key
                   2697:       my $key='';
                   2698:       if($string =~ /^__HASH_REF__/) {
                   2699:           ($key, $string)=&str2hashref($string);
                   2700:           if(defined($key->{'error'})) {
                   2701:               $hash{'error'}='Bad data';
                   2702:               return (\%hash, $string);
                   2703:           }
                   2704:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2705:           ($key, $string)=&str2arrayref($string);
                   2706:           if($key->[0] eq 'Array reference error') {
                   2707:               $hash{'error'}='Bad data';
                   2708:               return (\%hash, $string);
                   2709:           }
                   2710:       } else {
                   2711:           $string =~ s/^(.*?)=//;
1.267     albertel 2712: 	  $key=&unescape($1);
1.265     albertel 2713:       }
                   2714:       $string =~ s/^=//;
                   2715: 
                   2716:       #value
                   2717:       my $value='';
                   2718:       if($string =~ /^__HASH_REF__/) {
                   2719:           ($value, $string)=&str2hashref($string);
                   2720:           if(defined($value->{'error'})) {
                   2721:               $hash{'error'}='Bad data';
                   2722:               return (\%hash, $string);
                   2723:           }
                   2724:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2725:           ($value, $string)=&str2arrayref($string);
                   2726:           if($value->[0] eq 'Array reference error') {
                   2727:               $hash{'error'}='Bad data';
                   2728:               return (\%hash, $string);
                   2729:           }
                   2730:       } else {
                   2731: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2732:       }
                   2733:       $string =~ s/^&//;
                   2734: 
                   2735:       $hash{$key}=$value;
1.204     albertel 2736:   }
1.265     albertel 2737: 
                   2738:   $string =~ s/^__END_HASH_REF__//;
                   2739: 
                   2740:   return (\%hash, $string);
1.204     albertel 2741: }
                   2742: 
                   2743: sub str2array {
1.265     albertel 2744:     my ($string)=@_;
                   2745:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2746:     return @$array;
                   2747: }
                   2748: 
                   2749: sub str2arrayref {
1.204     albertel 2750:   my ($string) = @_;
1.265     albertel 2751:   my @array;
                   2752: 
                   2753:   if($string !~ /^__ARRAY_REF__/) {
                   2754:       if (! ($string eq '' || !defined($string))) {
                   2755: 	  $array[0]='Array reference error';
                   2756:       }
                   2757:       return (\@array, $string);
                   2758:   }
                   2759: 
                   2760:   $string =~ s/^__ARRAY_REF__//;
                   2761: 
                   2762:   while($string !~ /^__END_ARRAY_REF__/) {
                   2763:       my $value='';
                   2764:       if($string =~ /^__HASH_REF__/) {
                   2765:           ($value, $string)=&str2hashref($string);
                   2766:           if(defined($value->{'error'})) {
                   2767:               $array[0] ='Array reference error';
                   2768:               return (\@array, $string);
                   2769:           }
                   2770:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2771:           ($value, $string)=&str2arrayref($string);
                   2772:           if($value->[0] eq 'Array reference error') {
                   2773:               $array[0] ='Array reference error';
                   2774:               return (\@array, $string);
                   2775:           }
                   2776:       } else {
                   2777: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2778:       }
                   2779:       $string =~ s/^&//;
                   2780: 
                   2781:       push(@array, $value);
1.191     harris41 2782:   }
1.265     albertel 2783: 
                   2784:   $string =~ s/^__END_ARRAY_REF__//;
                   2785: 
                   2786:   return (\@array, $string);
1.168     albertel 2787: }
                   2788: 
1.167     albertel 2789: # -------------------------------------------------------------------Temp Store
                   2790: 
1.168     albertel 2791: sub tmpreset {
                   2792:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2793:   if (!$symb) {
                   2794:     $symb=&symbread();
1.620     albertel 2795:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2796:   }
                   2797:   $symb=escape($symb);
                   2798: 
1.620     albertel 2799:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2800:   $namespace=~s/\//\_/g;
                   2801:   $namespace=~s/\W//g;
                   2802: 
1.620     albertel 2803:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2804:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2805:   if ($domain eq 'public' && $stuname eq 'public') {
                   2806:       $stuname=$ENV{'REMOTE_ADDR'};
                   2807:   }
1.168     albertel 2808:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2809:   my %hash;
                   2810:   if (tie(%hash,'GDBM_File',
                   2811: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2812: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2813:     foreach my $key (keys %hash) {
1.180     albertel 2814:       if ($key=~ /:$symb/) {
1.168     albertel 2815: 	delete($hash{$key});
                   2816:       }
                   2817:     }
                   2818:   }
                   2819: }
                   2820: 
1.167     albertel 2821: sub tmpstore {
1.168     albertel 2822:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2823: 
                   2824:   if (!$symb) {
                   2825:     $symb=&symbread();
1.620     albertel 2826:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2827:   }
                   2828:   $symb=escape($symb);
                   2829: 
                   2830:   if (!$namespace) {
                   2831:     # I don't think we would ever want to store this for a course.
                   2832:     # it seems this will only be used if we don't have a course.
1.620     albertel 2833:     #$namespace=$env{'request.course.id'};
1.168     albertel 2834:     #if (!$namespace) {
1.620     albertel 2835:       $namespace=$env{'request.state'};
1.168     albertel 2836:     #}
                   2837:   }
                   2838:   $namespace=~s/\//\_/g;
                   2839:   $namespace=~s/\W//g;
1.620     albertel 2840:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2841:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2842:   if ($domain eq 'public' && $stuname eq 'public') {
                   2843:       $stuname=$ENV{'REMOTE_ADDR'};
                   2844:   }
1.168     albertel 2845:   my $now=time;
                   2846:   my %hash;
                   2847:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2848:   if (tie(%hash,'GDBM_File',
                   2849: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2850: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2851:     $hash{"version:$symb"}++;
                   2852:     my $version=$hash{"version:$symb"};
                   2853:     my $allkeys=''; 
                   2854:     foreach my $key (keys(%$storehash)) {
                   2855:       $allkeys.=$key.':';
1.591     albertel 2856:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2857:     }
                   2858:     $hash{"$version:$symb:timestamp"}=$now;
                   2859:     $allkeys.='timestamp';
                   2860:     $hash{"$version:keys:$symb"}=$allkeys;
                   2861:     if (untie(%hash)) {
                   2862:       return 'ok';
                   2863:     } else {
                   2864:       return "error:$!";
                   2865:     }
                   2866:   } else {
                   2867:     return "error:$!";
                   2868:   }
                   2869: }
1.167     albertel 2870: 
1.168     albertel 2871: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2872: 
1.168     albertel 2873: sub tmprestore {
                   2874:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2875: 
1.168     albertel 2876:   if (!$symb) {
                   2877:     $symb=&symbread();
1.620     albertel 2878:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2879:   }
                   2880:   $symb=escape($symb);
                   2881: 
1.620     albertel 2882:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2883: 
1.620     albertel 2884:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2885:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2886:   if ($domain eq 'public' && $stuname eq 'public') {
                   2887:       $stuname=$ENV{'REMOTE_ADDR'};
                   2888:   }
1.168     albertel 2889:   my %returnhash;
                   2890:   $namespace=~s/\//\_/g;
                   2891:   $namespace=~s/\W//g;
                   2892:   my %hash;
                   2893:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2894:   if (tie(%hash,'GDBM_File',
                   2895: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2896: 	  &GDBM_READER(),0640)) {
1.168     albertel 2897:     my $version=$hash{"version:$symb"};
                   2898:     $returnhash{'version'}=$version;
                   2899:     my $scope;
                   2900:     for ($scope=1;$scope<=$version;$scope++) {
                   2901:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2902:       my @keys=split(/:/,$vkeys);
                   2903:       my $key;
                   2904:       $returnhash{"$scope:keys"}=$vkeys;
                   2905:       foreach $key (@keys) {
1.591     albertel 2906: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2907: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2908:       }
                   2909:     }
1.168     albertel 2910:     if (!(untie(%hash))) {
                   2911:       return "error:$!";
                   2912:     }
                   2913:   } else {
                   2914:     return "error:$!";
                   2915:   }
                   2916:   return %returnhash;
1.167     albertel 2917: }
                   2918: 
1.9       www      2919: # ----------------------------------------------------------------------- Store
                   2920: 
                   2921: sub store {
1.124     www      2922:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2923:     my $home='';
                   2924: 
1.168     albertel 2925:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2926: 
1.213     www      2927:     $symb=&symbclean($symb);
1.122     albertel 2928:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2929: 
1.620     albertel 2930:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2931:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2932: 
                   2933:     &devalidate($symb,$stuname,$domain);
1.109     www      2934: 
                   2935:     $symb=escape($symb);
1.187     www      2936:     if (!$namespace) { 
1.620     albertel 2937:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2938:           return ''; 
                   2939:        } 
                   2940:     }
1.620     albertel 2941:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2942: 
                   2943:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2944:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2945: 
1.12      www      2946:     my $namevalue='';
1.800     albertel 2947:     foreach my $key (keys(%$storehash)) {
                   2948:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2949:     }
1.12      www      2950:     $namevalue=~s/\&$//;
1.187     www      2951:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2952:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2953: }
                   2954: 
1.47      www      2955: # -------------------------------------------------------------- Critical Store
                   2956: 
                   2957: sub cstore {
1.124     www      2958:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2959:     my $home='';
                   2960: 
1.168     albertel 2961:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2962: 
1.213     www      2963:     $symb=&symbclean($symb);
1.122     albertel 2964:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2965: 
1.620     albertel 2966:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2967:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2968: 
                   2969:     &devalidate($symb,$stuname,$domain);
1.109     www      2970: 
                   2971:     $symb=escape($symb);
1.187     www      2972:     if (!$namespace) { 
1.620     albertel 2973:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2974:           return ''; 
                   2975:        } 
                   2976:     }
1.620     albertel 2977:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2978: 
                   2979:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2980:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2981: 
1.47      www      2982:     my $namevalue='';
1.800     albertel 2983:     foreach my $key (keys(%$storehash)) {
                   2984:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2985:     }
1.47      www      2986:     $namevalue=~s/\&$//;
1.187     www      2987:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2988:     return critical
                   2989:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2990: }
                   2991: 
1.9       www      2992: # --------------------------------------------------------------------- Restore
                   2993: 
                   2994: sub restore {
1.124     www      2995:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2996:     my $home='';
                   2997: 
1.168     albertel 2998:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2999: 
1.122     albertel 3000:     if (!$symb) {
                   3001:       unless ($symb=escape(&symbread())) { return ''; }
                   3002:     } else {
1.213     www      3003:       $symb=&escape(&symbclean($symb));
1.122     albertel 3004:     }
1.188     www      3005:     if (!$namespace) { 
1.620     albertel 3006:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3007:           return ''; 
                   3008:        } 
                   3009:     }
1.620     albertel 3010:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3011:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3012:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3013:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3014: 
1.12      www      3015:     my %returnhash=();
1.800     albertel 3016:     foreach my $line (split(/\&/,$answer)) {
                   3017: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3018:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3019:     }
1.75      www      3020:     my $version;
                   3021:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3022:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3023:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3024:        }
1.75      www      3025:     }
1.13      www      3026:     return %returnhash;
1.34      www      3027: }
                   3028: 
                   3029: # ---------------------------------------------------------- Course Description
                   3030: 
                   3031: sub coursedescription {
1.731     albertel 3032:     my ($courseid,$args)=@_;
1.34      www      3033:     $courseid=~s/^\///;
1.49      www      3034:     $courseid=~s/\_/\//g;
1.34      www      3035:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3036:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3037:     my $normalid=$cdomain.'_'.$cnum;
                   3038:     # need to always cache even if we get errors otherwise we keep 
                   3039:     # trying and trying and trying to get the course description.
                   3040:     my %envhash=();
                   3041:     my %returnhash=();
1.731     albertel 3042:     
                   3043:     my $expiretime=600;
                   3044:     if ($env{'request.course.id'} eq $normalid) {
                   3045: 	$expiretime=120;
                   3046:     }
                   3047: 
                   3048:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3049:     if (!$args->{'freshen_cache'}
                   3050: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3051: 	foreach my $key (keys(%env)) {
                   3052: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3053: 	    my ($setting) = $1;
                   3054: 	    $returnhash{$setting} = $env{$key};
                   3055: 	}
                   3056: 	return %returnhash;
                   3057:     }
                   3058: 
                   3059:     # get the data agin
                   3060:     if (!$args->{'one_time'}) {
                   3061: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3062:     }
1.811     albertel 3063: 
1.34      www      3064:     if ($chome ne 'no_host') {
1.302     albertel 3065:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3066:        if (!exists($returnhash{'con_lost'})) {
                   3067:            $returnhash{'home'}= $chome;
                   3068: 	   $returnhash{'domain'} = $cdomain;
                   3069: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3070:            if (!defined($returnhash{'type'})) {
                   3071:                $returnhash{'type'} = 'Course';
                   3072:            }
1.130     albertel 3073:            while (my ($name,$value) = each %returnhash) {
1.53      www      3074:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3075:            }
1.270     www      3076:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3077:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3078: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3079:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3080:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3081:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3082:        }
                   3083:     }
1.731     albertel 3084:     if (!$args->{'one_time'}) {
                   3085: 	&appenv(%envhash);
                   3086:     }
1.302     albertel 3087:     return %returnhash;
1.461     www      3088: }
                   3089: 
                   3090: # -------------------------------------------------See if a user is privileged
                   3091: 
                   3092: sub privileged {
                   3093:     my ($username,$domain)=@_;
                   3094:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3095: 			&homeserver($username,$domain));
                   3096:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3097:     my $now=time;
                   3098:     if ($rolesdump ne '') {
1.800     albertel 3099:         foreach my $entry (split(/&/,$rolesdump)) {
                   3100: 	    if ($entry!~/^rolesdef_/) {
                   3101: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3102: 		$area=~s/\_\w\w$//;
                   3103: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3104: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3105: 		    my $active=1;
                   3106: 		    if ($tend) {
                   3107: 			if ($tend<$now) { $active=0; }
                   3108: 		    }
                   3109: 		    if ($tstart) {
                   3110: 			if ($tstart>$now) { $active=0; }
                   3111: 		    }
                   3112: 		    if ($active) { return 1; }
                   3113: 		}
                   3114: 	    }
                   3115: 	}
                   3116:     }
                   3117:     return 0;
1.9       www      3118: }
1.1       albertel 3119: 
1.103     harris41 3120: # -------------------------------------------------------- Get user privileges
1.11      www      3121: 
                   3122: sub rolesinit {
                   3123:     my ($domain,$username,$authhost)=@_;
                   3124:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3125:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3126:     my %allroles=();
1.678     raeburn  3127:     my %allgroups=();   
1.11      www      3128:     my $now=time;
1.743     albertel 3129:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3130:     my $group_privs;
1.11      www      3131: 
                   3132:     if ($rolesdump ne '') {
1.800     albertel 3133:         foreach my $entry (split(/&/,$rolesdump)) {
                   3134: 	  if ($entry!~/^rolesdef_/) {
                   3135:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3136: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3137:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3138: 	    if ($role=~/^cr/) { 
1.807     albertel 3139: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3140: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3141: 		    ($tend,$tstart)=split('_',$trest);
                   3142: 		} else {
                   3143: 		    $trole=$role;
                   3144: 		}
1.678     raeburn  3145:             } elsif ($role =~ m|^gr/|) {
                   3146:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3147:                 ($trole,$group_privs) = split(/\//,$trole);
                   3148:                 $group_privs = &unescape($group_privs);
1.587     albertel 3149: 	    } else {
                   3150: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3151: 	    }
1.743     albertel 3152: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3153: 					 $username);
                   3154: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3155:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3156:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3157:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3158: 		my $spec=$trole.'.'.$area;
                   3159: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3160: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3161:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3162:                 } elsif ($trole eq 'gr') {
                   3163:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3164: 		} else {
1.567     raeburn  3165:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3166: 		}
1.12      www      3167:             }
1.662     raeburn  3168:           }
1.191     harris41 3169:         }
1.743     albertel 3170:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3171:         $userroles{'user.adv'}    = $adv;
                   3172: 	$userroles{'user.author'} = $author;
1.620     albertel 3173:         $env{'user.adv'}=$adv;
1.11      www      3174:     }
1.743     albertel 3175:     return \%userroles;  
1.11      www      3176: }
                   3177: 
1.567     raeburn  3178: sub set_arearole {
                   3179:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3180: # log the associated role with the area
                   3181:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3182:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3183: }
                   3184: 
                   3185: sub custom_roleprivs {
                   3186:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3187:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3188:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3189:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3190:         my ($rdummy,$roledef)=
                   3191:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3192:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3193:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3194:             if (defined($syspriv)) {
                   3195:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3196:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3197:             }
                   3198:             if ($tdomain ne '') {
                   3199:                 if (defined($dompriv)) {
                   3200:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3201:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3202:                 }
                   3203:                 if (($trest ne '') && (defined($coursepriv))) {
                   3204:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3205:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3206:                 }
                   3207:             }
                   3208:         }
                   3209:     }
                   3210: }
                   3211: 
1.678     raeburn  3212: sub group_roleprivs {
                   3213:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3214:     my $access = 1;
                   3215:     my $now = time;
                   3216:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3217:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3218:     if ($access) {
1.811     albertel 3219:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3220:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3221:     }
                   3222: }
1.567     raeburn  3223: 
                   3224: sub standard_roleprivs {
                   3225:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3226:     if (defined($pr{$trole.':s'})) {
                   3227:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3228:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3229:     }
                   3230:     if ($tdomain ne '') {
                   3231:         if (defined($pr{$trole.':d'})) {
                   3232:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3233:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3234:         }
                   3235:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3236:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3237:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3238:         }
                   3239:     }
                   3240: }
                   3241: 
                   3242: sub set_userprivs {
1.678     raeburn  3243:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3244:     my $author=0;
                   3245:     my $adv=0;
1.678     raeburn  3246:     my %grouproles = ();
                   3247:     if (keys(%{$allgroups}) > 0) {
                   3248:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3249:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3250:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3251:                 $trole = $1;
                   3252:                 $area = $2;
1.681     raeburn  3253:                 $sec = $3;
                   3254:                 $extendedarea = $area.$sec;
                   3255:                 if (exists($$allgroups{$area})) {
                   3256:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3257:                         my $spec = $trole.'.'.$extendedarea;
                   3258:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3259:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3260:                     }
                   3261:                 }
                   3262:             }
                   3263:         }
                   3264:     }
1.800     albertel 3265:     foreach my $group (keys(%grouproles)) {
                   3266:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3267:     }
1.800     albertel 3268:     foreach my $role (keys(%{$allroles})) {
                   3269:         my %thesepriv;
                   3270:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3271:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3272:             if ($item ne '') {
                   3273:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3274:                 if ($restrictions eq '') {
                   3275:                     $thesepriv{$privilege}='F';
                   3276:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3277:                     $thesepriv{$privilege}.=$restrictions;
                   3278:                 }
                   3279:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3280:             }
                   3281:         }
                   3282:         my $thesestr='';
1.800     albertel 3283:         foreach my $priv (keys(%thesepriv)) {
                   3284: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3285: 	}
                   3286:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3287:     }
                   3288:     return ($author,$adv);
                   3289: }
                   3290: 
1.12      www      3291: # --------------------------------------------------------------- get interface
                   3292: 
                   3293: sub get {
1.131     albertel 3294:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3295:    my $items='';
1.800     albertel 3296:    foreach my $item (@$storearr) {
                   3297:        $items.=&escape($item).'&';
1.191     harris41 3298:    }
1.12      www      3299:    $items=~s/\&$//;
1.620     albertel 3300:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3301:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3302:    my $uhome=&homeserver($uname,$udomain);
                   3303: 
1.133     albertel 3304:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3305:    my @pairs=split(/\&/,$rep);
1.273     albertel 3306:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3307:      return @pairs;
                   3308:    }
1.15      www      3309:    my %returnhash=();
1.42      www      3310:    my $i=0;
1.800     albertel 3311:    foreach my $item (@$storearr) {
                   3312:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3313:       $i++;
1.191     harris41 3314:    }
1.15      www      3315:    return %returnhash;
1.27      www      3316: }
                   3317: 
                   3318: # --------------------------------------------------------------- del interface
                   3319: 
                   3320: sub del {
1.133     albertel 3321:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3322:    my $items='';
1.800     albertel 3323:    foreach my $item (@$storearr) {
                   3324:        $items.=&escape($item).'&';
1.191     harris41 3325:    }
1.27      www      3326:    $items=~s/\&$//;
1.620     albertel 3327:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3328:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3329:    my $uhome=&homeserver($uname,$udomain);
                   3330: 
                   3331:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3332: }
                   3333: 
                   3334: # -------------------------------------------------------------- dump interface
                   3335: 
                   3336: sub dump {
1.755     albertel 3337:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3338:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3339:     if (!$uname) { $uname=$env{'user.name'}; }
                   3340:     my $uhome=&homeserver($uname,$udomain);
                   3341:     if ($regexp) {
                   3342: 	$regexp=&escape($regexp);
                   3343:     } else {
                   3344: 	$regexp='.';
                   3345:     }
                   3346:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3347:     my @pairs=split(/\&/,$rep);
                   3348:     my %returnhash=();
                   3349:     foreach my $item (@pairs) {
                   3350: 	my ($key,$value)=split(/=/,$item,2);
                   3351: 	$key = &unescape($key);
                   3352: 	next if ($key =~ /^error: 2 /);
                   3353: 	$returnhash{$key}=&thaw_unescape($value);
                   3354:     }
                   3355:     return %returnhash;
1.407     www      3356: }
                   3357: 
1.717     albertel 3358: # --------------------------------------------------------- dumpstore interface
                   3359: 
                   3360: sub dumpstore {
                   3361:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3362:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3363:    if (!$uname) { $uname=$env{'user.name'}; }
                   3364:    my $uhome=&homeserver($uname,$udomain);
                   3365:    if ($regexp) {
                   3366:        $regexp=&escape($regexp);
                   3367:    } else {
                   3368:        $regexp='.';
                   3369:    }
                   3370:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3371:    my @pairs=split(/\&/,$rep);
                   3372:    my %returnhash=();
                   3373:    foreach my $item (@pairs) {
                   3374:        my ($key,$value)=split(/=/,$item,2);
                   3375:        next if ($key =~ /^error: 2 /);
                   3376:        $returnhash{$key}=&thaw_unescape($value);
                   3377:    }
                   3378:    return %returnhash;
1.717     albertel 3379: }
                   3380: 
1.407     www      3381: # -------------------------------------------------------------- keys interface
                   3382: 
                   3383: sub getkeys {
                   3384:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3385:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3386:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3387:    my $uhome=&homeserver($uname,$udomain);
                   3388:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3389:    my @keyarray=();
1.800     albertel 3390:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3391:       next if ($key =~ /^error: 2 /);
1.800     albertel 3392:       push(@keyarray,&unescape($key));
1.407     www      3393:    }
                   3394:    return @keyarray;
1.318     matthew  3395: }
                   3396: 
1.319     matthew  3397: # --------------------------------------------------------------- currentdump
                   3398: sub currentdump {
1.328     matthew  3399:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3400:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3401:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3402:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3403:    my $uhome = &homeserver($sname,$sdom);
                   3404:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3405:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3406:    #
1.318     matthew  3407:    my %returnhash=();
1.319     matthew  3408:    #
                   3409:    if ($rep eq "unknown_cmd") { 
                   3410:        # an old lond will not know currentdump
                   3411:        # Do a dump and make it look like a currentdump
1.822     albertel 3412:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3413:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3414:        my %hash = @tmp;
                   3415:        @tmp=();
1.424     matthew  3416:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3417:    } else {
                   3418:        my @pairs=split(/\&/,$rep);
1.800     albertel 3419:        foreach my $pair (@pairs) {
                   3420:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3421:            my ($symb,$param) = split(/:/,$key);
                   3422:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3423:                                                         &thaw_unescape($value);
1.319     matthew  3424:        }
1.191     harris41 3425:    }
1.12      www      3426:    return %returnhash;
1.424     matthew  3427: }
                   3428: 
                   3429: sub convert_dump_to_currentdump{
                   3430:     my %hash = %{shift()};
                   3431:     my %returnhash;
                   3432:     # Code ripped from lond, essentially.  The only difference
                   3433:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3434:     # we might run in to problems with parameter names =~ /^v\./
                   3435:     while (my ($key,$value) = each(%hash)) {
                   3436:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3437: 	$symb  = &unescape($symb);
                   3438: 	$param = &unescape($param);
1.424     matthew  3439:         next if ($v eq 'version' || $symb eq 'keys');
                   3440:         next if (exists($returnhash{$symb}) &&
                   3441:                  exists($returnhash{$symb}->{$param}) &&
                   3442:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3443:         $returnhash{$symb}->{$param}=$value;
                   3444:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3445:     }
                   3446:     #
                   3447:     # Remove all of the keys in the hashes which keep track of
                   3448:     # the version of the parameter.
                   3449:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3450:         # use a foreach because we are going to delete from the hash.
                   3451:         foreach my $key (keys(%$param_hash)) {
                   3452:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3453:         }
                   3454:     }
                   3455:     return \%returnhash;
1.12      www      3456: }
                   3457: 
1.627     albertel 3458: # ------------------------------------------------------ critical inc interface
                   3459: 
                   3460: sub cinc {
                   3461:     return &inc(@_,'critical');
                   3462: }
                   3463: 
1.449     matthew  3464: # --------------------------------------------------------------- inc interface
                   3465: 
                   3466: sub inc {
1.627     albertel 3467:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3468:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3469:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3470:     my $uhome=&homeserver($uname,$udomain);
                   3471:     my $items='';
                   3472:     if (! ref($store)) {
                   3473:         # got a single value, so use that instead
                   3474:         $items = &escape($store).'=&';
                   3475:     } elsif (ref($store) eq 'SCALAR') {
                   3476:         $items = &escape($$store).'=&';        
                   3477:     } elsif (ref($store) eq 'ARRAY') {
                   3478:         $items = join('=&',map {&escape($_);} @{$store});
                   3479:     } elsif (ref($store) eq 'HASH') {
                   3480:         while (my($key,$value) = each(%{$store})) {
                   3481:             $items.= &escape($key).'='.&escape($value).'&';
                   3482:         }
                   3483:     }
                   3484:     $items=~s/\&$//;
1.627     albertel 3485:     if ($critical) {
                   3486: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3487:     } else {
                   3488: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3489:     }
1.449     matthew  3490: }
                   3491: 
1.12      www      3492: # --------------------------------------------------------------- put interface
                   3493: 
                   3494: sub put {
1.134     albertel 3495:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3496:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3497:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3498:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3499:    my $items='';
1.800     albertel 3500:    foreach my $item (keys(%$storehash)) {
                   3501:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3502:    }
1.12      www      3503:    $items=~s/\&$//;
1.134     albertel 3504:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3505: }
                   3506: 
1.631     albertel 3507: # ------------------------------------------------------------ newput interface
                   3508: 
                   3509: sub newput {
                   3510:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3511:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3512:    if (!$uname) { $uname=$env{'user.name'}; }
                   3513:    my $uhome=&homeserver($uname,$udomain);
                   3514:    my $items='';
                   3515:    foreach my $key (keys(%$storehash)) {
                   3516:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3517:    }
                   3518:    $items=~s/\&$//;
                   3519:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3520: }
                   3521: 
                   3522: # ---------------------------------------------------------  putstore interface
                   3523: 
1.524     raeburn  3524: sub putstore {
1.715     albertel 3525:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3526:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3527:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3528:    my $uhome=&homeserver($uname,$udomain);
                   3529:    my $items='';
1.715     albertel 3530:    foreach my $key (keys(%$storehash)) {
                   3531:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3532:    }
1.715     albertel 3533:    $items=~s/\&$//;
1.716     albertel 3534:    my $esc_symb=&escape($symb);
                   3535:    my $esc_v=&escape($version);
1.715     albertel 3536:    my $reply =
1.716     albertel 3537:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3538: 	      $uhome);
                   3539:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3540:        # gfall back to way things use to be done
1.715     albertel 3541:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3542: 			    $uname);
1.524     raeburn  3543:    }
1.715     albertel 3544:    return $reply;
                   3545: }
                   3546: 
                   3547: sub old_putstore {
1.716     albertel 3548:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3549:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3550:     if (!$uname) { $uname=$env{'user.name'}; }
                   3551:     my $uhome=&homeserver($uname,$udomain);
                   3552:     my %newstorehash;
1.800     albertel 3553:     foreach my $item (keys(%$storehash)) {
                   3554: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3555: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3556:     }
                   3557:     my $items='';
                   3558:     my %allitems = ();
1.800     albertel 3559:     foreach my $item (keys(%newstorehash)) {
                   3560: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3561: 	    my $key = $1.':keys:'.$2;
                   3562: 	    $allitems{$key} .= $3.':';
                   3563: 	}
1.800     albertel 3564: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3565:     }
1.800     albertel 3566:     foreach my $item (keys(%allitems)) {
                   3567: 	$allitems{$item} =~ s/\:$//;
                   3568: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3569:     }
                   3570:     $items=~s/\&$//;
                   3571:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3572: }
                   3573: 
1.47      www      3574: # ------------------------------------------------------ critical put interface
                   3575: 
                   3576: sub cput {
1.134     albertel 3577:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3578:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3579:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3580:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3581:    my $items='';
1.800     albertel 3582:    foreach my $item (keys(%$storehash)) {
                   3583:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3584:    }
1.47      www      3585:    $items=~s/\&$//;
1.134     albertel 3586:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3587: }
                   3588: 
                   3589: # -------------------------------------------------------------- eget interface
                   3590: 
                   3591: sub eget {
1.133     albertel 3592:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3593:    my $items='';
1.800     albertel 3594:    foreach my $item (@$storearr) {
                   3595:        $items.=&escape($item).'&';
1.191     harris41 3596:    }
1.12      www      3597:    $items=~s/\&$//;
1.620     albertel 3598:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3599:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3600:    my $uhome=&homeserver($uname,$udomain);
                   3601:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3602:    my @pairs=split(/\&/,$rep);
                   3603:    my %returnhash=();
1.42      www      3604:    my $i=0;
1.800     albertel 3605:    foreach my $item (@$storearr) {
                   3606:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3607:       $i++;
1.191     harris41 3608:    }
1.12      www      3609:    return %returnhash;
                   3610: }
                   3611: 
1.667     albertel 3612: # ------------------------------------------------------------ tmpput interface
                   3613: sub tmpput {
1.802     raeburn  3614:     my ($storehash,$server,$context)=@_;
1.667     albertel 3615:     my $items='';
1.800     albertel 3616:     foreach my $item (keys(%$storehash)) {
                   3617: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3618:     }
                   3619:     $items=~s/\&$//;
1.802     raeburn  3620:     if (defined($context)) {
                   3621:         $items .= ':'.&escape($context);
                   3622:     }
1.667     albertel 3623:     return &reply("tmpput:$items",$server);
                   3624: }
                   3625: 
                   3626: # ------------------------------------------------------------ tmpget interface
                   3627: sub tmpget {
1.688     albertel 3628:     my ($token,$server)=@_;
                   3629:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3630:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3631:     my %returnhash;
                   3632:     foreach my $item (split(/\&/,$rep)) {
                   3633: 	my ($key,$value)=split(/=/,$item);
                   3634: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3635:     }
                   3636:     return %returnhash;
                   3637: }
                   3638: 
1.688     albertel 3639: # ------------------------------------------------------------ tmpget interface
                   3640: sub tmpdel {
                   3641:     my ($token,$server)=@_;
                   3642:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3643:     return &reply("tmpdel:$token",$server);
                   3644: }
                   3645: 
1.765     albertel 3646: # -------------------------------------------------- portfolio access checking
                   3647: 
                   3648: sub portfolio_access {
1.766     albertel 3649:     my ($requrl) = @_;
1.765     albertel 3650:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3651:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3652:     if ($result) {
                   3653:         my %setters;
                   3654:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3655:             my ($startblock,$endblock) =
                   3656:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3657:             if ($startblock && $endblock) {
                   3658:                 return 'B';
                   3659:             }
                   3660:         } else {
                   3661:             my ($startblock,$endblock) =
                   3662:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3663:             if ($startblock && $endblock) {
                   3664:                 return 'B';
                   3665:             }
                   3666:         }
                   3667:     }
1.765     albertel 3668:     if ($result eq 'ok') {
1.766     albertel 3669:        return 'F';
1.765     albertel 3670:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3671:        return 'A';
1.765     albertel 3672:     }
1.766     albertel 3673:     return '';
1.765     albertel 3674: }
                   3675: 
                   3676: sub get_portfolio_access {
1.767     albertel 3677:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3678: 
                   3679:     if (!ref($access_hash)) {
                   3680: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3681: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3682: 						   $file_name);
                   3683: 	$access_hash = $access_controls{$file_name};
                   3684:     }
                   3685: 
1.765     albertel 3686:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3687:     my $now = time;
                   3688:     if (ref($access_hash) eq 'HASH') {
                   3689:         foreach my $key (keys(%{$access_hash})) {
                   3690:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3691:             if ($start > $now) {
                   3692:                 next;
                   3693:             }
                   3694:             if ($end && $end<$now) {
                   3695:                 next;
                   3696:             }
                   3697:             if ($scope eq 'public') {
                   3698:                 $public = $key;
                   3699:                 last;
                   3700:             } elsif ($scope eq 'guest') {
                   3701:                 $guest = $key;
                   3702:             } elsif ($scope eq 'domains') {
                   3703:                 push(@domains,$key);
                   3704:             } elsif ($scope eq 'users') {
                   3705:                 push(@users,$key);
                   3706:             } elsif ($scope eq 'course') {
                   3707:                 push(@courses,$key);
                   3708:             } elsif ($scope eq 'group') {
                   3709:                 push(@groups,$key);
                   3710:             }
                   3711:         }
                   3712:         if ($public) {
                   3713:             return 'ok';
                   3714:         }
                   3715:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3716:             if ($guest) {
                   3717:                 return $guest;
                   3718:             }
                   3719:         } else {
                   3720:             if (@domains > 0) {
                   3721:                 foreach my $domkey (@domains) {
                   3722:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3723:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3724:                             return 'ok';
                   3725:                         }
                   3726:                     }
                   3727:                 }
                   3728:             }
                   3729:             if (@users > 0) {
                   3730:                 foreach my $userkey (@users) {
1.865     raeburn  3731:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3732:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3733:                             if (ref($item) eq 'HASH') {
                   3734:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3735:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3736:                                     return 'ok';
                   3737:                                 }
                   3738:                             }
                   3739:                         }
                   3740:                     } 
1.765     albertel 3741:                 }
                   3742:             }
                   3743:             my %roleshash;
                   3744:             my @courses_and_groups = @courses;
                   3745:             push(@courses_and_groups,@groups); 
                   3746:             if (@courses_and_groups > 0) {
                   3747:                 my (%allgroups,%allroles); 
                   3748:                 my ($start,$end,$role,$sec,$group);
                   3749:                 foreach my $envkey (%env) {
1.811     albertel 3750:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3751:                         my $cid = $2.'_'.$3; 
                   3752:                         if ($1 eq 'gr') {
                   3753:                             $group = $4;
                   3754:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3755:                         } else {
                   3756:                             if ($4 eq '') {
                   3757:                                 $sec = 'none';
                   3758:                             } else {
                   3759:                                 $sec = $4;
                   3760:                             }
                   3761:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3762:                         }
1.811     albertel 3763:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3764:                         my $cid = $2.'_'.$3;
                   3765:                         if ($4 eq '') {
                   3766:                             $sec = 'none';
                   3767:                         } else {
                   3768:                             $sec = $4;
                   3769:                         }
                   3770:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3771:                     }
                   3772:                 }
                   3773:                 if (keys(%allroles) == 0) {
                   3774:                     return;
                   3775:                 }
                   3776:                 foreach my $key (@courses_and_groups) {
                   3777:                     my %content = %{$$access_hash{$key}};
                   3778:                     my $cnum = $content{'number'};
                   3779:                     my $cdom = $content{'domain'};
                   3780:                     my $cid = $cdom.'_'.$cnum;
                   3781:                     if (!exists($allroles{$cid})) {
                   3782:                         next;
                   3783:                     }    
                   3784:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3785:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3786:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3787:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3788:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3789:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3790:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3791:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3792:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3793:                                         if (grep/^all$/,@sections) {
                   3794:                                             return 'ok';
                   3795:                                         } else {
                   3796:                                             if (grep/^$sec$/,@sections) {
                   3797:                                                 return 'ok';
                   3798:                                             }
                   3799:                                         }
                   3800:                                     }
                   3801:                                 }
                   3802:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3803:                                     if (grep/^none$/,@groups) {
                   3804:                                         return 'ok';
                   3805:                                     }
                   3806:                                 } else {
                   3807:                                     if (grep/^all$/,@groups) {
                   3808:                                         return 'ok';
                   3809:                                     } 
                   3810:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3811:                                         if (grep/^$group$/,@groups) {
                   3812:                                             return 'ok';
                   3813:                                         }
                   3814:                                     }
                   3815:                                 } 
                   3816:                             }
                   3817:                         }
                   3818:                     }
                   3819:                 }
                   3820:             }
                   3821:             if ($guest) {
                   3822:                 return $guest;
                   3823:             }
                   3824:         }
                   3825:     }
                   3826:     return;
                   3827: }
                   3828: 
                   3829: sub course_group_datechecker {
                   3830:     my ($dates,$now,$status) = @_;
                   3831:     my ($start,$end) = split(/\./,$dates);
                   3832:     if (!$start && !$end) {
                   3833:         return 'ok';
                   3834:     }
                   3835:     if (grep/^active$/,@{$status}) {
                   3836:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3837:             return 'ok';
                   3838:         }
                   3839:     }
                   3840:     if (grep/^previous$/,@{$status}) {
                   3841:         if ($end > $now ) {
                   3842:             return 'ok';
                   3843:         }
                   3844:     }
                   3845:     if (grep/^future$/,@{$status}) {
                   3846:         if ($start > $now) {
                   3847:             return 'ok';
                   3848:         }
                   3849:     }
                   3850:     return; 
                   3851: }
                   3852: 
                   3853: sub parse_portfolio_url {
                   3854:     my ($url) = @_;
                   3855: 
                   3856:     my ($type,$udom,$unum,$group,$file_name);
                   3857:     
1.823     albertel 3858:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3859: 	$type = 1;
                   3860:         $udom = $1;
                   3861:         $unum = $2;
                   3862:         $file_name = $3;
1.823     albertel 3863:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3864: 	$type = 2;
                   3865:         $udom = $1;
                   3866:         $unum = $2;
                   3867:         $group = $3;
                   3868:         $file_name = $3.'/'.$4;
                   3869:     }
                   3870:     if (wantarray) {
                   3871: 	return ($type,$udom,$unum,$file_name,$group);
                   3872:     }
                   3873:     return $type;
                   3874: }
                   3875: 
                   3876: sub is_portfolio_url {
                   3877:     my ($url) = @_;
                   3878:     return scalar(&parse_portfolio_url($url));
                   3879: }
                   3880: 
1.798     raeburn  3881: sub is_portfolio_file {
                   3882:     my ($file) = @_;
1.820     raeburn  3883:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3884:         return 1;
                   3885:     }
                   3886:     return;
                   3887: }
                   3888: 
                   3889: 
1.341     www      3890: # ---------------------------------------------- Custom access rule evaluation
                   3891: 
                   3892: sub customaccess {
                   3893:     my ($priv,$uri)=@_;
1.807     albertel 3894:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3895:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3896:     $udom = &LONCAPA::clean_domain($udom);
                   3897:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3898:     my $access=0;
1.800     albertel 3899:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 3900: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   3901: 	if ($type eq 'user') {
                   3902: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 3903: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 3904: 		if ($tdom) {
                   3905: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   3906: 		}
1.896     albertel 3907: 		if ($tuname) {
                   3908: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 3909: 		}
                   3910: 		$access=($effect eq 'allow');
                   3911: 		last;
                   3912: 	    }
                   3913: 	} else {
                   3914: 	    if ($role) {
                   3915: 		if ($role ne $urole) { next; }
                   3916: 	    }
                   3917: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3918: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   3919: 		if ($tdom) {
                   3920: 		    if ($tdom ne $udom) { next; }
                   3921: 		}
                   3922: 		if ($tcrs) {
                   3923: 		    if ($tcrs ne $ucrs) { next; }
                   3924: 		}
                   3925: 		if ($tsec) {
                   3926: 		    if ($tsec ne $usec) { next; }
                   3927: 		}
                   3928: 		$access=($effect eq 'allow');
                   3929: 		last;
                   3930: 	    }
                   3931: 	    if ($realm eq '' && $role eq '') {
                   3932: 		$access=($effect eq 'allow');
                   3933: 	    }
1.402     bowersj2 3934: 	}
1.341     www      3935:     }
                   3936:     return $access;
                   3937: }
                   3938: 
1.103     harris41 3939: # ------------------------------------------------- Check for a user privilege
1.12      www      3940: 
                   3941: sub allowed {
1.810     raeburn  3942:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3943:     my $ver_orguri=$uri;
1.439     www      3944:     $uri=&deversion($uri);
1.152     www      3945:     my $orguri=$uri;
1.52      www      3946:     $uri=&declutter($uri);
1.809     raeburn  3947: 
1.810     raeburn  3948:     if ($priv eq 'evb') {
                   3949: # Evade communication block restrictions for specified role in a course
                   3950:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3951:             return $1;
                   3952:         } else {
                   3953:             return;
                   3954:         }
                   3955:     }
                   3956: 
1.620     albertel 3957:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3958: # Free bre access to adm and meta resources
1.775     albertel 3959:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3960: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3961: 	&& ($priv eq 'bre')) {
1.14      www      3962: 	return 'F';
1.159     www      3963:     }
                   3964: 
1.545     banghart 3965: # Free bre access to user's own portfolio contents
1.714     raeburn  3966:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3967:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3968: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3969:         my %setters;
                   3970:         my ($startblock,$endblock) = 
                   3971:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3972:         if ($startblock && $endblock) {
                   3973:             return 'B';
                   3974:         } else {
                   3975:             return 'F';
                   3976:         }
1.545     banghart 3977:     }
                   3978: 
1.762     raeburn  3979: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3980:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3981:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3982:         if (exists($env{'request.course.id'})) {
                   3983:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3984:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3985:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3986:                 my $courseprivid=$env{'request.course.id'};
                   3987:                 $courseprivid=~s/\_/\//;
                   3988:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3989:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3990:                     return $1; 
1.762     raeburn  3991:                 } else {
                   3992:                     if ($env{'request.course.sec'}) {
                   3993:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3994:                     }
                   3995:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3996:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3997:                         return $2;
                   3998:                     }
1.714     raeburn  3999:                 }
                   4000:             }
                   4001:         }
                   4002:     }
                   4003: 
1.159     www      4004: # Free bre to public access
                   4005: 
                   4006:     if ($priv eq 'bre') {
1.238     www      4007:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4008: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4009:            return 'F'; 
                   4010:         }
1.238     www      4011:         if ($copyright eq 'priv') {
                   4012:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4013: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4014: 		return '';
                   4015:             }
                   4016:         }
                   4017:         if ($copyright eq 'domain') {
                   4018:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4019: 	    unless (($env{'user.domain'} eq $1) ||
                   4020:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4021: 		return '';
                   4022:             }
1.262     matthew  4023:         }
1.620     albertel 4024:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4025:             # Library role, so allow browsing of resources in this domain.
                   4026:             return 'F';
1.238     www      4027:         }
1.341     www      4028:         if ($copyright eq 'custom') {
                   4029: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4030:         }
1.14      www      4031:     }
1.264     matthew  4032:     # Domain coordinator is trying to create a course
1.620     albertel 4033:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4034:         # uri is the requested domain in this case.
                   4035:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4036:         # a role of dc for the domain in question.
1.620     albertel 4037:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4038:     }
1.29      www      4039: 
1.52      www      4040:     my $thisallowed='';
                   4041:     my $statecond=0;
                   4042:     my $courseprivid='';
                   4043: 
                   4044: # Course
                   4045: 
1.620     albertel 4046:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4047:        $thisallowed.=$1;
                   4048:     }
1.29      www      4049: 
1.52      www      4050: # Domain
                   4051: 
1.620     albertel 4052:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4053:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4054:        $thisallowed.=$1;
                   4055:     }
1.52      www      4056: 
                   4057: # Course: uri itself is a course
1.66      www      4058:     my $courseuri=$uri;
                   4059:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4060:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4061: 
1.620     albertel 4062:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4063:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4064:        $thisallowed.=$1;
                   4065:     }
1.29      www      4066: 
1.665     albertel 4067: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4068: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4069:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4070: 	$thisallowed='';
1.671     raeburn  4071:         my ($match)=&is_on_map($uri);
                   4072:         if ($match) {
                   4073:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4074:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4075:                 $thisallowed.=$1;
                   4076:             }
                   4077:         } else {
1.705     albertel 4078:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4079:             if ($refuri) {
                   4080:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4081:                     $thisallowed='F';
1.671     raeburn  4082:                 } else {
                   4083:                     $refuri=&declutter($refuri);
                   4084:                     my ($match) = &is_on_map($refuri);
                   4085:                     if ($match) {
                   4086:                         $thisallowed='F';
                   4087:                     }
1.669     raeburn  4088:                 }
1.671     raeburn  4089:             }
                   4090:         }
1.314     www      4091:     }
1.492     albertel 4092: 
1.766     albertel 4093:     if ($priv eq 'bre'
                   4094: 	&& $thisallowed ne 'F' 
                   4095: 	&& $thisallowed ne '2'
                   4096: 	&& &is_portfolio_url($uri)) {
                   4097: 	$thisallowed = &portfolio_access($uri);
                   4098:     }
                   4099:     
1.52      www      4100: # Full access at system, domain or course-wide level? Exit.
1.29      www      4101: 
                   4102:     if ($thisallowed=~/F/) {
                   4103: 	return 'F';
                   4104:     }
                   4105: 
1.52      www      4106: # If this is generating or modifying users, exit with special codes
1.29      www      4107: 
1.643     www      4108:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4109: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4110: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4111: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4112: 	    unless ($auname) { return $thisallowed; }
                   4113: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4114: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4115: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4116: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4117: 	}
1.52      www      4118: 	return $thisallowed;
                   4119:     }
                   4120: #
1.103     harris41 4121: # Gathered so far: system, domain and course wide privileges
1.52      www      4122: #
                   4123: # Course: See if uri or referer is an individual resource that is part of 
                   4124: # the course
                   4125: 
1.620     albertel 4126:     if ($env{'request.course.id'}) {
1.232     www      4127: 
1.620     albertel 4128:        $courseprivid=$env{'request.course.id'};
                   4129:        if ($env{'request.course.sec'}) {
                   4130:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4131:        }
                   4132:        $courseprivid=~s/\_/\//;
                   4133:        my $checkreferer=1;
1.232     www      4134:        my ($match,$cond)=&is_on_map($uri);
                   4135:        if ($match) {
                   4136:            $statecond=$cond;
1.620     albertel 4137:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4138:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4139:                $thisallowed.=$1;
                   4140:                $checkreferer=0;
                   4141:            }
1.29      www      4142:        }
1.83      www      4143:        
1.148     www      4144:        if ($checkreferer) {
1.620     albertel 4145: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4146:             unless ($refuri) {
1.800     albertel 4147:                 foreach my $key (keys(%env)) {
                   4148: 		    if ($key=~/^httpref\..*\*/) {
                   4149: 			my $pattern=$key;
1.156     www      4150:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4151:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4152:                         $pattern=~s/\//\\\//g;
1.152     www      4153:                         if ($orguri=~/$pattern/) {
1.800     albertel 4154: 			    $refuri=$env{$key};
1.148     www      4155:                         }
                   4156:                     }
1.191     harris41 4157:                 }
1.148     www      4158:             }
1.232     www      4159: 
1.148     www      4160:          if ($refuri) { 
1.152     www      4161: 	  $refuri=&declutter($refuri);
1.232     www      4162:           my ($match,$cond)=&is_on_map($refuri);
                   4163:             if ($match) {
                   4164:               my $refstatecond=$cond;
1.620     albertel 4165:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4166:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4167:                   $thisallowed.=$1;
1.53      www      4168:                   $uri=$refuri;
                   4169:                   $statecond=$refstatecond;
1.52      www      4170:               }
                   4171:           }
1.148     www      4172:         }
1.29      www      4173:        }
1.52      www      4174:    }
1.29      www      4175: 
1.52      www      4176: #
1.103     harris41 4177: # Gathered now: all privileges that could apply, and condition number
1.52      www      4178: # 
                   4179: #
                   4180: # Full or no access?
                   4181: #
1.29      www      4182: 
1.52      www      4183:     if ($thisallowed=~/F/) {
                   4184: 	return 'F';
                   4185:     }
1.29      www      4186: 
1.52      www      4187:     unless ($thisallowed) {
                   4188:         return '';
                   4189:     }
1.29      www      4190: 
1.52      www      4191: # Restrictions exist, deal with them
                   4192: #
                   4193: #   C:according to course preferences
                   4194: #   R:according to resource settings
                   4195: #   L:unless locked
                   4196: #   X:according to user session state
                   4197: #
                   4198: 
                   4199: # Possibly locked functionality, check all courses
1.54      www      4200: # Locks might take effect only after 10 minutes cache expiration for other
                   4201: # courses, and 2 minutes for current course
1.52      www      4202: 
                   4203:     my $envkey;
                   4204:     if ($thisallowed=~/L/) {
1.620     albertel 4205:         foreach $envkey (keys %env) {
1.54      www      4206:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4207:                my $courseid=$2;
                   4208:                my $roleid=$1.'.'.$2;
1.92      www      4209:                $courseid=~s/^\///;
1.54      www      4210:                my $expiretime=600;
1.620     albertel 4211:                if ($env{'request.role'} eq $roleid) {
1.54      www      4212: 		  $expiretime=120;
                   4213:                }
                   4214: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4215:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4216:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4217: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4218:                }
1.620     albertel 4219:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4220:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4221: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4222:                        &log($env{'user.domain'},$env{'user.name'},
                   4223:                             $env{'user.home'},
1.57      www      4224:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4225:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4226:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4227: 		       return '';
                   4228:                    }
                   4229:                }
1.620     albertel 4230:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4231:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4232: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4233:                        &log($env{'user.domain'},$env{'user.name'},
                   4234:                             $env{'user.home'},
1.57      www      4235:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4236:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4237:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4238: 		       return '';
                   4239:                    }
                   4240:                }
                   4241: 	   }
1.29      www      4242:        }
1.52      www      4243:     }
                   4244:    
                   4245: #
                   4246: # Rest of the restrictions depend on selected course
                   4247: #
                   4248: 
1.620     albertel 4249:     unless ($env{'request.course.id'}) {
1.766     albertel 4250: 	if ($thisallowed eq 'A') {
                   4251: 	    return 'A';
1.814     raeburn  4252:         } elsif ($thisallowed eq 'B') {
                   4253:             return 'B';
1.766     albertel 4254: 	} else {
                   4255: 	    return '1';
                   4256: 	}
1.52      www      4257:     }
1.29      www      4258: 
1.52      www      4259: #
                   4260: # Now user is definitely in a course
                   4261: #
1.53      www      4262: 
                   4263: 
                   4264: # Course preferences
                   4265: 
                   4266:    if ($thisallowed=~/C/) {
1.620     albertel 4267:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4268:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4269:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4270: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4271: 	   if ($priv ne 'pch') { 
                   4272: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4273: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4274: 			$env{'request.course.id'});
                   4275: 	   }
1.237     www      4276:            return '';
                   4277:        }
                   4278: 
1.620     albertel 4279:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4280: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4281: 	   if ($priv ne 'pch') { 
                   4282: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4283: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4284: 			$env{'request.course.id'});
                   4285: 	   }
1.54      www      4286:            return '';
                   4287:        }
1.53      www      4288:    }
                   4289: 
                   4290: # Resource preferences
                   4291: 
                   4292:    if ($thisallowed=~/R/) {
1.620     albertel 4293:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4294:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4295: 	   if ($priv ne 'pch') { 
                   4296: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4297: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4298: 	   }
                   4299: 	   return '';
1.54      www      4300:        }
1.53      www      4301:    }
1.30      www      4302: 
1.246     www      4303: # Restricted by state or randomout?
1.30      www      4304: 
1.52      www      4305:    if ($thisallowed=~/X/) {
1.620     albertel 4306:       if ($env{'acc.randomout'}) {
1.579     albertel 4307: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4308:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4309:             return ''; 
                   4310:          }
1.247     www      4311:       }
                   4312:       if (&condval($statecond)) {
1.52      www      4313: 	 return '2';
                   4314:       } else {
                   4315:          return '';
                   4316:       }
                   4317:    }
1.30      www      4318: 
1.766     albertel 4319:     if ($thisallowed eq 'A') {
                   4320: 	return 'A';
1.814     raeburn  4321:     } elsif ($thisallowed eq 'B') {
                   4322:         return 'B';
1.766     albertel 4323:     }
1.52      www      4324:    return 'F';
1.232     www      4325: }
                   4326: 
1.710     albertel 4327: sub split_uri_for_cond {
                   4328:     my $uri=&deversion(&declutter(shift));
                   4329:     my @uriparts=split(/\//,$uri);
                   4330:     my $filename=pop(@uriparts);
                   4331:     my $pathname=join('/',@uriparts);
                   4332:     return ($pathname,$filename);
                   4333: }
1.232     www      4334: # --------------------------------------------------- Is a resource on the map?
                   4335: 
                   4336: sub is_on_map {
1.710     albertel 4337:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4338:     #Trying to find the conditional for the file
1.620     albertel 4339:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4340: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4341:     if ($match) {
1.289     bowersj2 4342: 	return (1,$1);
                   4343:     } else {
1.434     www      4344: 	return (0,0);
1.289     bowersj2 4345:     }
1.12      www      4346: }
                   4347: 
1.427     www      4348: # --------------------------------------------------------- Get symb from alias
                   4349: 
                   4350: sub get_symb_from_alias {
                   4351:     my $symb=shift;
                   4352:     my ($map,$resid,$url)=&decode_symb($symb);
                   4353: # Already is a symb
                   4354:     if ($url) { return $symb; }
                   4355: # Must be an alias
                   4356:     my $aliassymb='';
                   4357:     my %bighash;
1.620     albertel 4358:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4359:                             &GDBM_READER(),0640)) {
                   4360:         my $rid=$bighash{'mapalias_'.$symb};
                   4361: 	if ($rid) {
                   4362: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4363: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4364: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4365: 	}
                   4366:         untie %bighash;
                   4367:     }
                   4368:     return $aliassymb;
                   4369: }
                   4370: 
1.12      www      4371: # ----------------------------------------------------------------- Define Role
                   4372: 
                   4373: sub definerole {
                   4374:   if (allowed('mcr','/')) {
                   4375:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4376:     foreach my $role (split(':',$sysrole)) {
                   4377: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4378:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4379:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4380: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4381:                return "refused:s:$crole&$cqual"; 
                   4382:             }
                   4383:         }
1.191     harris41 4384:     }
1.800     albertel 4385:     foreach my $role (split(':',$domrole)) {
                   4386: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4387:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4388:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4389: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4390:                return "refused:d:$crole&$cqual"; 
                   4391:             }
                   4392:         }
1.191     harris41 4393:     }
1.800     albertel 4394:     foreach my $role (split(':',$courole)) {
                   4395: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4396:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4397:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4398: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4399:                return "refused:c:$crole&$cqual"; 
                   4400:             }
                   4401:         }
1.191     harris41 4402:     }
1.620     albertel 4403:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4404:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4405: 	        "rolesdef_$rolename=".
                   4406:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4407:     return reply($command,$env{'user.home'});
1.12      www      4408:   } else {
                   4409:     return 'refused';
                   4410:   }
1.105     harris41 4411: }
                   4412: 
                   4413: # ---------------- Make a metadata query against the network of library servers
                   4414: 
                   4415: sub metadata_query {
1.244     matthew  4416:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4417:     my %rhash;
1.845     albertel 4418:     my %libserv = &all_library();
1.244     matthew  4419:     my @server_list = (defined($server_array) ? @$server_array
                   4420:                                               : keys(%libserv) );
                   4421:     for my $server (@server_list) {
1.118     harris41 4422: 	unless ($custom or $customshow) {
                   4423: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4424: 	    $rhash{$server}=$reply;
                   4425: 	}
                   4426: 	else {
                   4427: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4428: 			     &escape($custom).':'.&escape($customshow),
                   4429: 			     $server);
                   4430: 	    $rhash{$server}=$reply;
                   4431: 	}
1.112     harris41 4432:     }
1.118     harris41 4433:     return \%rhash;
1.240     www      4434: }
                   4435: 
                   4436: # ----------------------------------------- Send log queries and wait for reply
                   4437: 
                   4438: sub log_query {
                   4439:     my ($uname,$udom,$query,%filters)=@_;
                   4440:     my $uhome=&homeserver($uname,$udom);
                   4441:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4442:     my $uhost=&hostname($uhome);
1.800     albertel 4443:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4444:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4445:                        $uhome);
1.479     albertel 4446:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4447:     return get_query_reply($queryid);
                   4448: }
                   4449: 
1.818     raeburn  4450: # -------------------------- Update MySQL table for portfolio file
                   4451: 
                   4452: sub update_portfolio_table {
1.821     raeburn  4453:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4454:     my $homeserver = &homeserver($uname,$udom);
                   4455:     my $queryid=
1.821     raeburn  4456:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4457:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4458:     my $reply = &get_query_reply($queryid);
                   4459:     return $reply;
                   4460: }
                   4461: 
1.899     raeburn  4462: # -------------------------- Update MySQL allusers table
                   4463: 
                   4464: sub update_allusers_table {
                   4465:     my ($uname,$udom,$names) = @_;
                   4466:     my $homeserver = &homeserver($uname,$udom);
                   4467:     my $queryid=
                   4468:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4469:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4470:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4471:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4472:                'generation='.&escape($names->{'generation'}).'%%'.
                   4473:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4474:                'id='.&escape($names->{'id'}),$homeserver);
                   4475:     my $reply = &get_query_reply($queryid);
                   4476:     return $reply;
                   4477: }
                   4478: 
1.508     raeburn  4479: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4480: 
                   4481: sub fetch_enrollment_query {
1.511     raeburn  4482:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4483:     my $homeserver;
1.547     raeburn  4484:     my $maxtries = 1;
1.508     raeburn  4485:     if ($context eq 'automated') {
                   4486:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4487:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4488:     } else {
                   4489:         $homeserver = &homeserver($cnum,$dom);
                   4490:     }
1.838     albertel 4491:     my $host=&hostname($homeserver);
1.506     raeburn  4492:     my $cmd = '';
1.800     albertel 4493:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4494:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4495:     }
                   4496:     $cmd =~ s/%%$//;
                   4497:     $cmd = &escape($cmd);
                   4498:     my $query = 'fetchenrollment';
1.620     albertel 4499:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4500:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4501:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4502:         return 'error: '.$queryid;
                   4503:     }
1.506     raeburn  4504:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4505:     my $tries = 1;
                   4506:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4507:         $reply = &get_query_reply($queryid);
                   4508:         $tries ++;
                   4509:     }
1.526     raeburn  4510:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4511:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4512:     } else {
1.901     albertel 4513:         my @responses = split(/:/,$reply);
1.515     raeburn  4514:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4515:             foreach my $line (@responses) {
                   4516:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4517:                 $$replyref{$key} = $value;
                   4518:             }
                   4519:         } else {
1.506     raeburn  4520:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4521:             foreach my $line (@responses) {
                   4522:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4523:                 $$replyref{$key} = $value;
                   4524:                 if ($value > 0) {
1.800     albertel 4525:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4526:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4527:                         my $destname = $pathname.'/'.$filename;
                   4528:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4529:                         if ($xml_classlist =~ /^error/) {
                   4530:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4531:                         } else {
1.506     raeburn  4532:                             if ( open(FILE,">$destname") ) {
                   4533:                                 print FILE &unescape($xml_classlist);
                   4534:                                 close(FILE);
1.526     raeburn  4535:                             } else {
                   4536:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4537:                             }
                   4538:                         }
                   4539:                     }
                   4540:                 }
                   4541:             }
                   4542:         }
                   4543:         return 'ok';
                   4544:     }
                   4545:     return 'error';
                   4546: }
                   4547: 
1.242     www      4548: sub get_query_reply {
                   4549:     my $queryid=shift;
1.240     www      4550:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4551:     my $reply='';
                   4552:     for (1..100) {
                   4553: 	sleep 2;
                   4554:         if (-e $replyfile.'.end') {
1.448     albertel 4555: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4556: 		$reply = join('',<$fh>);
                   4557: 		close($fh);
1.240     www      4558: 	   } else { return 'error: reply_file_error'; }
1.242     www      4559:            return &unescape($reply);
                   4560: 	}
1.240     www      4561:     }
1.242     www      4562:     return 'timeout:'.$queryid;
1.240     www      4563: }
                   4564: 
                   4565: sub courselog_query {
1.241     www      4566: #
                   4567: # possible filters:
                   4568: # url: url or symb
                   4569: # username
                   4570: # domain
                   4571: # action: view, submit, grade
                   4572: # start: timestamp
                   4573: # end: timestamp
                   4574: #
1.240     www      4575:     my (%filters)=@_;
1.620     albertel 4576:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4577:     if ($filters{'url'}) {
                   4578: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4579:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4580:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4581:     }
1.620     albertel 4582:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4583:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4584:     return &log_query($cname,$cdom,'courselog',%filters);
                   4585: }
                   4586: 
                   4587: sub userlog_query {
1.858     raeburn  4588: #
                   4589: # possible filters:
                   4590: # action: log check role
                   4591: # start: timestamp
                   4592: # end: timestamp
                   4593: #
1.240     www      4594:     my ($uname,$udom,%filters)=@_;
                   4595:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4596: }
                   4597: 
1.506     raeburn  4598: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4599: 
                   4600: sub auto_run {
1.508     raeburn  4601:     my ($cnum,$cdom) = @_;
1.876     raeburn  4602:     my $response = 0;
                   4603:     my $settings;
                   4604:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4605:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4606:         $settings = $domconfig{'autoenroll'};
                   4607:         if ($settings->{'run'} eq '1') {
                   4608:             $response = 1;
                   4609:         }
                   4610:     } else {
                   4611:         my $homeserver = &homeserver($cnum,$cdom);
                   4612:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4613:     }
1.506     raeburn  4614:     return $response;
                   4615: }
1.776     albertel 4616: 
1.506     raeburn  4617: sub auto_get_sections {
1.508     raeburn  4618:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4619:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4620:     my @secs = ();
1.511     raeburn  4621:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4622:     unless ($response eq 'refused') {
1.901     albertel 4623:         @secs = split(/:/,$response);
1.506     raeburn  4624:     }
                   4625:     return @secs;
                   4626: }
1.776     albertel 4627: 
1.506     raeburn  4628: sub auto_new_course {
1.508     raeburn  4629:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4630:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4631:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4632:     return $response;
                   4633: }
1.776     albertel 4634: 
1.506     raeburn  4635: sub auto_validate_courseID {
1.508     raeburn  4636:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4637:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4638:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4639:     return $response;
                   4640: }
1.776     albertel 4641: 
1.506     raeburn  4642: sub auto_create_password {
1.873     raeburn  4643:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4644:     my ($homeserver,$response);
1.506     raeburn  4645:     my $create_passwd = 0;
                   4646:     my $authchk = '';
1.873     raeburn  4647:     if ($udom =~ /^$match_domain$/) {
                   4648:         $homeserver = &domain($udom,'primary');
                   4649:     }
                   4650:     if ($homeserver eq '') {
                   4651:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4652:             $homeserver = &homeserver($cnum,$cdom);
                   4653:         }
                   4654:     }
                   4655:     if ($homeserver eq '') {
                   4656:         $authchk = 'nodomain';
1.506     raeburn  4657:     } else {
1.873     raeburn  4658:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4659:         if ($response eq 'refused') {
                   4660:             $authchk = 'refused';
                   4661:         } else {
1.901     albertel 4662:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4663:         }
1.506     raeburn  4664:     }
                   4665:     return ($authparam,$create_passwd,$authchk);
                   4666: }
                   4667: 
1.706     raeburn  4668: sub auto_photo_permission {
                   4669:     my ($cnum,$cdom,$students) = @_;
                   4670:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4671:     my ($outcome,$perm_reqd,$conditions) = 
                   4672: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4673:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4674: 	return (undef,undef);
                   4675:     }
1.706     raeburn  4676:     return ($outcome,$perm_reqd,$conditions);
                   4677: }
                   4678: 
                   4679: sub auto_checkphotos {
                   4680:     my ($uname,$udom,$pid) = @_;
                   4681:     my $homeserver = &homeserver($uname,$udom);
                   4682:     my ($result,$resulttype);
                   4683:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4684: 				   &escape($uname).':'.&escape($pid),
                   4685: 				   $homeserver));
1.709     albertel 4686:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4687: 	return (undef,undef);
                   4688:     }
1.706     raeburn  4689:     if ($outcome) {
                   4690:         ($result,$resulttype) = split(/:/,$outcome);
                   4691:     } 
                   4692:     return ($result,$resulttype);
                   4693: }
                   4694: 
                   4695: sub auto_photochoice {
                   4696:     my ($cnum,$cdom) = @_;
                   4697:     my $homeserver = &homeserver($cnum,$cdom);
                   4698:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4699: 						       &escape($cdom),
                   4700: 						       $homeserver)));
1.709     albertel 4701:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4702: 	return (undef,undef);
                   4703:     }
1.706     raeburn  4704:     return ($update,$comment);
                   4705: }
                   4706: 
                   4707: sub auto_photoupdate {
                   4708:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4709:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4710:     my $host=&hostname($homeserver);
1.706     raeburn  4711:     my $cmd = '';
                   4712:     my $maxtries = 1;
1.800     albertel 4713:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4714:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4715:     }
                   4716:     $cmd =~ s/%%$//;
                   4717:     $cmd = &escape($cmd);
                   4718:     my $query = 'institutionalphotos';
                   4719:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4720:     unless ($queryid=~/^\Q$host\E\_/) {
                   4721:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4722:         return 'error: '.$queryid;
                   4723:     }
                   4724:     my $reply = &get_query_reply($queryid);
                   4725:     my $tries = 1;
                   4726:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4727:         $reply = &get_query_reply($queryid);
                   4728:         $tries ++;
                   4729:     }
                   4730:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4731:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4732:     } else {
                   4733:         my @responses = split(/:/,$reply);
                   4734:         my $outcome = shift(@responses); 
                   4735:         foreach my $item (@responses) {
                   4736:             my ($key,$value) = split(/=/,$item);
                   4737:             $$photo{$key} = $value;
                   4738:         }
                   4739:         return $outcome;
                   4740:     }
                   4741:     return 'error';
                   4742: }
                   4743: 
1.521     raeburn  4744: sub auto_instcode_format {
1.793     albertel 4745:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4746: 	$cat_order) = @_;
1.521     raeburn  4747:     my $courses = '';
1.772     raeburn  4748:     my @homeservers;
1.521     raeburn  4749:     if ($caller eq 'global') {
1.841     albertel 4750: 	my %servers = &get_servers($codedom,'library');
                   4751: 	foreach my $tryserver (keys(%servers)) {
                   4752: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4753: 		push(@homeservers,$tryserver);
                   4754: 	    }
1.584     raeburn  4755:         }
1.521     raeburn  4756:     } else {
1.772     raeburn  4757:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4758:     }
1.793     albertel 4759:     foreach my $code (keys(%{$instcodes})) {
                   4760:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4761:     }
                   4762:     chop($courses);
1.772     raeburn  4763:     my $ok_response = 0;
                   4764:     my $response;
                   4765:     while (@homeservers > 0 && $ok_response == 0) {
                   4766:         my $server = shift(@homeservers); 
                   4767:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4768:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4769:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4770: 		split(/:/,$response);
1.772     raeburn  4771:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4772:             push(@{$codetitles},&str2array($codetitles_str));
                   4773:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4774:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4775:             $ok_response = 1;
                   4776:         }
                   4777:     }
                   4778:     if ($ok_response) {
1.521     raeburn  4779:         return 'ok';
1.772     raeburn  4780:     } else {
                   4781:         return $response;
1.521     raeburn  4782:     }
                   4783: }
                   4784: 
1.792     raeburn  4785: sub auto_instcode_defaults {
                   4786:     my ($domain,$returnhash,$code_order) = @_;
                   4787:     my @homeservers;
1.841     albertel 4788: 
                   4789:     my %servers = &get_servers($domain,'library');
                   4790:     foreach my $tryserver (keys(%servers)) {
                   4791: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4792: 	    push(@homeservers,$tryserver);
                   4793: 	}
1.792     raeburn  4794:     }
1.841     albertel 4795: 
1.792     raeburn  4796:     my $response;
1.841     albertel 4797:     foreach my $server (@homeservers) {
1.792     raeburn  4798:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4799:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4800: 	
                   4801: 	foreach my $pair (split(/\&/,$response)) {
                   4802: 	    my ($name,$value)=split(/\=/,$pair);
                   4803: 	    if ($name eq 'code_order') {
                   4804: 		@{$code_order} = split(/\&/,&unescape($value));
                   4805: 	    } else {
                   4806: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4807: 	    }
                   4808: 	}
                   4809: 	return 'ok';
1.792     raeburn  4810:     }
1.841     albertel 4811: 
                   4812:     return $response;
1.792     raeburn  4813: } 
                   4814: 
1.777     albertel 4815: sub auto_validate_class_sec {
1.773     raeburn  4816:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4817:     my $homeserver = &homeserver($cnum,$cdom);
                   4818:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4819:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4820:     return $response;
                   4821: }
                   4822: 
1.679     raeburn  4823: # ------------------------------------------------------- Course Group routines
                   4824: 
                   4825: sub get_coursegroups {
1.809     raeburn  4826:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4827:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4828: }
                   4829: 
1.679     raeburn  4830: sub modify_coursegroup {
                   4831:     my ($cdom,$cnum,$groupsettings) = @_;
                   4832:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4833: }
                   4834: 
1.809     raeburn  4835: sub toggle_coursegroup_status {
                   4836:     my ($cdom,$cnum,$group,$action) = @_;
                   4837:     my ($from_namespace,$to_namespace);
                   4838:     if ($action eq 'delete') {
                   4839:         $from_namespace = 'coursegroups';
                   4840:         $to_namespace = 'deleted_groups';
                   4841:     } else {
                   4842:         $from_namespace = 'deleted_groups';
                   4843:         $to_namespace = 'coursegroups';
                   4844:     }
                   4845:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4846:     if (my $tmp = &error(%curr_group)) {
                   4847:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4848:         return ('read error',$tmp);
                   4849:     } else {
                   4850:         my %savedsettings = %curr_group; 
1.809     raeburn  4851:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4852:         my $deloutcome;
                   4853:         if ($result eq 'ok') {
1.809     raeburn  4854:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4855:         } else {
                   4856:             return ('write error',$result);
                   4857:         }
                   4858:         if ($deloutcome eq 'ok') {
                   4859:             return 'ok';
                   4860:         } else {
                   4861:             return ('delete error',$deloutcome);
                   4862:         }
                   4863:     }
                   4864: }
                   4865: 
1.679     raeburn  4866: sub modify_group_roles {
                   4867:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4868:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4869:     my $role = 'gr/'.&escape($userprivs);
                   4870:     my ($uname,$udom) = split(/:/,$user);
                   4871:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4872:     if ($result eq 'ok') {
                   4873:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4874:     }
1.679     raeburn  4875:     return $result;
                   4876: }
                   4877: 
                   4878: sub modify_coursegroup_membership {
                   4879:     my ($cdom,$cnum,$membership) = @_;
                   4880:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4881:     return $result;
                   4882: }
                   4883: 
1.682     raeburn  4884: sub get_active_groups {
                   4885:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4886:     my $now = time;
                   4887:     my %groups = ();
                   4888:     foreach my $key (keys(%env)) {
1.811     albertel 4889:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4890:             my ($start,$end) = split(/\./,$env{$key});
                   4891:             if (($end!=0) && ($end<$now)) { next; }
                   4892:             if (($start!=0) && ($start>$now)) { next; }
                   4893:             if ($1 eq $cdom && $2 eq $cnum) {
                   4894:                 $groups{$3} = $env{$key} ;
                   4895:             }
                   4896:         }
                   4897:     }
                   4898:     return %groups;
                   4899: }
                   4900: 
1.683     raeburn  4901: sub get_group_membership {
                   4902:     my ($cdom,$cnum,$group) = @_;
                   4903:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4904: }
                   4905: 
                   4906: sub get_users_groups {
                   4907:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4908:     my @usersgroups;
1.683     raeburn  4909:     my $cachetime=1800;
                   4910: 
                   4911:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4912:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4913:     if (defined($cached)) {
1.734     albertel 4914:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4915:     } else {  
                   4916:         $grouplist = '';
1.816     raeburn  4917:         my $courseurl = &courseid_to_courseurl($courseid);
                   4918:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4919:         my $access_end = $env{'course.'.$courseid.
                   4920:                               '.default_enrollment_end_date'};
                   4921:         my $now = time;
                   4922:         foreach my $key (keys(%roleshash)) {
                   4923:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4924:                 my $group = $1;
                   4925:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4926:                     my $start = $2;
                   4927:                     my $end = $1;
                   4928:                     if ($start == -1) { next; } # deleted from group
                   4929:                     if (($start!=0) && ($start>$now)) { next; }
                   4930:                     if (($end!=0) && ($end<$now)) {
                   4931:                         if ($access_end && $access_end < $now) {
                   4932:                             if ($access_end - $end < 86400) {
                   4933:                                 push(@usersgroups,$group);
1.733     raeburn  4934:                             }
                   4935:                         }
1.817     raeburn  4936:                         next;
1.733     raeburn  4937:                     }
1.817     raeburn  4938:                     push(@usersgroups,$group);
1.683     raeburn  4939:                 }
                   4940:             }
                   4941:         }
1.817     raeburn  4942:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4943:         $grouplist = join(':',@usersgroups);
                   4944:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4945:     }
1.733     raeburn  4946:     return @usersgroups;
1.683     raeburn  4947: }
                   4948: 
                   4949: sub devalidate_getgroups_cache {
                   4950:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4951:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4952: 
1.683     raeburn  4953:     my $hashid="$udom:$uname:$courseid";
                   4954:     &devalidate_cache_new('getgroups',$hashid);
                   4955: }
                   4956: 
1.12      www      4957: # ------------------------------------------------------------------ Plain Text
                   4958: 
                   4959: sub plaintext {
1.742     raeburn  4960:     my ($short,$type,$cid) = @_;
1.758     albertel 4961:     if ($short =~ /^cr/) {
                   4962: 	return (split('/',$short))[-1];
                   4963:     }
1.742     raeburn  4964:     if (!defined($cid)) {
                   4965:         $cid = $env{'request.course.id'};
                   4966:     }
                   4967:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4968:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4969:                                           '.plaintext'});
                   4970:     }
                   4971:     my %rolenames = (
                   4972:                       Course => 'std',
                   4973:                       Group => 'alt1',
                   4974:                     );
                   4975:     if (defined($type) && 
                   4976:          defined($rolenames{$type}) && 
                   4977:          defined($prp{$short}{$rolenames{$type}})) {
                   4978:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4979:     } else {
                   4980:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4981:     }
1.12      www      4982: }
                   4983: 
                   4984: # ----------------------------------------------------------------- Assign Role
                   4985: 
                   4986: sub assignrole {
1.357     www      4987:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4988:     my $mrole;
                   4989:     if ($role =~ /^cr\//) {
1.393     www      4990:         my $cwosec=$url;
1.811     albertel 4991:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4992: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4993:            &logthis('Refused custom assignrole: '.
                   4994:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4995: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4996:            return 'refused'; 
                   4997:         }
1.21      www      4998:         $mrole='cr';
1.678     raeburn  4999:     } elsif ($role =~ /^gr\//) {
                   5000:         my $cwogrp=$url;
1.811     albertel 5001:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5002:         unless (&allowed('mdg',$cwogrp)) {
                   5003:             &logthis('Refused group assignrole: '.
                   5004:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5005:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5006:             return 'refused';
                   5007:         }
                   5008:         $mrole='gr';
1.21      www      5009:     } else {
1.82      www      5010:         my $cwosec=$url;
1.811     albertel 5011:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5012:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5013:            &logthis('Refused assignrole: '.
                   5014:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5015: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5016:            return 'refused'; 
                   5017:         }
1.21      www      5018:         $mrole=$role;
                   5019:     }
1.620     albertel 5020:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5021:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5022:     if ($end) { $command.='_'.$end; }
1.21      www      5023:     if ($start) {
                   5024: 	if ($end) { 
1.81      www      5025:            $command.='_'.$start; 
1.21      www      5026:         } else {
1.81      www      5027:            $command.='_0_'.$start;
1.21      www      5028:         }
                   5029:     }
1.739     raeburn  5030:     my $origstart = $start;
                   5031:     my $origend = $end;
1.357     www      5032: # actually delete
                   5033:     if ($deleteflag) {
1.373     www      5034: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5035: # modify command to delete the role
1.620     albertel 5036:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5037:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5038: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5039: # set start and finish to negative values for userrolelog
                   5040:            $start=-1;
                   5041:            $end=-1;
                   5042:         }
                   5043:     }
                   5044: # send command
1.349     www      5045:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5046: # log new user role if status is ok
1.349     www      5047:     if ($answer eq 'ok') {
1.663     raeburn  5048: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5049: # for course roles, perform group memberships changes triggered by role change.
                   5050:         unless ($role =~ /^gr/) {
                   5051:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5052:                                              $origstart);
                   5053:         }
1.349     www      5054:     }
                   5055:     return $answer;
1.169     harris41 5056: }
                   5057: 
                   5058: # -------------------------------------------------- Modify user authentication
1.197     www      5059: # Overrides without validation
                   5060: 
1.169     harris41 5061: sub modifyuserauth {
                   5062:     my ($udom,$uname,$umode,$upass)=@_;
                   5063:     my $uhome=&homeserver($uname,$udom);
1.197     www      5064:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5065:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5066:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5067:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5068:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5069: 		     &escape($upass),$uhome);
1.620     albertel 5070:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5071:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5072:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5073:     &log($udom,,$uname,$uhome,
1.620     albertel 5074:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5075:                                      $env{'user.name'}.', '.$umode.
1.197     www      5076:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5077:     unless ($reply eq 'ok') {
1.197     www      5078:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5079: 	return 'error: '.$reply;
                   5080:     }   
1.170     harris41 5081:     return 'ok';
1.80      www      5082: }
                   5083: 
1.81      www      5084: # --------------------------------------------------------------- Modify a user
1.80      www      5085: 
1.81      www      5086: sub modifyuser {
1.206     matthew  5087:     my ($udom,    $uname, $uid,
                   5088:         $umode,   $upass, $first,
                   5089:         $middle,  $last,  $gene,
1.387     www      5090:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5091:     $udom= &LONCAPA::clean_domain($udom);
                   5092:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5093:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5094:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5095: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5096:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5097:                                      ' desiredhome not specified'). 
1.620     albertel 5098:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5099:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5100:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5101: # ----------------------------------------------------------------- Create User
1.406     albertel 5102:     if (($uhome eq 'no_host') && 
                   5103: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5104:         my $unhome='';
1.844     albertel 5105:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5106:             $unhome = $desiredhome;
1.620     albertel 5107: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5108: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5109:         } else { # load balancing routine for determining $unhome
1.81      www      5110:             my $loadm=10000000;
1.841     albertel 5111: 	    my %servers = &get_servers($udom,'library');
                   5112: 	    foreach my $tryserver (keys(%servers)) {
                   5113: 		my $answer=reply('load',$tryserver);
                   5114: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5115: 		    $loadm=$answer;
                   5116: 		    $unhome=$tryserver;
                   5117: 		}
1.80      www      5118: 	    }
                   5119:         }
                   5120:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5121: 	    return 'error: unable to find a home server for '.$uname.
                   5122:                    ' in domain '.$udom;
1.80      www      5123:         }
                   5124:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5125:                          &escape($upass),$unhome);
                   5126: 	unless ($reply eq 'ok') {
                   5127:             return 'error: '.$reply;
                   5128:         }   
1.230     stredwic 5129:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5130:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5131: 	    return 'error: unable verify users home machine.';
1.80      www      5132:         }
1.209     matthew  5133:     }   # End of creation of new user
1.80      www      5134: # ---------------------------------------------------------------------- Add ID
                   5135:     if ($uid) {
                   5136:        $uid=~tr/A-Z/a-z/;
                   5137:        my %uidhash=&idrget($udom,$uname);
1.196     www      5138:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5139:          && (!$forceid)) {
1.80      www      5140: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5141: 	      return 'error: user id "'.$uid.'" does not match '.
                   5142:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5143:           }
                   5144:        } else {
                   5145: 	  &idput($udom,($uname => $uid));
                   5146:        }
                   5147:     }
                   5148: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5149:     my @tmp=&get('environment',
1.899     raeburn  5150: 		   ['firstname','middlename','lastname','generation','id',
                   5151:                     'permanentemail'],
1.134     albertel 5152: 		   $udom,$uname);
1.313     matthew  5153:     my %names;
                   5154:     if ($tmp[0] =~ m/^error:.*/) { 
                   5155:         %names=(); 
                   5156:     } else {
                   5157:         %names = @tmp;
                   5158:     }
1.388     www      5159: #
                   5160: # Make sure to not trash student environment if instructor does not bother
                   5161: # to supply name and email information
                   5162: #
                   5163:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5164:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5165:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5166:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5167:     if ($email) {
                   5168:        $email=~s/[^\w\@\.\-\,]//gs;
                   5169:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5170: 			   $names{'critnotification'} = $email;
                   5171: 			   $names{'permanentemail'} = $email; }
                   5172:     }
1.899     raeburn  5173:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5174:     my $reply = &put('environment', \%names, $udom,$uname);
                   5175:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5176:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5177:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5178:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5179:              $umode.', '.$first.', '.$middle.', '.
                   5180: 	     $last.', '.$gene.' by '.
1.620     albertel 5181:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5182:     return 'ok';
1.80      www      5183: }
                   5184: 
1.81      www      5185: # -------------------------------------------------------------- Modify student
1.80      www      5186: 
1.81      www      5187: sub modifystudent {
                   5188:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5189:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5190:     if (!$cid) {
1.620     albertel 5191: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5192: 	    return 'not_in_class';
                   5193: 	}
1.80      www      5194:     }
                   5195: # --------------------------------------------------------------- Make the user
1.81      www      5196:     my $reply=&modifyuser
1.209     matthew  5197: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5198:          $desiredhome,$email);
1.80      www      5199:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5200:     # This will cause &modify_student_enrollment to get the uid from the
                   5201:     # students environment
                   5202:     $uid = undef if (!$forceid);
1.455     albertel 5203:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5204: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5205:     return $reply;
                   5206: }
                   5207: 
                   5208: sub modify_student_enrollment {
1.515     raeburn  5209:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5210:     my ($cdom,$cnum,$chome);
                   5211:     if (!$cid) {
1.620     albertel 5212: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5213: 	    return 'not_in_class';
                   5214: 	}
1.620     albertel 5215: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5216: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5217:     } else {
                   5218: 	($cdom,$cnum)=split(/_/,$cid);
                   5219:     }
1.620     albertel 5220:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5221:     if (!$chome) {
1.457     raeburn  5222: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5223:     }
1.455     albertel 5224:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5225:     # Make sure the user exists
1.81      www      5226:     my $uhome=&homeserver($uname,$udom);
                   5227:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5228: 	return 'error: no such user';
                   5229:     }
1.297     matthew  5230:     # Get student data if we were not given enough information
                   5231:     if (!defined($first)  || $first  eq '' || 
                   5232:         !defined($last)   || $last   eq '' || 
                   5233:         !defined($uid)    || $uid    eq '' || 
                   5234:         !defined($middle) || $middle eq '' || 
                   5235:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5236:         # They did not supply us with enough data to enroll the student, so
                   5237:         # we need to pick up more information.
1.297     matthew  5238:         my %tmp = &get('environment',
1.294     matthew  5239:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5240:                        ,$udom,$uname);
                   5241: 
1.800     albertel 5242:         #foreach my $key (keys(%tmp)) {
                   5243:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5244:         #}
1.294     matthew  5245:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5246:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5247:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5248:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5249:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5250:     }
1.556     albertel 5251:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5252:     my $reply=cput('classlist',
                   5253: 		   {"$uname:$udom" => 
1.515     raeburn  5254: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5255: 		   $cdom,$cnum);
1.81      www      5256:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5257: 	return 'error: '.$reply;
1.652     albertel 5258:     } else {
                   5259: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5260:     }
1.297     matthew  5261:     # Add student role to user
1.83      www      5262:     my $uurl='/'.$cid;
1.81      www      5263:     $uurl=~s/\_/\//g;
                   5264:     if ($usec) {
                   5265: 	$uurl.='/'.$usec;
                   5266:     }
                   5267:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5268: }
                   5269: 
1.556     albertel 5270: sub format_name {
                   5271:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5272:     my $name;
                   5273:     if ($first ne 'lastname') {
                   5274: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5275:     } else {
                   5276: 	if ($lastname=~/\S/) {
                   5277: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5278: 	    $name=~s/\s+,/,/;
                   5279: 	} else {
                   5280: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5281: 	}
                   5282:     }
                   5283:     $name=~s/^\s+//;
                   5284:     $name=~s/\s+$//;
                   5285:     $name=~s/\s+/ /g;
                   5286:     return $name;
                   5287: }
                   5288: 
1.84      www      5289: # ------------------------------------------------- Write to course preferences
                   5290: 
                   5291: sub writecoursepref {
                   5292:     my ($courseid,%prefs)=@_;
                   5293:     $courseid=~s/^\///;
                   5294:     $courseid=~s/\_/\//g;
                   5295:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5296:     my $chome=homeserver($cnum,$cdomain);
                   5297:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5298: 	return 'error: no such course';
                   5299:     }
                   5300:     my $cstring='';
1.800     albertel 5301:     foreach my $pref (keys(%prefs)) {
                   5302: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5303:     }
1.84      www      5304:     $cstring=~s/\&$//;
                   5305:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5306: }
                   5307: 
                   5308: # ---------------------------------------------------------- Make/modify course
                   5309: 
                   5310: sub createcourse {
1.741     raeburn  5311:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5312:         $course_owner,$crstype)=@_;
1.84      www      5313:     $url=&declutter($url);
                   5314:     my $cid='';
1.264     matthew  5315:     unless (&allowed('ccc',$udom)) {
1.84      www      5316:         return 'refused';
                   5317:     }
                   5318: # ------------------------------------------------------------------- Create ID
1.674     www      5319:    my $uname=int(1+rand(9)).
                   5320:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5321:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5322:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5323: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5324:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5325:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5326:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5327:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5328:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5329:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5330:            return 'error: unable to generate unique course-ID';
                   5331:        } 
                   5332:    }
1.264     matthew  5333: # ------------------------------------------------ Check supplied server name
1.620     albertel 5334:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5335:     if (! &is_library($course_server)) {
1.264     matthew  5336:         return 'error:bad server name '.$course_server;
                   5337:     }
1.84      www      5338: # ------------------------------------------------------------- Make the course
                   5339:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5340:                       $course_server);
1.84      www      5341:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5342:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5343:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5344: 	return 'error: no such course';
                   5345:     }
1.271     www      5346: # ----------------------------------------------------------------- Course made
1.516     raeburn  5347: # log existence
                   5348:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5349:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5350:                   &escape($crstype),$uhome);
1.358     www      5351:     &flushcourselogs();
                   5352: # set toplevel url
1.271     www      5353:     my $topurl=$url;
                   5354:     unless ($nonstandard) {
                   5355: # ------------------------------------------ For standard courses, make top url
                   5356:         my $mapurl=&clutter($url);
1.278     www      5357:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5358:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5359: <map>
                   5360: <resource id="1" type="start"></resource>
                   5361: <resource id="2" src="$mapurl"></resource>
                   5362: <resource id="3" type="finish"></resource>
                   5363: <link index="1" from="1" to="2"></link>
                   5364: <link index="2" from="2" to="3"></link>
                   5365: </map>
                   5366: ENDINITMAP
                   5367:         $topurl=&declutter(
1.638     albertel 5368:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5369:                           );
                   5370:     }
                   5371: # ----------------------------------------------------------- Write preferences
1.84      www      5372:     &writecoursepref($udom.'_'.$uname,
                   5373:                      ('description' => $description,
1.271     www      5374:                       'url'         => $topurl));
1.84      www      5375:     return '/'.$udom.'/'.$uname;
                   5376: }
                   5377: 
1.813     albertel 5378: sub is_course {
                   5379:     my ($cdom,$cnum) = @_;
                   5380:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5381: 				undef,'.');
                   5382:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5383:         return 1;
                   5384:     }
                   5385:     return 0;
                   5386: }
                   5387: 
1.21      www      5388: # ---------------------------------------------------------- Assign Custom Role
                   5389: 
                   5390: sub assigncustomrole {
1.357     www      5391:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5392:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5393:                        $end,$start,$deleteflag);
1.21      www      5394: }
                   5395: 
                   5396: # ----------------------------------------------------------------- Revoke Role
                   5397: 
                   5398: sub revokerole {
1.357     www      5399:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5400:     my $now=time;
1.357     www      5401:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5402: }
                   5403: 
                   5404: # ---------------------------------------------------------- Revoke Custom Role
                   5405: 
                   5406: sub revokecustomrole {
1.357     www      5407:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5408:     my $now=time;
1.357     www      5409:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5410:            $deleteflag);
1.17      www      5411: }
                   5412: 
1.533     banghart 5413: # ------------------------------------------------------------ Disk usage
1.535     albertel 5414: sub diskusage {
1.533     banghart 5415:     my ($udom,$uname,$directoryRoot)=@_;
                   5416:     $directoryRoot =~ s/\/$//;
1.535     albertel 5417:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5418:     return $listing;
1.512     banghart 5419: }
                   5420: 
1.566     banghart 5421: sub is_locked {
                   5422:     my ($file_name, $domain, $user) = @_;
                   5423:     my @check;
                   5424:     my $is_locked;
                   5425:     push @check, $file_name;
1.613     albertel 5426:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5427: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5428:     my ($tmp)=keys(%locked);
                   5429:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5430:     
1.566     banghart 5431:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5432:         $is_locked = 'false';
                   5433:         foreach my $entry (@{$locked{$file_name}}) {
                   5434:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5435:                $is_locked = 'true';
                   5436:                last;
1.745     raeburn  5437:            }
                   5438:        }
1.566     banghart 5439:     } else {
                   5440:         $is_locked = 'false';
                   5441:     }
                   5442: }
                   5443: 
1.759     albertel 5444: sub declutter_portfile {
                   5445:     my ($file) = @_;
1.833     albertel 5446:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5447:     return $file;
                   5448: }
                   5449: 
1.559     banghart 5450: # ------------------------------------------------------------- Mark as Read Only
                   5451: 
                   5452: sub mark_as_readonly {
                   5453:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5454:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5455:     my ($tmp)=keys(%current_permissions);
                   5456:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5457:     foreach my $file (@{$files}) {
1.759     albertel 5458: 	$file = &declutter_portfile($file);
1.561     banghart 5459:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5460:     }
1.613     albertel 5461:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5462:     return;
                   5463: }
                   5464: 
1.572     banghart 5465: # ------------------------------------------------------------Save Selected Files
                   5466: 
                   5467: sub save_selected_files {
                   5468:     my ($user, $path, @files) = @_;
                   5469:     my $filename = $user."savedfiles";
1.573     banghart 5470:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5471:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5472:     foreach my $file (@files) {
1.620     albertel 5473:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5474:     }
                   5475:     foreach my $file (@other_files) {
1.574     banghart 5476:         print (OUT $file."\n");
1.572     banghart 5477:     }
1.574     banghart 5478:     close (OUT);
1.572     banghart 5479:     return 'ok';
                   5480: }
                   5481: 
1.574     banghart 5482: sub clear_selected_files {
                   5483:     my ($user) = @_;
                   5484:     my $filename = $user."savedfiles";
                   5485:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5486:     print (OUT undef);
                   5487:     close (OUT);
                   5488:     return ("ok");    
                   5489: }
                   5490: 
1.572     banghart 5491: sub files_in_path {
                   5492:     my ($user, $path) = @_;
                   5493:     my $filename = $user."savedfiles";
                   5494:     my %return_files;
1.574     banghart 5495:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5496:     while (my $line_in = <IN>) {
1.574     banghart 5497:         chomp ($line_in);
                   5498:         my @paths_and_file = split (m!/!, $line_in);
                   5499:         my $file_part = pop (@paths_and_file);
                   5500:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5501:         $path_part.='/';
                   5502:         my $path_and_file = $path_part.$file_part;
                   5503:         if ($path_part eq $path) {
                   5504:             $return_files{$file_part}= 'selected';
                   5505:         }
                   5506:     }
1.574     banghart 5507:     close (IN);
                   5508:     return (\%return_files);
1.572     banghart 5509: }
                   5510: 
                   5511: # called in portfolio select mode, to show files selected NOT in current directory
                   5512: sub files_not_in_path {
                   5513:     my ($user, $path) = @_;
                   5514:     my $filename = $user."savedfiles";
                   5515:     my @return_files;
                   5516:     my $path_part;
1.800     albertel 5517:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5518:     while (my $line = <IN>) {
1.572     banghart 5519:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5520:         my @paths_and_file = split(m|/|, $line);
                   5521:         my $file_part = pop(@paths_and_file);
                   5522:         chomp($file_part);
                   5523:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5524:         $path_part .= '/';
                   5525:         my $path_and_file = $path_part.$file_part;
                   5526:         if ($path_part ne $path) {
1.800     albertel 5527:             push(@return_files, ($path_and_file));
1.572     banghart 5528:         }
                   5529:     }
1.800     albertel 5530:     close(OUT);
1.574     banghart 5531:     return (@return_files);
1.572     banghart 5532: }
                   5533: 
1.745     raeburn  5534: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5535: 
1.745     raeburn  5536: sub get_portfile_permissions {
                   5537:     my ($domain,$user) = @_;
1.613     albertel 5538:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5539:     my ($tmp)=keys(%current_permissions);
                   5540:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5541:     return \%current_permissions;
                   5542: }
                   5543: 
                   5544: #---------------------------------------------Get portfolio file access controls
                   5545: 
1.749     raeburn  5546: sub get_access_controls {
1.745     raeburn  5547:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5548:     my %access;
                   5549:     my $real_file = $file;
                   5550:     $file =~ s/\.meta$//;
1.745     raeburn  5551:     if (defined($file)) {
1.749     raeburn  5552:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5553:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5554:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5555:             }
                   5556:         }
1.745     raeburn  5557:     } else {
1.749     raeburn  5558:         foreach my $key (keys(%{$current_permissions})) {
                   5559:             if ($key =~ /\0accesscontrol$/) {
                   5560:                 if (defined($group)) {
                   5561:                     if ($key !~ m-^\Q$group\E/-) {
                   5562:                         next;
                   5563:                     }
                   5564:                 }
                   5565:                 my ($fullpath) = split(/\0/,$key);
                   5566:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5567:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5568:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5569:                     }
                   5570:                 }
                   5571:             }
                   5572:         }
                   5573:     }
                   5574:     return %access;
                   5575: }
                   5576: 
                   5577: sub modify_access_controls {
                   5578:     my ($file_name,$changes,$domain,$user)=@_;
                   5579:     my ($outcome,$deloutcome);
                   5580:     my %store_permissions;
                   5581:     my %new_values;
                   5582:     my %new_control;
                   5583:     my %translation;
                   5584:     my @deletions = ();
                   5585:     my $now = time;
                   5586:     if (exists($$changes{'activate'})) {
                   5587:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5588:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5589:             my $numnew = scalar(@newitems);
                   5590:             for (my $i=0; $i<$numnew; $i++) {
                   5591:                 my $newkey = $newitems[$i];
                   5592:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5593:                 if ($newkey =~ /^\d+:/) { 
                   5594:                     $newkey =~ s/^(\d+)/$newid/;
                   5595:                     $translation{$1} = $newid;
                   5596:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5597:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5598:                     $translation{$1} = $newid;
                   5599:                 }
1.749     raeburn  5600:                 $new_values{$file_name."\0".$newkey} = 
                   5601:                                           $$changes{'activate'}{$newitems[$i]};
                   5602:                 $new_control{$newkey} = $now;
                   5603:             }
                   5604:         }
                   5605:     }
                   5606:     my %todelete;
                   5607:     my %changed_items;
                   5608:     foreach my $action ('delete','update') {
                   5609:         if (exists($$changes{$action})) {
                   5610:             if (ref($$changes{$action}) eq 'HASH') {
                   5611:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5612:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5613:                     if ($action eq 'delete') { 
                   5614:                         $todelete{$itemnum} = 1;
                   5615:                     } else {
                   5616:                         $changed_items{$itemnum} = $key;
                   5617:                     }
                   5618:                 }
1.745     raeburn  5619:             }
                   5620:         }
1.749     raeburn  5621:     }
                   5622:     # get lock on access controls for file.
                   5623:     my $lockhash = {
                   5624:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5625:                                                        ':'.$env{'user.domain'},
                   5626:                    }; 
                   5627:     my $tries = 0;
                   5628:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5629:    
                   5630:     while (($gotlock ne 'ok') && $tries <3) {
                   5631:         $tries ++;
                   5632:         sleep 1;
                   5633:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5634:     }
                   5635:     if ($gotlock eq 'ok') {
                   5636:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5637:         my ($tmp)=keys(%curr_permissions);
                   5638:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5639:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5640:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5641:             if (ref($curr_controls) eq 'HASH') {
                   5642:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5643:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5644:                     if (defined($todelete{$itemnum})) {
                   5645:                         push(@deletions,$file_name."\0".$control_item);
                   5646:                     } else {
                   5647:                         if (defined($changed_items{$itemnum})) {
                   5648:                             $new_control{$changed_items{$itemnum}} = $now;
                   5649:                             push(@deletions,$file_name."\0".$control_item);
                   5650:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5651:                         } else {
                   5652:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5653:                         }
                   5654:                     }
1.745     raeburn  5655:                 }
                   5656:             }
                   5657:         }
1.749     raeburn  5658:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5659:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5660:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5661:         #  remove lock
                   5662:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5663:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5664:         my ($file,$group);
                   5665:         if (&is_course($domain,$user)) {
                   5666:             ($group,$file) = split(/\//,$file_name,2);
                   5667:         } else {
                   5668:             $file = $file_name;
                   5669:         }
                   5670:         my $sqlresult =
                   5671:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5672:                                     $group);
1.749     raeburn  5673:     } else {
                   5674:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5675:     }
1.749     raeburn  5676:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5677: }
                   5678: 
1.827     raeburn  5679: sub make_public_indefinitely {
                   5680:     my ($requrl) = @_;
                   5681:     my $now = time;
                   5682:     my $action = 'activate';
                   5683:     my $aclnum = 0;
                   5684:     if (&is_portfolio_url($requrl)) {
                   5685:         my (undef,$udom,$unum,$file_name,$group) =
                   5686:             &parse_portfolio_url($requrl);
                   5687:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5688:         my %access_controls = &get_access_controls($current_perms,
                   5689:                                                    $group,$file_name);
                   5690:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5691:             my ($num,$scope,$end,$start) = 
                   5692:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5693:             if ($scope eq 'public') {
                   5694:                 if ($start <= $now && $end == 0) {
                   5695:                     $action = 'none';
                   5696:                 } else {
                   5697:                     $action = 'update';
                   5698:                     $aclnum = $num;
                   5699:                 }
                   5700:                 last;
                   5701:             }
                   5702:         }
                   5703:         if ($action eq 'none') {
                   5704:              return 'ok';
                   5705:         } else {
                   5706:             my %changes;
                   5707:             my $newend = 0;
                   5708:             my $newstart = $now;
                   5709:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5710:             $changes{$action}{$newkey} = {
                   5711:                 type => 'public',
                   5712:                 time => {
                   5713:                     start => $newstart,
                   5714:                     end   => $newend,
                   5715:                 },
                   5716:             };
                   5717:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5718:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5719:             return $outcome;
                   5720:         }
                   5721:     } else {
                   5722:         return 'invalid';
                   5723:     }
                   5724: }
                   5725: 
1.745     raeburn  5726: #------------------------------------------------------Get Marked as Read Only
                   5727: 
                   5728: sub get_marked_as_readonly {
                   5729:     my ($domain,$user,$what,$group) = @_;
                   5730:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5731:     my @readonly_files;
1.629     banghart 5732:     my $cmp1=$what;
                   5733:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5734:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5735:         if (defined($group)) {
                   5736:             if ($file_name !~ m-^\Q$group\E/-) {
                   5737:                 next;
                   5738:             }
                   5739:         }
1.561     banghart 5740:         if (ref($value) eq "ARRAY"){
                   5741:             foreach my $stored_what (@{$value}) {
1.629     banghart 5742:                 my $cmp2=$stored_what;
1.759     albertel 5743:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5744:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5745:                 }
1.629     banghart 5746:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5747:                     push(@readonly_files, $file_name);
1.745     raeburn  5748:                     last;
1.563     banghart 5749:                 } elsif (!defined($what)) {
                   5750:                     push(@readonly_files, $file_name);
1.745     raeburn  5751:                     last;
1.561     banghart 5752:                 }
                   5753:             }
1.745     raeburn  5754:         }
1.561     banghart 5755:     }
                   5756:     return @readonly_files;
                   5757: }
1.577     banghart 5758: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5759: 
1.577     banghart 5760: sub get_marked_as_readonly_hash {
1.745     raeburn  5761:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5762:     my %readonly_files;
1.745     raeburn  5763:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5764:         if (defined($group)) {
                   5765:             if ($file_name !~ m-^\Q$group\E/-) {
                   5766:                 next;
                   5767:             }
                   5768:         }
1.577     banghart 5769:         if (ref($value) eq "ARRAY"){
                   5770:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5771:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5772:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5773:                         if ($lock_descriptor eq 'graded') {
                   5774:                             $readonly_files{$file_name} = 'graded';
                   5775:                         } elsif ($lock_descriptor eq 'handback') {
                   5776:                             $readonly_files{$file_name} = 'handback';
                   5777:                         } else {
                   5778:                             if (!exists($readonly_files{$file_name})) {
                   5779:                                 $readonly_files{$file_name} = 'locked';
                   5780:                             }
                   5781:                         }
1.745     raeburn  5782:                     }
1.750     banghart 5783:                 } 
1.577     banghart 5784:             }
                   5785:         } 
                   5786:     }
                   5787:     return %readonly_files;
                   5788: }
1.559     banghart 5789: # ------------------------------------------------------------ Unmark as Read Only
                   5790: 
                   5791: sub unmark_as_readonly {
1.629     banghart 5792:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5793:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5794:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5795:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5796:     my $symb_crs = $what;
                   5797:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5798:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5799:     my ($tmp)=keys(%current_permissions);
                   5800:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5801:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5802:     foreach my $file (@readonly_files) {
1.759     albertel 5803: 	my $clean_file = &declutter_portfile($file);
                   5804: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5805: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5806:         my @new_locks;
                   5807:         my @del_keys;
                   5808:         if (ref($current_locks) eq "ARRAY"){
                   5809:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5810:                 my $compare=$locker;
1.749     raeburn  5811:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5812:                     $compare=join('',@{$locker});
1.746     raeburn  5813:                     if ($compare ne $symb_crs) {
                   5814:                         push(@new_locks, $locker);
                   5815:                     }
1.563     banghart 5816:                 }
                   5817:             }
1.650     albertel 5818:             if (scalar(@new_locks) > 0) {
1.563     banghart 5819:                 $current_permissions{$file} = \@new_locks;
                   5820:             } else {
                   5821:                 push(@del_keys, $file);
1.613     albertel 5822:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5823:                 delete($current_permissions{$file});
1.563     banghart 5824:             }
                   5825:         }
1.561     banghart 5826:     }
1.613     albertel 5827:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5828:     return;
                   5829: }
1.512     banghart 5830: 
1.17      www      5831: # ------------------------------------------------------------ Directory lister
                   5832: 
                   5833: sub dirlist {
1.253     stredwic 5834:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5835: 
1.18      www      5836:     $uri=~s/^\///;
                   5837:     $uri=~s/\/$//;
1.253     stredwic 5838:     my ($udom, $uname);
                   5839:     (undef,$udom,$uname)=split(/\//,$uri);
                   5840:     if(defined($userdomain)) {
                   5841:         $udom = $userdomain;
                   5842:     }
                   5843:     if(defined($username)) {
                   5844:         $uname = $username;
                   5845:     }
                   5846: 
                   5847:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5848:     if(defined($alternateDirectoryRoot)) {
                   5849:         $dirRoot = $alternateDirectoryRoot;
                   5850:         $dirRoot =~ s/\/$//;
1.751     banghart 5851:     }
1.253     stredwic 5852: 
                   5853:     if($udom) {
                   5854:         if($uname) {
1.800     albertel 5855:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5856: 				 &homeserver($uname,$udom));
1.605     matthew  5857:             my @listing_results;
                   5858:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5859:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5860: 				  &homeserver($uname,$udom));
1.605     matthew  5861:                 @listing_results = split(/:/,$listing);
                   5862:             } else {
                   5863:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5864:             }
                   5865:             return @listing_results;
1.253     stredwic 5866:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5867:             my %allusers;
1.841     albertel 5868: 	    my %servers = &get_servers($udom,'library');
                   5869: 	    foreach my $tryserver (keys(%servers)) {
                   5870: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5871: 				     $udom, $tryserver);
                   5872: 		my @listing_results;
                   5873: 		if ($listing eq 'unknown_cmd') {
                   5874: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5875: 				      $udom, $tryserver);
                   5876: 		    @listing_results = split(/:/,$listing);
                   5877: 		} else {
                   5878: 		    @listing_results =
                   5879: 			map { &unescape($_); } split(/:/,$listing);
                   5880: 		}
                   5881: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5882: 		    $listing_results[0] ne 'empty'       &&
                   5883: 		    $listing_results[0] ne 'con_lost') {
                   5884: 		    foreach my $line (@listing_results) {
                   5885: 			my ($entry) = split(/&/,$line,2);
                   5886: 			$allusers{$entry} = 1;
                   5887: 		    }
                   5888: 		}
1.253     stredwic 5889:             }
                   5890:             my $alluserstr='';
1.800     albertel 5891:             foreach my $user (sort(keys(%allusers))) {
                   5892:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5893:             }
                   5894:             $alluserstr=~s/:$//;
                   5895:             return split(/:/,$alluserstr);
                   5896:         } else {
1.800     albertel 5897:             return ('missing user name');
1.253     stredwic 5898:         }
                   5899:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5900:         my @all_domains = sort(&all_domains());
                   5901:          foreach my $domain (@all_domains) {
                   5902:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5903:          }
                   5904:          return @all_domains;
                   5905:      } else {
1.800     albertel 5906:         return ('missing domain');
1.275     stredwic 5907:     }
                   5908: }
                   5909: 
                   5910: # --------------------------------------------- GetFileTimestamp
                   5911: # This function utilizes dirlist and returns the date stamp for
                   5912: # when it was last modified.  It will also return an error of -1
                   5913: # if an error occurs
                   5914: 
1.410     matthew  5915: ##
                   5916: ## FIXME: This subroutine assumes its caller knows something about the
                   5917: ## directory structure of the home server for the student ($root).
                   5918: ## Not a good assumption to make.  Since this is for looking up files
                   5919: ## in user directories, the full path should be constructed by lond, not
                   5920: ## whatever machine we request data from.
                   5921: ##
1.275     stredwic 5922: sub GetFileTimestamp {
                   5923:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5924:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5925:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5926:     my $subdir=$studentName.'__';
                   5927:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5928:     my $proname="$studentDomain/$subdir/$studentName";
                   5929:     $proname .= '/'.$filename;
1.375     matthew  5930:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5931:                                               $studentName, $root);
1.275     stredwic 5932:     my @stats = split('&', $fileStat);
                   5933:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5934:         # @stats contains first the filename, then the stat output
                   5935:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5936:     } else {
                   5937:         return -1;
1.253     stredwic 5938:     }
1.26      www      5939: }
                   5940: 
1.712     albertel 5941: sub stat_file {
                   5942:     my ($uri) = @_;
1.787     albertel 5943:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5944: 
1.712     albertel 5945:     my ($udom,$uname,$file,$dir);
                   5946:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5947: 	($udom,$uname,$file) =
1.811     albertel 5948: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5949: 	$file = 'userfiles/'.$file;
1.740     www      5950: 	$dir = &propath($udom,$uname);
1.712     albertel 5951:     }
                   5952:     if ($uri =~ m-^/res/-) {
                   5953: 	($udom,$uname) = 
1.807     albertel 5954: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5955: 	$file = $uri;
                   5956:     }
                   5957: 
                   5958:     if (!$udom || !$uname || !$file) {
                   5959: 	# unable to handle the uri
                   5960: 	return ();
                   5961:     }
                   5962: 
                   5963:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5964:     my @stats = split('&', $result);
1.721     banghart 5965:     
1.712     albertel 5966:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5967: 	shift(@stats); #filename is first
                   5968: 	return @stats;
                   5969:     }
                   5970:     return ();
                   5971: }
                   5972: 
1.26      www      5973: # -------------------------------------------------------- Value of a Condition
                   5974: 
1.713     albertel 5975: # gets the value of a specific preevaluated condition
                   5976: #    stored in the string  $env{user.state.<cid>}
                   5977: # or looks up a condition reference in the bighash and if if hasn't
                   5978: # already been evaluated recurses into docondval to get the value of
                   5979: # the condition, then memoizing it to 
                   5980: #   $env{user.state.<cid>.<condition>}
1.40      www      5981: sub directcondval {
                   5982:     my $number=shift;
1.620     albertel 5983:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5984: 	&Apache::lonuserstate::evalstate();
                   5985:     }
1.713     albertel 5986:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5987: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5988:     } elsif ($number =~ /^_/) {
                   5989: 	my $sub_condition;
                   5990: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5991: 		&GDBM_READER(),0640)) {
                   5992: 	    $sub_condition=$bighash{'conditions'.$number};
                   5993: 	    untie(%bighash);
                   5994: 	}
                   5995: 	my $value = &docondval($sub_condition);
                   5996: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5997: 	return $value;
                   5998:     }
1.620     albertel 5999:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6000:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6001:     } else {
                   6002:        return 2;
                   6003:     }
                   6004: }
                   6005: 
1.713     albertel 6006: # get the collection of conditions for this resource
1.26      www      6007: sub condval {
                   6008:     my $condidx=shift;
1.54      www      6009:     my $allpathcond='';
1.713     albertel 6010:     foreach my $cond (split(/\|/,$condidx)) {
                   6011: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6012: 	    $allpathcond.=
                   6013: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6014: 	}
1.191     harris41 6015:     }
1.54      www      6016:     $allpathcond=~s/\|$//;
1.713     albertel 6017:     return &docondval($allpathcond);
                   6018: }
                   6019: 
                   6020: #evaluates an expression of conditions
                   6021: sub docondval {
                   6022:     my ($allpathcond) = @_;
                   6023:     my $result=0;
                   6024:     if ($env{'request.course.id'}
                   6025: 	&& defined($allpathcond)) {
                   6026: 	my $operand='|';
                   6027: 	my @stack;
                   6028: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6029: 	    if ($chunk eq '(') {
                   6030: 		push @stack,($operand,$result);
                   6031: 	    } elsif ($chunk eq ')') {
                   6032: 		my $before=pop @stack;
                   6033: 		if (pop @stack eq '&') {
                   6034: 		    $result=$result>$before?$before:$result;
                   6035: 		} else {
                   6036: 		    $result=$result>$before?$result:$before;
                   6037: 		}
                   6038: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6039: 		$operand=$chunk;
                   6040: 	    } else {
                   6041: 		my $new=directcondval($chunk);
                   6042: 		if ($operand eq '&') {
                   6043: 		    $result=$result>$new?$new:$result;
                   6044: 		} else {
                   6045: 		    $result=$result>$new?$result:$new;
                   6046: 		}
                   6047: 	    }
                   6048: 	}
1.26      www      6049:     }
                   6050:     return $result;
1.421     albertel 6051: }
                   6052: 
                   6053: # ---------------------------------------------------- Devalidate courseresdata
                   6054: 
                   6055: sub devalidatecourseresdata {
                   6056:     my ($coursenum,$coursedomain)=@_;
                   6057:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6058:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6059: }
                   6060: 
1.763     www      6061: 
1.200     www      6062: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6063: #
                   6064: #  Parameters:
                   6065: #      $coursenum    - Number of the course.
                   6066: #      $coursedomain - Domain at which the course was created.
                   6067: #  Returns:
                   6068: #     A hash of the course parameters along (I think) with timestamps
                   6069: #     and version info.
1.877     foxr     6070: 
1.624     albertel 6071: sub get_courseresdata {
                   6072:     my ($coursenum,$coursedomain)=@_;
1.200     www      6073:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6074:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6075:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6076:     my %dumpreply;
1.417     albertel 6077:     unless (defined($cached)) {
1.624     albertel 6078: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6079: 	$result=\%dumpreply;
1.251     albertel 6080: 	my ($tmp) = keys(%dumpreply);
                   6081: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6082: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6083: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6084: 	    return $tmp;
1.416     albertel 6085: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6086: 	    $result=undef;
1.599     albertel 6087: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6088: 	}
                   6089:     }
1.624     albertel 6090:     return $result;
                   6091: }
                   6092: 
1.633     albertel 6093: sub devalidateuserresdata {
                   6094:     my ($uname,$udom)=@_;
                   6095:     my $hashid="$udom:$uname";
                   6096:     &devalidate_cache_new('userres',$hashid);
                   6097: }
                   6098: 
1.624     albertel 6099: sub get_userresdata {
                   6100:     my ($uname,$udom)=@_;
                   6101:     #most student don\'t have any data set, check if there is some data
                   6102:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6103: 
                   6104:     my $hashid="$udom:$uname";
                   6105:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6106:     if (!defined($cached)) {
                   6107: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6108: 	$result=\%resourcedata;
                   6109: 	&do_cache_new('userres',$hashid,$result,600);
                   6110:     }
                   6111:     my ($tmp)=keys(%$result);
                   6112:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6113: 	return $result;
                   6114:     }
                   6115:     #error 2 occurs when the .db doesn't exist
                   6116:     if ($tmp!~/error: 2 /) {
1.672     albertel 6117: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6118: 		 " Trying to get resource data for ".
                   6119: 		 $uname." at ".$udom.": ".
                   6120: 		 $tmp."</font>");
                   6121:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6122: 	#&EXT_cache_set($udom,$uname);
                   6123: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6124: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6125:     }
                   6126:     return $tmp;
                   6127: }
1.879     foxr     6128: #----------------------------------------------- resdata - return resource data
                   6129: #  Purpose:
                   6130: #    Return resource data for either users or for a course.
                   6131: #  Parameters:
                   6132: #     $name      - Course/user name.
                   6133: #     $domain    - Name of the domain the user/course is registered on.
                   6134: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6135: #     @which     - Array of names of resources desired.
                   6136: #  Returns:
                   6137: #     The value of the first reasource in @which that is found in the
                   6138: #     resource hash.
                   6139: #  Exceptional Conditions:
                   6140: #     If the $type passed in is not valid (not the string 'course' or 
                   6141: #     'user', an undefined  reference is returned.
                   6142: #     If none of the resources are found, an undef is returned
1.624     albertel 6143: sub resdata {
                   6144:     my ($name,$domain,$type,@which)=@_;
                   6145:     my $result;
                   6146:     if ($type eq 'course') {
                   6147: 	$result=&get_courseresdata($name,$domain);
                   6148:     } elsif ($type eq 'user') {
                   6149: 	$result=&get_userresdata($name,$domain);
                   6150:     }
                   6151:     if (!ref($result)) { return $result; }    
1.251     albertel 6152:     foreach my $item (@which) {
1.417     albertel 6153: 	if (defined($result->{$item})) {
                   6154: 	    return $result->{$item};
1.251     albertel 6155: 	}
1.250     albertel 6156:     }
1.291     albertel 6157:     return undef;
1.200     www      6158: }
                   6159: 
1.379     matthew  6160: #
                   6161: # EXT resource caching routines
                   6162: #
                   6163: 
                   6164: sub clear_EXT_cache_status {
1.383     albertel 6165:     &delenv('cache.EXT.');
1.379     matthew  6166: }
                   6167: 
                   6168: sub EXT_cache_status {
                   6169:     my ($target_domain,$target_user) = @_;
1.383     albertel 6170:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6171:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6172:         # We know already the user has no data
                   6173:         return 1;
                   6174:     } else {
                   6175:         return 0;
                   6176:     }
                   6177: }
                   6178: 
                   6179: sub EXT_cache_set {
                   6180:     my ($target_domain,$target_user) = @_;
1.383     albertel 6181:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6182:     #&appenv($cachename => time);
1.379     matthew  6183: }
                   6184: 
1.28      www      6185: # --------------------------------------------------------- Value of a Variable
1.58      www      6186: sub EXT {
1.715     albertel 6187: 
1.395     albertel 6188:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6189:     unless ($varname) { return ''; }
1.218     albertel 6190:     #get real user name/domain, courseid and symb
                   6191:     my $courseid;
1.359     albertel 6192:     my $publicuser;
1.427     www      6193:     if ($symbparm) {
                   6194: 	$symbparm=&get_symb_from_alias($symbparm);
                   6195:     }
1.218     albertel 6196:     if (!($uname && $udom)) {
1.790     albertel 6197:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6198:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6199:     } else {
1.620     albertel 6200: 	$courseid=$env{'request.course.id'};
1.218     albertel 6201:     }
1.48      www      6202:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6203:     my $rest;
1.320     albertel 6204:     if (defined($therest[0])) {
1.48      www      6205:        $rest=join('.',@therest);
                   6206:     } else {
                   6207:        $rest='';
                   6208:     }
1.320     albertel 6209: 
1.57      www      6210:     my $qualifierrest=$qualifier;
                   6211:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6212:     my $spacequalifierrest=$space;
                   6213:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6214:     if ($realm eq 'user') {
1.48      www      6215: # --------------------------------------------------------------- user.resource
                   6216: 	if ($space eq 'resource') {
1.651     albertel 6217: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6218: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6219: 		 &&
1.744     albertel 6220: 		 ($symbparm eq &symbread()) ) {	
                   6221: 		# if we are in the middle of processing the resource the
                   6222: 		# get the value we are planning on committing
                   6223:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6224:                     return $Apache::lonhomework::results{$qualifierrest};
                   6225:                 } else {
                   6226:                     return $Apache::lonhomework::history{$qualifierrest};
                   6227:                 }
1.335     albertel 6228: 	    } else {
1.359     albertel 6229: 		my %restored;
1.620     albertel 6230: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6231: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6232: 		} else {
                   6233: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6234: 		}
1.335     albertel 6235: 		return $restored{$qualifierrest};
                   6236: 	    }
1.48      www      6237: # ----------------------------------------------------------------- user.access
                   6238:         } elsif ($space eq 'access') {
1.218     albertel 6239: 	    # FIXME - not supporting calls for a specific user
1.48      www      6240:             return &allowed($qualifier,$rest);
                   6241: # ------------------------------------------ user.preferences, user.environment
                   6242:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6243: 	    if (($uname eq $env{'user.name'}) &&
                   6244: 		($udom eq $env{'user.domain'})) {
                   6245: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6246: 	    } else {
1.359     albertel 6247: 		my %returnhash;
                   6248: 		if (!$publicuser) {
                   6249: 		    %returnhash=&userenvironment($udom,$uname,
                   6250: 						 $qualifierrest);
                   6251: 		}
1.218     albertel 6252: 		return $returnhash{$qualifierrest};
                   6253: 	    }
1.48      www      6254: # ----------------------------------------------------------------- user.course
                   6255:         } elsif ($space eq 'course') {
1.218     albertel 6256: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6257:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6258: # ------------------------------------------------------------------- user.role
                   6259:         } elsif ($space eq 'role') {
1.218     albertel 6260: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6261:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6262:             if ($qualifier eq 'value') {
                   6263: 		return $role;
                   6264:             } elsif ($qualifier eq 'extent') {
                   6265:                 return $where;
                   6266:             }
                   6267: # ----------------------------------------------------------------- user.domain
                   6268:         } elsif ($space eq 'domain') {
1.218     albertel 6269:             return $udom;
1.48      www      6270: # ------------------------------------------------------------------- user.name
                   6271:         } elsif ($space eq 'name') {
1.218     albertel 6272:             return $uname;
1.48      www      6273: # ---------------------------------------------------- Any other user namespace
1.29      www      6274:         } else {
1.359     albertel 6275: 	    my %reply;
                   6276: 	    if (!$publicuser) {
                   6277: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6278: 	    }
                   6279: 	    return $reply{$qualifierrest};
1.48      www      6280:         }
1.236     www      6281:     } elsif ($realm eq 'query') {
                   6282: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6283:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6284: 						[$spacequalifierrest]);
1.620     albertel 6285: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6286:    } elsif ($realm eq 'request') {
1.48      www      6287: # ------------------------------------------------------------- request.browser
                   6288:         if ($space eq 'browser') {
1.430     www      6289: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6290: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6291: 		    return 1;
                   6292: 		} else {
                   6293: 		    return 0;
                   6294: 		}
                   6295: 	    } else {
1.620     albertel 6296: 		return $env{'browser.'.$qualifier};
1.430     www      6297: 	    }
1.57      www      6298: # ------------------------------------------------------------ request.filename
                   6299:         } else {
1.620     albertel 6300:             return $env{'request.'.$spacequalifierrest};
1.29      www      6301:         }
1.28      www      6302:     } elsif ($realm eq 'course') {
1.48      www      6303: # ---------------------------------------------------------- course.description
1.620     albertel 6304:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6305:     } elsif ($realm eq 'resource') {
1.165     www      6306: 
1.620     albertel 6307: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6308: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6309: 	}
1.693     albertel 6310: 
                   6311: 	if ($space eq 'title') {
                   6312: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6313: 	    return &gettitle($symbparm);
                   6314: 	}
                   6315: 	
                   6316: 	if ($space eq 'map') {
                   6317: 	    my ($map) = &decode_symb($symbparm);
                   6318: 	    return &symbread($map);
                   6319: 	}
1.905     albertel 6320: 	if ($space eq 'filename') {
                   6321: 	    if ($symbparm) {
                   6322: 		return &clutter((&decode_symb($symbparm))[2]);
                   6323: 	    }
                   6324: 	    return &hreflocation('',$env{'request.filename'});
                   6325: 	}
1.693     albertel 6326: 
                   6327: 	my ($section, $group, @groups);
1.593     albertel 6328: 	my ($courselevelm,$courselevel);
1.539     albertel 6329: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6330: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6331: 
1.218     albertel 6332: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6333: 
1.60      www      6334: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6335: 	    my $symbp=$symbparm;
1.735     albertel 6336: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6337: 
                   6338: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6339: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6340: 
1.620     albertel 6341: 	    if (($env{'user.name'} eq $uname) &&
                   6342: 		($env{'user.domain'} eq $udom)) {
                   6343: 		$section=$env{'request.course.sec'};
1.733     raeburn  6344:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6345:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6346: 	    } else {
1.539     albertel 6347: 		if (! defined($usection)) {
1.551     albertel 6348: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6349: 		} else {
                   6350: 		    $section = $usection;
                   6351: 		}
1.733     raeburn  6352:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6353: 	    }
                   6354: 
                   6355: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6356: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6357: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6358: 
1.593     albertel 6359: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6360: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6361: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6362: 
1.60      www      6363: # ----------------------------------------------------------- first, check user
1.624     albertel 6364: 
                   6365: 	    my $userreply=&resdata($uname,$udom,'user',
                   6366: 				       ($courselevelr,$courselevelm,
                   6367: 					$courselevel));
                   6368: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6369: 
1.594     albertel 6370: # ------------------------------------------------ second, check some of course
1.684     raeburn  6371:             my $coursereply;
1.691     raeburn  6372:             if (@groups > 0) {
                   6373:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6374:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6375:                 if (defined($coursereply)) { return $coursereply; }
                   6376:             }
1.96      www      6377: 
1.684     raeburn  6378: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6379: 				     $env{'course.'.$courseid.'.domain'},
                   6380: 				     'course',
                   6381: 				     ($seclevelr,$seclevelm,$seclevel,
                   6382: 				      $courselevelr));
1.287     albertel 6383: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6384: 
1.60      www      6385: # ------------------------------------------------------ third, check map parms
1.218     albertel 6386: 	    my %parmhash=();
                   6387: 	    my $thisparm='';
                   6388: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6389: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6390: 		    &GDBM_READER(),0640)) {
1.218     albertel 6391: 		$thisparm=$parmhash{$symbparm};
                   6392: 		untie(%parmhash);
                   6393: 	    }
                   6394: 	    if ($thisparm) { return $thisparm; }
                   6395: 	}
1.594     albertel 6396: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6397: 
1.218     albertel 6398: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6399: 	my $filename;
                   6400: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6401: 	if ($symbparm) {
1.409     www      6402: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6403: 	} else {
1.620     albertel 6404: 	    $filename=$env{'request.filename'};
1.282     albertel 6405: 	}
                   6406: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6407: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6408: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6409: 	if (defined($metadata)) { return $metadata; }
1.142     www      6410: 
1.594     albertel 6411: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6412: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6413: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6414: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6415: 				     $env{'course.'.$courseid.'.domain'},
                   6416: 				     'course',
                   6417: 				     ($courselevelm,$courselevel));
1.593     albertel 6418: 	    if (defined($coursereply)) { return $coursereply; }
                   6419: 	}
1.145     www      6420: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6421: 	unless ($space eq '0') {
1.336     albertel 6422: 	    my @parts=split(/_/,$space);
                   6423: 	    my $id=pop(@parts);
                   6424: 	    my $part=join('_',@parts);
                   6425: 	    if ($part eq '') { $part='0'; }
                   6426: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6427: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6428: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6429: 	}
1.395     albertel 6430: 	if ($recurse) { return undef; }
                   6431: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6432: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6433: 
1.48      www      6434: # ---------------------------------------------------- Any other user namespace
                   6435:     } elsif ($realm eq 'environment') {
                   6436: # ----------------------------------------------------------------- environment
1.620     albertel 6437: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6438: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6439: 	} else {
1.770     albertel 6440: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6441: 		return '';
                   6442: 	    }
1.219     albertel 6443: 	    my %returnhash=&userenvironment($udom,$uname,
                   6444: 					    $spacequalifierrest);
                   6445: 	    return $returnhash{$spacequalifierrest};
                   6446: 	}
1.28      www      6447:     } elsif ($realm eq 'system') {
1.48      www      6448: # ----------------------------------------------------------------- system.time
                   6449: 	if ($space eq 'time') {
                   6450: 	    return time;
                   6451:         }
1.696     albertel 6452:     } elsif ($realm eq 'server') {
                   6453: # ----------------------------------------------------------------- system.time
                   6454: 	if ($space eq 'name') {
                   6455: 	    return $ENV{'SERVER_NAME'};
                   6456:         }
1.28      www      6457:     }
1.48      www      6458:     return '';
1.61      www      6459: }
                   6460: 
1.691     raeburn  6461: sub check_group_parms {
                   6462:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6463:     my @groupitems = ();
                   6464:     my $resultitem;
                   6465:     my @levels = ($symbparm,$mapparm,$what);
                   6466:     foreach my $group (@{$groups}) {
                   6467:         foreach my $level (@levels) {
                   6468:              my $item = $courseid.'.['.$group.'].'.$level;
                   6469:              push(@groupitems,$item);
                   6470:         }
                   6471:     }
                   6472:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6473:                             $env{'course.'.$courseid.'.domain'},
                   6474:                                      'course',@groupitems);
                   6475:     return $coursereply;
                   6476: }
                   6477: 
                   6478: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6479:     my ($courseid,@groups) = @_;
                   6480:     @groups = sort(@groups);
1.691     raeburn  6481:     return @groups;
                   6482: }
                   6483: 
1.395     albertel 6484: sub packages_tab_default {
                   6485:     my ($uri,$varname)=@_;
                   6486:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6487: 
                   6488:     my (@extension,@specifics,$do_default);
                   6489:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6490: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6491: 	if ($pack_type eq 'default') {
                   6492: 	    $do_default=1;
                   6493: 	} elsif ($pack_type eq 'extension') {
                   6494: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6495: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6496: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6497: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6498: 	}
                   6499:     }
                   6500:     # first look for a package that matches the requested part id
                   6501:     foreach my $package (@specifics) {
                   6502: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6503: 	next if ($pack_part ne $part);
                   6504: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6505: 	    return $packagetab{"$pack_type&$name&default"};
                   6506: 	}
                   6507:     }
                   6508:     # look for any possible matching non extension_ package
                   6509:     foreach my $package (@specifics) {
                   6510: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6511: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6512: 	    return $packagetab{"$pack_type&$name&default"};
                   6513: 	}
1.585     albertel 6514: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6515: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6516: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6517: 	}
                   6518:     }
1.738     albertel 6519:     # look for any posible extension_ match
                   6520:     foreach my $package (@extension) {
                   6521: 	my ($package,$pack_type)=@{$package};
                   6522: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6523: 	    return $packagetab{"$pack_type&$name&default"};
                   6524: 	}
                   6525: 	if (defined($packagetab{$package."&$name&default"})) {
                   6526: 	    return $packagetab{$package."&$name&default"};
                   6527: 	}
                   6528:     }
                   6529:     # look for a global default setting
                   6530:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6531: 	return $packagetab{"default&$name&default"};
                   6532:     }
1.395     albertel 6533:     return undef;
                   6534: }
                   6535: 
1.334     albertel 6536: sub add_prefix_and_part {
                   6537:     my ($prefix,$part)=@_;
                   6538:     my $keyroot;
                   6539:     if (defined($prefix) && $prefix !~ /^__/) {
                   6540: 	# prefix that has a part already
                   6541: 	$keyroot=$prefix;
                   6542:     } elsif (defined($prefix)) {
                   6543: 	# prefix that is missing a part
                   6544: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6545:     } else {
                   6546: 	# no prefix at all
                   6547: 	if (defined($part)) { $keyroot='_'.$part; }
                   6548:     }
                   6549:     return $keyroot;
                   6550: }
                   6551: 
1.71      www      6552: # ---------------------------------------------------------------- Get metadata
                   6553: 
1.599     albertel 6554: my %metaentry;
1.71      www      6555: sub metadata {
1.176     www      6556:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6557:     $uri=&declutter($uri);
1.288     albertel 6558:     # if it is a non metadata possible uri return quickly
1.529     albertel 6559:     if (($uri eq '') || 
                   6560: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6561: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6562:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6563: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6564: 	return undef;
1.288     albertel 6565:     }
1.73      www      6566:     my $filename=$uri;
                   6567:     $uri=~s/\.meta$//;
1.172     www      6568: #
                   6569: # Is the metadata already cached?
1.177     www      6570: # Look at timestamp of caching
1.172     www      6571: # Everything is cached by the main uri, libraries are never directly cached
                   6572: #
1.428     albertel 6573:     if (!defined($liburi)) {
1.599     albertel 6574: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6575: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6576:     }
                   6577:     {
1.172     www      6578: #
                   6579: # Is this a recursive call for a library?
                   6580: #
1.599     albertel 6581: #	if (! exists($metacache{$uri})) {
                   6582: #	    $metacache{$uri}={};
                   6583: #	}
1.171     www      6584:         if ($liburi) {
                   6585: 	    $liburi=&declutter($liburi);
                   6586:             $filename=$liburi;
1.401     bowersj2 6587:         } else {
1.599     albertel 6588: 	    &devalidate_cache_new('meta',$uri);
                   6589: 	    undef(%metaentry);
1.401     bowersj2 6590: 	}
1.140     www      6591:         my %metathesekeys=();
1.73      www      6592:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6593: 	my $metastring;
1.768     albertel 6594: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6595: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6596: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6597: 	    $metastring=&getfile($file);
1.489     albertel 6598: 	}
1.208     albertel 6599:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6600:         my $token;
1.140     www      6601:         undef %metathesekeys;
1.71      www      6602:         while ($token=$parser->get_token) {
1.339     albertel 6603: 	    if ($token->[0] eq 'S') {
                   6604: 		if (defined($token->[2]->{'package'})) {
1.172     www      6605: #
                   6606: # This is a package - get package info
                   6607: #
1.339     albertel 6608: 		    my $package=$token->[2]->{'package'};
                   6609: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6610: 		    if (defined($token->[2]->{'id'})) { 
                   6611: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6612: 		    }
1.599     albertel 6613: 		    if ($metaentry{':packages'}) {
                   6614: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6615: 		    } else {
1.599     albertel 6616: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6617: 		    }
1.736     albertel 6618: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6619: 			my $part=$keyroot;
                   6620: 			$part=~s/^\_//;
1.736     albertel 6621: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6622: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6623: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6624: 			    # ignore package.tab specified default values
                   6625:                             # here &package_tab_default() will fetch those
                   6626: 			    if ($subp eq 'default') { next; }
1.736     albertel 6627: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6628: 			    my $unikey;
                   6629: 			    if ($pack =~ /_0$/) {
                   6630: 				$unikey='parameter_0_'.$name;
                   6631: 				$part=0;
                   6632: 			    } else {
                   6633: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6634: 			    }
1.339     albertel 6635: 			    if ($subp eq 'display') {
                   6636: 				$value.=' [Part: '.$part.']';
                   6637: 			    }
1.599     albertel 6638: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6639: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6640: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6641: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6642: 			    }
1.599     albertel 6643: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6644: 				$metaentry{':'.$unikey}=
                   6645: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6646: 			    }
1.339     albertel 6647: 			}
                   6648: 		    }
                   6649: 		} else {
1.172     www      6650: #
                   6651: # This is not a package - some other kind of start tag
1.339     albertel 6652: #
                   6653: 		    my $entry=$token->[1];
                   6654: 		    my $unikey;
                   6655: 		    if ($entry eq 'import') {
                   6656: 			$unikey='';
                   6657: 		    } else {
                   6658: 			$unikey=$entry;
                   6659: 		    }
                   6660: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6661: 
                   6662: 		    if (defined($token->[2]->{'id'})) { 
                   6663: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6664: 		    }
1.175     www      6665: 
1.339     albertel 6666: 		    if ($entry eq 'import') {
1.175     www      6667: #
                   6668: # Importing a library here
1.339     albertel 6669: #
                   6670: 			if ($depthcount<20) {
                   6671: 			    my $location=$parser->get_text('/import');
                   6672: 			    my $dir=$filename;
                   6673: 			    $dir=~s|[^/]*$||;
                   6674: 			    $location=&filelocation($dir,$location);
1.736     albertel 6675: 			    my $metadata = 
                   6676: 				&metadata($uri,'keys', $location,$unikey,
                   6677: 					  $depthcount+1);
                   6678: 			    foreach my $meta (split(',',$metadata)) {
                   6679: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6680: 				$metathesekeys{$meta}=1;
1.339     albertel 6681: 			    }
                   6682: 			}
                   6683: 		    } else { 
                   6684: 			
                   6685: 			if (defined($token->[2]->{'name'})) { 
                   6686: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6687: 			}
                   6688: 			$metathesekeys{$unikey}=1;
1.736     albertel 6689: 			foreach my $param (@{$token->[3]}) {
                   6690: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6691: 				$token->[2]->{$param};
1.339     albertel 6692: 			}
                   6693: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6694: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6695: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6696: 		 # only ws inside the tag, and not in default, so use default
                   6697: 		 # as value
1.599     albertel 6698: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6699: 			} else {
1.321     albertel 6700: 		  # either something interesting inside the tag or default
                   6701:                   # uninteresting
1.599     albertel 6702: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6703: 			}
1.172     www      6704: # end of not-a-package not-a-library import
1.339     albertel 6705: 		    }
1.172     www      6706: # end of not-a-package start tag
1.339     albertel 6707: 		}
1.172     www      6708: # the next is the end of "start tag"
1.339     albertel 6709: 	    }
                   6710: 	}
1.483     albertel 6711: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6712: 	$extension = lc($extension);
                   6713: 	if ($extension eq 'htm') { $extension='html'; }
                   6714: 
1.737     albertel 6715: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6716: 	    #no specific packages #how's our extension
                   6717: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6718: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6719: 					 \%metathesekeys);
                   6720: 	}
1.883     albertel 6721: 
                   6722: 	if (!exists($metaentry{':packages'})
                   6723: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6724: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6725: 		#no specific packages well let's get default then
                   6726: 		if ($key!~/^default&/) { next; }
1.488     albertel 6727: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6728: 					     \%metathesekeys);
                   6729: 	    }
                   6730: 	}
1.338     www      6731: # are there custom rights to evaluate
1.599     albertel 6732: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6733: 
1.338     www      6734:     #
                   6735:     # Importing a rights file here
1.339     albertel 6736:     #
                   6737: 	    unless ($depthcount) {
1.599     albertel 6738: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6739: 		my $dir=$filename;
                   6740: 		$dir=~s|[^/]*$||;
                   6741: 		$location=&filelocation($dir,$location);
1.736     albertel 6742: 		my $rights_metadata =
                   6743: 		    &metadata($uri,'keys',$location,'_rights',
                   6744: 			      $depthcount+1);
                   6745: 		foreach my $rights (split(',',$rights_metadata)) {
                   6746: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6747: 		    $metathesekeys{$rights}=1;
1.339     albertel 6748: 		}
                   6749: 	    }
                   6750: 	}
1.737     albertel 6751: 	# uniqifiy package listing
                   6752: 	my %seen;
                   6753: 	my @uniq_packages =
                   6754: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6755: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6756: 
                   6757: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6758: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6759: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6760: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6761: # this is the end of "was not already recently cached
1.71      www      6762:     }
1.599     albertel 6763:     return $metaentry{':'.$what};
1.261     albertel 6764: }
                   6765: 
1.488     albertel 6766: sub metadata_create_package_def {
1.483     albertel 6767:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6768:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6769:     if ($subp eq 'default') { next; }
                   6770:     
1.599     albertel 6771:     if (defined($metaentry{':packages'})) {
                   6772: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6773:     } else {
1.599     albertel 6774: 	$metaentry{':packages'}=$package;
1.483     albertel 6775:     }
                   6776:     my $value=$packagetab{$key};
                   6777:     my $unikey;
                   6778:     $unikey='parameter_0_'.$name;
1.599     albertel 6779:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6780:     $$metathesekeys{$unikey}=1;
1.599     albertel 6781:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6782: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6783:     }
1.599     albertel 6784:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6785: 	$metaentry{':'.$unikey}=
                   6786: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6787:     }
                   6788: }
                   6789: 
1.261     albertel 6790: sub metadata_generate_part0 {
                   6791:     my ($metadata,$metacache,$uri) = @_;
                   6792:     my %allnames;
1.737     albertel 6793:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6794: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6795: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6796: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6797: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6798: 	    $allnames{$name}=$part;
                   6799: 	  }
                   6800: 	}
                   6801:     }
                   6802:     foreach my $name (keys(%allnames)) {
                   6803:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6804:       my $key=":parameter_0_$name";
1.261     albertel 6805:       $$metacache{"$key.part"}='0';
                   6806:       $$metacache{"$key.name"}=$name;
1.428     albertel 6807:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6808: 					   $allnames{$name}.'_'.$name.
                   6809: 					   '.type'};
1.428     albertel 6810:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6811: 			     '.display'};
1.644     www      6812:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6813:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6814:       $$metacache{"$key.display"}=$olddis;
                   6815:     }
1.71      www      6816: }
                   6817: 
1.764     albertel 6818: # ------------------------------------------------------ Devalidate title cache
                   6819: 
                   6820: sub devalidate_title_cache {
                   6821:     my ($url)=@_;
                   6822:     if (!$env{'request.course.id'}) { return; }
                   6823:     my $symb=&symbread($url);
                   6824:     if (!$symb) { return; }
                   6825:     my $key=$env{'request.course.id'}."\0".$symb;
                   6826:     &devalidate_cache_new('title',$key);
                   6827: }
                   6828: 
1.301     www      6829: # ------------------------------------------------- Get the title of a resource
                   6830: 
                   6831: sub gettitle {
                   6832:     my $urlsymb=shift;
                   6833:     my $symb=&symbread($urlsymb);
1.534     albertel 6834:     if ($symb) {
1.620     albertel 6835: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6836: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6837: 	if (defined($cached)) { 
                   6838: 	    return $result;
                   6839: 	}
1.534     albertel 6840: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6841: 	my $title='';
1.907   ! albertel 6842: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
        !          6843: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
        !          6844: 	} else {
        !          6845: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
        !          6846: 		    &GDBM_READER(),0640)) {
        !          6847: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
        !          6848: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
        !          6849: 		untie(%bighash);
        !          6850: 	    }
1.534     albertel 6851: 	}
                   6852: 	$title=~s/\&colon\;/\:/gs;
                   6853: 	if ($title) {
1.599     albertel 6854: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6855: 	}
                   6856: 	$urlsymb=$url;
                   6857:     }
                   6858:     my $title=&metadata($urlsymb,'title');
                   6859:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6860:     return $title;
1.301     www      6861: }
1.613     albertel 6862: 
1.614     albertel 6863: sub get_slot {
                   6864:     my ($which,$cnum,$cdom)=@_;
                   6865:     if (!$cnum || !$cdom) {
1.790     albertel 6866: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6867: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6868: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6869:     }
1.703     albertel 6870:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6871:     my %slotinfo;
                   6872:     if (exists($remembered{$key})) {
                   6873: 	$slotinfo{$which} = $remembered{$key};
                   6874:     } else {
                   6875: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6876: 	&Apache::lonhomework::showhash(%slotinfo);
                   6877: 	my ($tmp)=keys(%slotinfo);
                   6878: 	if ($tmp=~/^error:/) { return (); }
                   6879: 	$remembered{$key} = $slotinfo{$which};
                   6880:     }
1.616     albertel 6881:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6882: 	return %{$slotinfo{$which}};
                   6883:     }
                   6884:     return $slotinfo{$which};
1.614     albertel 6885: }
1.31      www      6886: # ------------------------------------------------- Update symbolic store links
                   6887: 
                   6888: sub symblist {
                   6889:     my ($mapname,%newhash)=@_;
1.438     www      6890:     $mapname=&deversion(&declutter($mapname));
1.31      www      6891:     my %hash;
1.620     albertel 6892:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6893:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6894:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6895: 	    foreach my $url (keys %newhash) {
                   6896: 		next if ($url eq 'last_known'
                   6897: 			 && $env{'form.no_update_last_known'});
                   6898: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6899: 						    $newhash{$url}->[1],
                   6900: 						    $newhash{$url}->[0]);
1.191     harris41 6901:             }
1.31      www      6902:             if (untie(%hash)) {
                   6903: 		return 'ok';
                   6904:             }
                   6905:         }
                   6906:     }
                   6907:     return 'error';
1.212     www      6908: }
                   6909: 
                   6910: # --------------------------------------------------------------- Verify a symb
                   6911: 
                   6912: sub symbverify {
1.510     www      6913:     my ($symb,$thisurl)=@_;
                   6914:     my $thisfn=$thisurl;
1.439     www      6915:     $thisfn=&declutter($thisfn);
1.215     www      6916: # direct jump to resource in page or to a sequence - will construct own symbs
                   6917:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6918: # check URL part
1.409     www      6919:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6920: 
1.431     www      6921:     unless ($url eq $thisfn) { return 0; }
1.213     www      6922: 
1.216     www      6923:     $symb=&symbclean($symb);
1.510     www      6924:     $thisurl=&deversion($thisurl);
1.439     www      6925:     $thisfn=&deversion($thisfn);
1.213     www      6926: 
                   6927:     my %bighash;
                   6928:     my $okay=0;
1.431     www      6929: 
1.620     albertel 6930:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6931:                             &GDBM_READER(),0640)) {
1.510     www      6932:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6933:         unless ($ids) { 
1.510     www      6934:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6935:         }
                   6936:         if ($ids) {
                   6937: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6938: 	    foreach my $id (split(/\,/,$ids)) {
                   6939: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6940:                if (
                   6941:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6942:    eq $symb) { 
1.620     albertel 6943: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6944: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6945: 		       $okay=1; 
                   6946: 		   }
                   6947: 	       }
1.216     www      6948: 	   }
                   6949:         }
1.213     www      6950: 	untie(%bighash);
                   6951:     }
                   6952:     return $okay;
1.31      www      6953: }
                   6954: 
1.210     www      6955: # --------------------------------------------------------------- Clean-up symb
                   6956: 
                   6957: sub symbclean {
                   6958:     my $symb=shift;
1.568     albertel 6959:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6960: # remove version from map
                   6961:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6962: 
1.210     www      6963: # remove version from URL
                   6964:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6965: 
1.507     www      6966: # remove wrapper
                   6967: 
1.510     www      6968:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6969:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6970:     return $symb;
1.409     www      6971: }
                   6972: 
                   6973: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6974: 
                   6975: sub encode_symb {
                   6976:     my ($map,$resid,$url)=@_;
                   6977:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6978: }
1.409     www      6979: 
                   6980: sub decode_symb {
1.568     albertel 6981:     my $symb=shift;
                   6982:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6983:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6984:     return (&fixversion($map),$resid,&fixversion($url));
                   6985: }
                   6986: 
                   6987: sub fixversion {
                   6988:     my $fn=shift;
1.609     banghart 6989:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6990:     my %bighash;
                   6991:     my $uri=&clutter($fn);
1.620     albertel 6992:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6993: # is this cached?
1.599     albertel 6994:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6995:     if (defined($cached)) { return $result; }
                   6996: # unfortunately not cached, or expired
1.620     albertel 6997:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6998: 	    &GDBM_READER(),0640)) {
                   6999:  	if ($bighash{'version_'.$uri}) {
                   7000:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7001:  	    unless (($version eq 'mostrecent') || 
                   7002: 		    ($version==&getversion($uri))) {
1.440     www      7003:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7004:  	    }
                   7005:  	}
                   7006:  	untie %bighash;
1.413     www      7007:     }
1.599     albertel 7008:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7009: }
                   7010: 
                   7011: sub deversion {
                   7012:     my $url=shift;
                   7013:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7014:     return $url;
1.210     www      7015: }
                   7016: 
1.31      www      7017: # ------------------------------------------------------ Return symb list entry
                   7018: 
                   7019: sub symbread {
1.249     www      7020:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7021:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7022:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7023: # no filename provided? try from environment
1.44      www      7024:     unless ($thisfn) {
1.620     albertel 7025:         if ($env{'request.symb'}) {
                   7026: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7027: 	}
1.620     albertel 7028: 	$thisfn=$env{'request.filename'};
1.44      www      7029:     }
1.569     albertel 7030:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7031: # is that filename actually a symb? Verify, clean, and return
                   7032:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7033: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7034: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7035: 	}
1.242     www      7036:     }
1.44      www      7037:     $thisfn=declutter($thisfn);
1.31      www      7038:     my %hash;
1.37      www      7039:     my %bighash;
                   7040:     my $syval='';
1.620     albertel 7041:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7042:         my $targetfn = $thisfn;
1.609     banghart 7043:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7044:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7045:         }
1.687     albertel 7046: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7047: 	    $targetfn=$1;
                   7048: 	}
1.620     albertel 7049:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7050:                       &GDBM_READER(),0640)) {
1.481     raeburn  7051: 	    $syval=$hash{$targetfn};
1.37      www      7052:             untie(%hash);
                   7053:         }
                   7054: # ---------------------------------------------------------- There was an entry
                   7055:         if ($syval) {
1.601     albertel 7056: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7057: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7058: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7059: 		    #return $env{$cache_str}='';
1.601     albertel 7060: 		#}    
                   7061: 		#$syval.=$1;
                   7062: 	    #}
1.37      www      7063:         } else {
                   7064: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7065:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7066:                             &GDBM_READER(),0640)) {
1.37      www      7067: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7068:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7069:               unless ($ids) { 
                   7070:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7071:               }
                   7072:               unless ($ids) {
                   7073: # alias?
                   7074: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7075:               }
1.37      www      7076:               if ($ids) {
                   7077: # ------------------------------------------------------------------- Has ID(s)
                   7078:                  my @possibilities=split(/\,/,$ids);
1.39      www      7079:                  if ($#possibilities==0) {
                   7080: # ----------------------------------------------- There is only one possibility
1.37      www      7081: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7082: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7083: 						    $resid,$thisfn);
1.249     www      7084:                  } elsif (!$donotrecurse) {
1.39      www      7085: # ------------------------------------------ There is more than one possibility
                   7086:                      my $realpossible=0;
1.800     albertel 7087:                      foreach my $id (@possibilities) {
                   7088: 			 my $file=$bighash{'src_'.$id};
1.39      www      7089:                          if (&allowed('bre',$file)) {
1.800     albertel 7090:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7091:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7092: 				$realpossible++;
1.626     albertel 7093:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7094: 						    $resid,$thisfn);
1.39      www      7095:                             }
                   7096: 			 }
1.191     harris41 7097:                      }
1.39      www      7098: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7099:                  } else {
                   7100:                      $syval='';
1.37      www      7101:                  }
                   7102: 	      }
                   7103:               untie(%bighash)
1.481     raeburn  7104:            }
1.31      www      7105:         }
1.62      www      7106:         if ($syval) {
1.620     albertel 7107: 	    return $env{$cache_str}=$syval;
1.62      www      7108:         }
1.31      www      7109:     }
1.44      www      7110:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7111:     return $env{$cache_str}='';
1.31      www      7112: }
                   7113: 
                   7114: # ---------------------------------------------------------- Return random seed
                   7115: 
1.32      www      7116: sub numval {
                   7117:     my $txt=shift;
                   7118:     $txt=~tr/A-J/0-9/;
                   7119:     $txt=~tr/a-j/0-9/;
                   7120:     $txt=~tr/K-T/0-9/;
                   7121:     $txt=~tr/k-t/0-9/;
                   7122:     $txt=~tr/U-Z/0-5/;
                   7123:     $txt=~tr/u-z/0-5/;
                   7124:     $txt=~s/\D//g;
1.564     albertel 7125:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7126:     return int($txt);
1.368     albertel 7127: }
                   7128: 
1.484     albertel 7129: sub numval2 {
                   7130:     my $txt=shift;
                   7131:     $txt=~tr/A-J/0-9/;
                   7132:     $txt=~tr/a-j/0-9/;
                   7133:     $txt=~tr/K-T/0-9/;
                   7134:     $txt=~tr/k-t/0-9/;
                   7135:     $txt=~tr/U-Z/0-5/;
                   7136:     $txt=~tr/u-z/0-5/;
                   7137:     $txt=~s/\D//g;
                   7138:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7139:     my $total;
                   7140:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7141:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7142:     return int($total);
                   7143: }
                   7144: 
1.575     albertel 7145: sub numval3 {
                   7146:     use integer;
                   7147:     my $txt=shift;
                   7148:     $txt=~tr/A-J/0-9/;
                   7149:     $txt=~tr/a-j/0-9/;
                   7150:     $txt=~tr/K-T/0-9/;
                   7151:     $txt=~tr/k-t/0-9/;
                   7152:     $txt=~tr/U-Z/0-5/;
                   7153:     $txt=~tr/u-z/0-5/;
                   7154:     $txt=~s/\D//g;
                   7155:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7156:     my $total;
                   7157:     foreach my $val (@txts) { $total+=$val; }
                   7158:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7159:     return $total;
                   7160: }
                   7161: 
1.675     albertel 7162: sub digest {
                   7163:     my ($data)=@_;
                   7164:     my $digest=&Digest::MD5::md5($data);
                   7165:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7166:     my ($e,$f);
                   7167:     {
                   7168:         use integer;
                   7169:         $e=($a+$b);
                   7170:         $f=($c+$d);
                   7171:         if ($_64bit) {
                   7172:             $e=(($e<<32)>>32);
                   7173:             $f=(($f<<32)>>32);
                   7174:         }
                   7175:     }
                   7176:     if (wantarray) {
                   7177: 	return ($e,$f);
                   7178:     } else {
                   7179: 	my $g;
                   7180: 	{
                   7181: 	    use integer;
                   7182: 	    $g=($e+$f);
                   7183: 	    if ($_64bit) {
                   7184: 		$g=(($g<<32)>>32);
                   7185: 	    }
                   7186: 	}
                   7187: 	return $g;
                   7188:     }
                   7189: }
                   7190: 
1.368     albertel 7191: sub latest_rnd_algorithm_id {
1.675     albertel 7192:     return '64bit5';
1.366     albertel 7193: }
1.32      www      7194: 
1.503     albertel 7195: sub get_rand_alg {
                   7196:     my ($courseid)=@_;
1.790     albertel 7197:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7198:     if ($courseid) {
1.620     albertel 7199: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7200:     }
                   7201:     return &latest_rnd_algorithm_id();
                   7202: }
                   7203: 
1.562     albertel 7204: sub validCODE {
                   7205:     my ($CODE)=@_;
                   7206:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7207:     return 0;
                   7208: }
                   7209: 
1.491     albertel 7210: sub getCODE {
1.620     albertel 7211:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7212:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7213: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7214: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7215: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7216:     }
                   7217:     return undef;
                   7218: }
                   7219: 
1.31      www      7220: sub rndseed {
1.155     albertel 7221:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7222:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7223:     if (!defined($symb)) {
1.366     albertel 7224: 	unless ($symb=$wsymb) { return time; }
                   7225:     }
                   7226:     if (!$courseid) { $courseid=$wcourseid; }
                   7227:     if (!$domain) { $domain=$wdomain; }
                   7228:     if (!$username) { $username=$wusername }
1.503     albertel 7229:     my $which=&get_rand_alg();
1.803     albertel 7230: 
1.491     albertel 7231:     if (defined(&getCODE())) {
1.675     albertel 7232: 	if ($which eq '64bit5') {
                   7233: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7234: 	} elsif ($which eq '64bit4') {
1.575     albertel 7235: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7236: 	} else {
                   7237: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7238: 	}
1.675     albertel 7239:     } elsif ($which eq '64bit5') {
                   7240: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7241:     } elsif ($which eq '64bit4') {
                   7242: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7243:     } elsif ($which eq '64bit3') {
                   7244: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7245:     } elsif ($which eq '64bit2') {
                   7246: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7247:     } elsif ($which eq '64bit') {
                   7248: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7249:     }
                   7250:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7251: }
                   7252: 
                   7253: sub rndseed_32bit {
                   7254:     my ($symb,$courseid,$domain,$username)=@_;
                   7255:     {
                   7256: 	use integer;
                   7257: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7258: 	my $symbseed=numval($symb) << 22;
                   7259: 	my $namechck=unpack("%32C*",$username) << 17;
                   7260: 	my $nameseed=numval($username) << 12;
                   7261: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7262: 	my $courseseed=unpack("%32C*",$courseid);
                   7263: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7264: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7265: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7266: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7267: 	return $num;
                   7268:     }
                   7269: }
                   7270: 
                   7271: sub rndseed_64bit {
                   7272:     my ($symb,$courseid,$domain,$username)=@_;
                   7273:     {
                   7274: 	use integer;
                   7275: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7276: 	my $symbseed=numval($symb) << 10;
                   7277: 	my $namechck=unpack("%32S*",$username);
                   7278: 	
                   7279: 	my $nameseed=numval($username) << 21;
                   7280: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7281: 	my $courseseed=unpack("%32S*",$courseid);
                   7282: 	
                   7283: 	my $num1=$symbchck+$symbseed+$namechck;
                   7284: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7285: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7286: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7287: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7288: 	return "$num1,$num2";
1.155     albertel 7289:     }
1.366     albertel 7290: }
                   7291: 
1.443     albertel 7292: sub rndseed_64bit2 {
                   7293:     my ($symb,$courseid,$domain,$username)=@_;
                   7294:     {
                   7295: 	use integer;
                   7296: 	# strings need to be an even # of cahracters long, it it is odd the
                   7297:         # last characters gets thrown away
                   7298: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7299: 	my $symbseed=numval($symb) << 10;
                   7300: 	my $namechck=unpack("%32S*",$username.' ');
                   7301: 	
                   7302: 	my $nameseed=numval($username) << 21;
1.501     albertel 7303: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7304: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7305: 	
                   7306: 	my $num1=$symbchck+$symbseed+$namechck;
                   7307: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7308: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7309: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7310: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7311: 	return "$num1,$num2";
                   7312:     }
                   7313: }
                   7314: 
                   7315: sub rndseed_64bit3 {
                   7316:     my ($symb,$courseid,$domain,$username)=@_;
                   7317:     {
                   7318: 	use integer;
                   7319: 	# strings need to be an even # of cahracters long, it it is odd the
                   7320:         # last characters gets thrown away
                   7321: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7322: 	my $symbseed=numval2($symb) << 10;
                   7323: 	my $namechck=unpack("%32S*",$username.' ');
                   7324: 	
                   7325: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7326: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7327: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7328: 	
                   7329: 	my $num1=$symbchck+$symbseed+$namechck;
                   7330: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7331: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7332: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7333: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7334: 	
1.503     albertel 7335: 	return "$num1:$num2";
1.443     albertel 7336:     }
                   7337: }
                   7338: 
1.575     albertel 7339: sub rndseed_64bit4 {
                   7340:     my ($symb,$courseid,$domain,$username)=@_;
                   7341:     {
                   7342: 	use integer;
                   7343: 	# strings need to be an even # of cahracters long, it it is odd the
                   7344:         # last characters gets thrown away
                   7345: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7346: 	my $symbseed=numval3($symb) << 10;
                   7347: 	my $namechck=unpack("%32S*",$username.' ');
                   7348: 	
                   7349: 	my $nameseed=numval3($username) << 21;
                   7350: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7351: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7352: 	
                   7353: 	my $num1=$symbchck+$symbseed+$namechck;
                   7354: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7355: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7356: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7357: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7358: 	
                   7359: 	return "$num1:$num2";
                   7360:     }
                   7361: }
                   7362: 
1.675     albertel 7363: sub rndseed_64bit5 {
                   7364:     my ($symb,$courseid,$domain,$username)=@_;
                   7365:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7366:     return "$num1:$num2";
                   7367: }
                   7368: 
1.366     albertel 7369: sub rndseed_CODE_64bit {
                   7370:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7371:     {
1.366     albertel 7372: 	use integer;
1.443     albertel 7373: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7374: 	my $symbseed=numval2($symb);
1.491     albertel 7375: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7376: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7377: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7378: 	my $num1=$symbseed+$CODEchck;
                   7379: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7380: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7381: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7382: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7383: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7384: 	return "$num1:$num2";
1.366     albertel 7385:     }
                   7386: }
                   7387: 
1.575     albertel 7388: sub rndseed_CODE_64bit4 {
                   7389:     my ($symb,$courseid,$domain,$username)=@_;
                   7390:     {
                   7391: 	use integer;
                   7392: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7393: 	my $symbseed=numval3($symb);
                   7394: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7395: 	my $CODEseed=numval3(&getCODE());
                   7396: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7397: 	my $num1=$symbseed+$CODEchck;
                   7398: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7399: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7400: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7401: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7402: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7403: 	return "$num1:$num2";
                   7404:     }
                   7405: }
                   7406: 
1.675     albertel 7407: sub rndseed_CODE_64bit5 {
                   7408:     my ($symb,$courseid,$domain,$username)=@_;
                   7409:     my $code = &getCODE();
                   7410:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7411:     return "$num1:$num2";
                   7412: }
                   7413: 
1.366     albertel 7414: sub setup_random_from_rndseed {
                   7415:     my ($rndseed)=@_;
1.503     albertel 7416:     if ($rndseed =~/([,:])/) {
                   7417: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7418: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7419:     } else {
                   7420: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7421:     }
1.36      albertel 7422: }
                   7423: 
1.474     albertel 7424: sub latest_receipt_algorithm_id {
1.835     albertel 7425:     return 'receipt3';
1.474     albertel 7426: }
                   7427: 
1.480     www      7428: sub recunique {
                   7429:     my $fucourseid=shift;
                   7430:     my $unique;
1.835     albertel 7431:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7432: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7433: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7434:     } else {
                   7435: 	$unique=$perlvar{'lonReceipt'};
                   7436:     }
                   7437:     return unpack("%32C*",$unique);
                   7438: }
                   7439: 
                   7440: sub recprefix {
                   7441:     my $fucourseid=shift;
                   7442:     my $prefix;
1.835     albertel 7443:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7444: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7445: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7446:     } else {
                   7447: 	$prefix=$perlvar{'lonHostID'};
                   7448:     }
                   7449:     return unpack("%32C*",$prefix);
                   7450: }
                   7451: 
1.76      www      7452: sub ireceipt {
1.474     albertel 7453:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7454: 
                   7455:     my $return =&recprefix($fucourseid).'-';
                   7456: 
                   7457:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7458: 	$env{'request.state'} eq 'construct') {
                   7459: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7460: 	return $return;
                   7461:     }
                   7462: 
1.76      www      7463:     my $cuname=unpack("%32C*",$funame);
                   7464:     my $cudom=unpack("%32C*",$fudom);
                   7465:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7466:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7467:     my $cunique=&recunique($fucourseid);
1.474     albertel 7468:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7469:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7470: 
1.790     albertel 7471: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7472: 			       
                   7473: 	$return.= ($cunique%$cuname+
                   7474: 		   $cunique%$cudom+
                   7475: 		   $cusymb%$cuname+
                   7476: 		   $cusymb%$cudom+
                   7477: 		   $cucourseid%$cuname+
                   7478: 		   $cucourseid%$cudom+
                   7479: 		   $cpart%$cuname+
                   7480: 		   $cpart%$cudom);
                   7481:     } else {
                   7482: 	$return.= ($cunique%$cuname+
                   7483: 		   $cunique%$cudom+
                   7484: 		   $cusymb%$cuname+
                   7485: 		   $cusymb%$cudom+
                   7486: 		   $cucourseid%$cuname+
                   7487: 		   $cucourseid%$cudom);
                   7488:     }
                   7489:     return $return;
1.76      www      7490: }
                   7491: 
                   7492: sub receipt {
1.474     albertel 7493:     my ($part)=@_;
1.790     albertel 7494:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7495:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7496: }
1.260     ng       7497: 
1.790     albertel 7498: sub whichuser {
                   7499:     my ($passedsymb)=@_;
                   7500:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7501:     if (defined($env{'form.grade_symb'})) {
                   7502: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7503: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7504: 	if (!$allowed &&
                   7505: 	    exists($env{'request.course.sec'}) &&
                   7506: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7507: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7508: 			      '/'.$env{'request.course.sec'});
                   7509: 	}
                   7510: 	if ($allowed) {
                   7511: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7512: 	    $courseid=$tmp_courseid;
                   7513: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7514: 	    ($name)=&get_env_multiple('form.grade_username');
                   7515: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7516: 	}
                   7517:     }
                   7518:     if (!$passedsymb) {
                   7519: 	$symb=&symbread();
                   7520:     } else {
                   7521: 	$symb=$passedsymb;
                   7522:     }
                   7523:     $courseid=$env{'request.course.id'};
                   7524:     $domain=$env{'user.domain'};
                   7525:     $name=$env{'user.name'};
                   7526:     if ($name eq 'public' && $domain eq 'public') {
                   7527: 	if (!defined($env{'form.username'})) {
                   7528: 	    $env{'form.username'}.=time.rand(10000000);
                   7529: 	}
                   7530: 	$name.=$env{'form.username'};
                   7531:     }
                   7532:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7533: 
                   7534: }
                   7535: 
1.36      albertel 7536: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7537: # returns either the contents of the file or 
                   7538: # -1 if the file doesn't exist
1.481     raeburn  7539: #
                   7540: # if the target is a file that was uploaded via DOCS, 
                   7541: # a check will be made to see if a current copy exists on the local server,
                   7542: # if it does this will be served, otherwise a copy will be retrieved from
                   7543: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7544: # the local server.   
1.472     albertel 7545: 
1.36      albertel 7546: sub getfile {
1.538     albertel 7547:     my ($file) = @_;
1.609     banghart 7548:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7549:     &repcopy($file);
                   7550:     return &readfile($file);
                   7551: }
                   7552: 
                   7553: sub repcopy_userfile {
                   7554:     my ($file)=@_;
1.609     banghart 7555:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7556:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7557:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7558: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7559:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7560:     if (-e "$file") {
1.828     www      7561: # we already have a local copy, check it out
1.538     albertel 7562: 	my @fileinfo = stat($file);
1.828     www      7563: 	my $rtncode;
                   7564: 	my $info;
1.538     albertel 7565: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7566: 	if ($lwpresp ne 'ok') {
1.828     www      7567: # there is no such file anymore, even though we had a local copy
1.482     albertel 7568: 	    if ($rtncode eq '404') {
1.538     albertel 7569: 		unlink($file);
1.482     albertel 7570: 	    }
                   7571: 	    return -1;
                   7572: 	}
                   7573: 	if ($info < $fileinfo[9]) {
1.828     www      7574: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7575: 	    return 'ok';
1.828     www      7576: 	} else {
                   7577: # the file is outdated, get rid of it
                   7578: 	    unlink($file);
1.482     albertel 7579: 	}
1.828     www      7580:     }
                   7581: # one way or the other, at this point, we don't have the file
                   7582: # construct the correct path for the file
                   7583:     my @parts = ($cdom,$cnum); 
                   7584:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7585: 	push @parts, split(/\//,$1);
                   7586:     }
                   7587:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7588:     foreach my $part (@parts) {
                   7589: 	$path .= '/'.$part;
                   7590: 	if (!-e $path) {
                   7591: 	    mkdir($path,0770);
1.482     albertel 7592: 	}
                   7593:     }
1.828     www      7594: # now the path exists for sure
                   7595: # get a user agent
                   7596:     my $ua=new LWP::UserAgent;
                   7597:     my $transferfile=$file.'.in.transfer';
                   7598: # FIXME: this should flock
                   7599:     if (-e $transferfile) { return 'ok'; }
                   7600:     my $request;
                   7601:     $uri=~s/^\///;
1.838     albertel 7602:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7603:     my $response=$ua->request($request,$transferfile);
                   7604: # did it work?
                   7605:     if ($response->is_error()) {
                   7606: 	unlink($transferfile);
                   7607: 	&logthis("Userfile repcopy failed for $uri");
                   7608: 	return -1;
                   7609:     }
                   7610: # worked, rename the transfer file
                   7611:     rename($transferfile,$file);
1.607     raeburn  7612:     return 'ok';
1.481     raeburn  7613: }
                   7614: 
1.517     albertel 7615: sub tokenwrapper {
                   7616:     my $uri=shift;
1.552     albertel 7617:     $uri=~s|^http\://([^/]+)||;
                   7618:     $uri=~s|^/||;
1.620     albertel 7619:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7620:     my $token=$1;
1.552     albertel 7621:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7622:     if ($udom && $uname && $file) {
                   7623: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7624:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7625:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7626:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7627:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7628:     } else {
                   7629:         return '/adm/notfound.html';
                   7630:     }
                   7631: }
                   7632: 
1.828     www      7633: # call with reqtype HEAD: get last modification time
                   7634: # call with reqtype GET: get the file contents
                   7635: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7636: #
1.481     raeburn  7637: sub getuploaded {
                   7638:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7639:     $uri=~s/^\///;
1.838     albertel 7640:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7641:     my $ua=new LWP::UserAgent;
                   7642:     my $request=new HTTP::Request($reqtype,$uri);
                   7643:     my $response=$ua->request($request);
                   7644:     $$rtncode = $response->code;
1.482     albertel 7645:     if (! $response->is_success()) {
                   7646: 	return 'failed';
                   7647:     }      
                   7648:     if ($reqtype eq 'HEAD') {
1.486     www      7649: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7650:     } elsif ($reqtype eq 'GET') {
                   7651: 	$$info = $response->content;
1.472     albertel 7652:     }
1.482     albertel 7653:     return 'ok';
1.36      albertel 7654: }
                   7655: 
1.481     raeburn  7656: sub readfile {
                   7657:     my $file = shift;
                   7658:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7659:     my $fh;
                   7660:     open($fh,"<$file");
                   7661:     my $a='';
1.800     albertel 7662:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7663:     return $a;
                   7664: }
                   7665: 
1.36      albertel 7666: sub filelocation {
1.590     banghart 7667:     my ($dir,$file) = @_;
                   7668:     my $location;
                   7669:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7670: 
                   7671:     if ($file =~ m-^/adm/-) {
                   7672: 	$file=~s-^/adm/wrapper/-/-;
                   7673: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7674:     }
1.882     albertel 7675: 
1.590     banghart 7676:     if ($file=~m:^/~:) { # is a contruction space reference
                   7677:         $location = $file;
                   7678:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7679:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7680: 	# is a correct contruction space reference
                   7681:         $location = $file;
1.609     banghart 7682:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7683:         my ($udom,$uname,$filename)=
1.811     albertel 7684:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7685:         my $home=&homeserver($uname,$udom);
                   7686:         my $is_me=0;
                   7687:         my @ids=&current_machine_ids();
                   7688:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7689:         if ($is_me) {
1.740     www      7690:   	    $location=&propath($udom,$uname).
1.590     banghart 7691:   	      '/userfiles/'.$filename;
                   7692:         } else {
                   7693:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7694:   	      $udom.'/'.$uname.'/'.$filename;
                   7695:         }
1.882     albertel 7696:     } elsif ($file =~ m-^/adm/-) {
                   7697: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7698:     } else {
                   7699:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7700:         $file=~s:^/res/:/:;
                   7701:         if ( !( $file =~ m:^/:) ) {
                   7702:             $location = $dir. '/'.$file;
                   7703:         } else {
                   7704:             $location = '/home/httpd/html/res'.$file;
                   7705:         }
1.59      albertel 7706:     }
1.590     banghart 7707:     $location=~s://+:/:g; # remove duplicate /
                   7708:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7709:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7710:     return $location;
1.46      www      7711: }
1.36      albertel 7712: 
1.46      www      7713: sub hreflocation {
                   7714:     my ($dir,$file)=@_;
1.460     albertel 7715:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7716: 	$file=filelocation($dir,$file);
1.700     albertel 7717:     } elsif ($file=~m-^/adm/-) {
                   7718: 	$file=~s-^/adm/wrapper/-/-;
                   7719: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7720:     }
                   7721:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7722: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7723:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7724: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7725:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7726: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7727: 	    -/uploaded/$1/$2/-x;
1.46      www      7728:     }
1.462     albertel 7729:     return $file;
1.465     albertel 7730: }
                   7731: 
                   7732: sub current_machine_domains {
1.853     albertel 7733:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7734: }
                   7735: 
                   7736: sub machine_domains {
                   7737:     my ($hostname) = @_;
1.465     albertel 7738:     my @domains;
1.838     albertel 7739:     my %hostname = &all_hostnames();
1.465     albertel 7740:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7741: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7742: 	if ($hostname eq $name) {
1.844     albertel 7743: 	    push(@domains,&host_domain($id));
1.465     albertel 7744: 	}
                   7745:     }
                   7746:     return @domains;
                   7747: }
                   7748: 
                   7749: sub current_machine_ids {
1.853     albertel 7750:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7751: }
                   7752: 
                   7753: sub machine_ids {
                   7754:     my ($hostname) = @_;
                   7755:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7756:     my @ids;
1.888     albertel 7757:     my %name_to_host = &all_names();
1.889     albertel 7758:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7759: 	return @{ $name_to_host{$hostname} };
                   7760:     }
                   7761:     return;
1.31      www      7762: }
                   7763: 
1.824     raeburn  7764: sub additional_machine_domains {
                   7765:     my @domains;
                   7766:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7767:     while( my $line = <$fh>) {
                   7768:         $line =~ s/\s//g;
                   7769:         push(@domains,$line);
                   7770:     }
                   7771:     return @domains;
                   7772: }
                   7773: 
                   7774: sub default_login_domain {
                   7775:     my $domain = $perlvar{'lonDefDomain'};
                   7776:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7777:     foreach my $posdom (&current_machine_domains(),
                   7778:                         &additional_machine_domains()) {
                   7779:         if (lc($posdom) eq lc($testdomain)) {
                   7780:             $domain=$posdom;
                   7781:             last;
                   7782:         }
                   7783:     }
                   7784:     return $domain;
                   7785: }
                   7786: 
1.31      www      7787: # ------------------------------------------------------------- Declutters URLs
                   7788: 
                   7789: sub declutter {
                   7790:     my $thisfn=shift;
1.569     albertel 7791:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7792:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7793:     $thisfn=~s/^\///;
1.697     albertel 7794:     $thisfn=~s|^adm/wrapper/||;
                   7795:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7796:     $thisfn=~s/^res\///;
1.235     www      7797:     $thisfn=~s/\?.+$//;
1.268     www      7798:     return $thisfn;
                   7799: }
                   7800: 
                   7801: # ------------------------------------------------------------- Clutter up URLs
                   7802: 
                   7803: sub clutter {
                   7804:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7805:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7806: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7807:        $thisfn='/res'.$thisfn; 
                   7808:     }
1.694     albertel 7809:     if ($thisfn !~m|/adm|) {
1.695     albertel 7810: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7811: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7812: 	} else {
                   7813: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7814: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7815: 	    if ($embstyle eq 'ssi'
                   7816: 		|| ($embstyle eq 'hdn')
                   7817: 		|| ($embstyle eq 'rat')
                   7818: 		|| ($embstyle eq 'prv')
                   7819: 		|| ($embstyle eq 'ign')) {
                   7820: 		#do nothing with these
                   7821: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7822: 		|| ($embstyle eq 'emb')
                   7823: 		|| ($embstyle eq 'wrp')) {
                   7824: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7825: 	    } elsif ($embstyle eq 'unk'
                   7826: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7827: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7828: 	    } else {
1.718     www      7829: #		&logthis("Got a blank emb style");
1.695     albertel 7830: 	    }
1.694     albertel 7831: 	}
                   7832:     }
1.31      www      7833:     return $thisfn;
1.12      www      7834: }
                   7835: 
1.787     albertel 7836: sub clutter_with_no_wrapper {
                   7837:     my $uri = &clutter(shift);
                   7838:     if ($uri =~ m-^/adm/-) {
                   7839: 	$uri =~ s-^/adm/wrapper/-/-;
                   7840: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7841:     }
                   7842:     return $uri;
                   7843: }
                   7844: 
1.557     albertel 7845: sub freeze_escape {
                   7846:     my ($value)=@_;
                   7847:     if (ref($value)) {
                   7848: 	$value=&nfreeze($value);
                   7849: 	return '__FROZEN__'.&escape($value);
                   7850:     }
                   7851:     return &escape($value);
                   7852: }
                   7853: 
1.11      www      7854: 
1.557     albertel 7855: sub thaw_unescape {
                   7856:     my ($value)=@_;
                   7857:     if ($value =~ /^__FROZEN__/) {
                   7858: 	substr($value,0,10,undef);
                   7859: 	$value=&unescape($value);
                   7860: 	return &thaw($value);
                   7861:     }
                   7862:     return &unescape($value);
                   7863: }
                   7864: 
1.436     albertel 7865: sub correct_line_ends {
                   7866:     my ($result)=@_;
                   7867:     $$result =~s/\r\n/\n/mg;
                   7868:     $$result =~s/\r/\n/mg;
1.415     albertel 7869: }
1.1       albertel 7870: # ================================================================ Main Program
                   7871: 
1.184     www      7872: sub goodbye {
1.204     albertel 7873:    &logthis("Starting Shut down");
1.443     albertel 7874: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7875:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7876: #converted
1.599     albertel 7877: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7878:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7879: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7880: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7881: #1.1 only
1.870     albertel 7882: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7883: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7884: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7885: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7886:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7887:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7888:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7889:    &flushcourselogs();
                   7890:    &logthis("Shutting down");
                   7891: }
                   7892: 
1.852     albertel 7893: sub get_dns {
1.869     albertel 7894:     my ($url,$func,$ignore_cache) = @_;
                   7895:     if (!$ignore_cache) {
                   7896: 	my ($content,$cached)=
                   7897: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7898: 	if ($cached) {
                   7899: 	    &$func($content);
                   7900: 	    return;
                   7901: 	}
                   7902:     }
                   7903: 
                   7904:     my %alldns;
1.852     albertel 7905:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7906:     foreach my $dns (<$config>) {
                   7907: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7908: 	$alldns{$1} = 1;
                   7909:     }
                   7910:     while (%alldns) {
                   7911: 	my ($dns) = keys(%alldns);
                   7912: 	delete($alldns{$dns});
1.852     albertel 7913: 	my $ua=new LWP::UserAgent;
                   7914: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7915: 	my $response=$ua->request($request);
                   7916: 	next if ($response->is_error());
                   7917: 	my @content = split("\n",$response->content);
1.869     albertel 7918: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7919: 	&$func(\@content);
1.869     albertel 7920: 	return;
1.852     albertel 7921:     }
                   7922:     close($config);
1.871     albertel 7923:     my $which = (split('/',$url))[3];
                   7924:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7925:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7926:     my @content = <$config>;
                   7927:     &$func(\@content);
                   7928:     return;
1.852     albertel 7929: }
1.327     albertel 7930: # ------------------------------------------------------------ Read domain file
                   7931: {
1.852     albertel 7932:     my $loaded;
1.846     albertel 7933:     my %domain;
                   7934: 
1.852     albertel 7935:     sub parse_domain_tab {
                   7936: 	my ($lines) = @_;
                   7937: 	foreach my $line (@$lines) {
                   7938: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7939: 
1.846     albertel 7940: 	    chomp($line);
1.852     albertel 7941: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7942: 	    my %this_domain;
                   7943: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7944: 			       'lang_def', 'city', 'longi', 'lati',
                   7945: 			       'primary') {
                   7946: 		$this_domain{$field} = shift(@elements);
                   7947: 	    }
                   7948: 	    $domain{$name} = \%this_domain;
1.852     albertel 7949: 	}
                   7950:     }
1.864     albertel 7951: 
                   7952:     sub reset_domain_info {
                   7953: 	undef($loaded);
                   7954: 	undef(%domain);
                   7955:     }
                   7956: 
1.852     albertel 7957:     sub load_domain_tab {
1.869     albertel 7958: 	my ($ignore_cache) = @_;
                   7959: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7960: 	my $fh;
                   7961: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7962: 	    my @lines = <$fh>;
                   7963: 	    &parse_domain_tab(\@lines);
1.448     albertel 7964: 	}
1.852     albertel 7965: 	close($fh);
                   7966: 	$loaded = 1;
1.327     albertel 7967:     }
1.846     albertel 7968: 
                   7969:     sub domain {
1.852     albertel 7970: 	&load_domain_tab() if (!$loaded);
                   7971: 
1.846     albertel 7972: 	my ($name,$what) = @_;
                   7973: 	return if ( !exists($domain{$name}) );
                   7974: 
                   7975: 	if (!$what) {
                   7976: 	    return $domain{$name}{'description'};
                   7977: 	}
                   7978: 	return $domain{$name}{$what};
                   7979:     }
1.327     albertel 7980: }
                   7981: 
                   7982: 
1.1       albertel 7983: # ------------------------------------------------------------- Read hosts file
                   7984: {
1.838     albertel 7985:     my %hostname;
1.844     albertel 7986:     my %hostdom;
1.845     albertel 7987:     my %libserv;
1.852     albertel 7988:     my $loaded;
1.888     albertel 7989:     my %name_to_host;
1.852     albertel 7990: 
                   7991:     sub parse_hosts_tab {
                   7992: 	my ($file) = @_;
                   7993: 	foreach my $configline (@$file) {
                   7994: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7995: 	    next if ($configline =~ /^\^/);
                   7996: 	    chomp($configline);
                   7997: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7998: 	    $name=~s/\s//g;
                   7999: 	    if ($id && $domain && $role && $name) {
                   8000: 		$hostname{$id}=$name;
1.888     albertel 8001: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8002: 		$hostdom{$id}=$domain;
                   8003: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8004: 	    }
                   8005: 	}
                   8006:     }
1.864     albertel 8007:     
                   8008:     sub reset_hosts_info {
1.897     albertel 8009: 	&purge_remembered();
1.864     albertel 8010: 	&reset_domain_info();
                   8011: 	&reset_hosts_ip_info();
1.892     albertel 8012: 	undef(%name_to_host);
1.864     albertel 8013: 	undef(%hostname);
                   8014: 	undef(%hostdom);
                   8015: 	undef(%libserv);
                   8016: 	undef($loaded);
                   8017:     }
1.1       albertel 8018: 
1.852     albertel 8019:     sub load_hosts_tab {
1.869     albertel 8020: 	my ($ignore_cache) = @_;
                   8021: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8022: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8023: 	my @config = <$config>;
                   8024: 	&parse_hosts_tab(\@config);
                   8025: 	close($config);
                   8026: 	$loaded=1;
1.1       albertel 8027:     }
1.852     albertel 8028: 
1.838     albertel 8029:     sub hostname {
1.852     albertel 8030: 	&load_hosts_tab() if (!$loaded);
                   8031: 
1.838     albertel 8032: 	my ($lonid) = @_;
                   8033: 	return $hostname{$lonid};
                   8034:     }
1.845     albertel 8035: 
1.838     albertel 8036:     sub all_hostnames {
1.852     albertel 8037: 	&load_hosts_tab() if (!$loaded);
                   8038: 
1.838     albertel 8039: 	return %hostname;
                   8040:     }
1.845     albertel 8041: 
1.888     albertel 8042:     sub all_names {
                   8043: 	&load_hosts_tab() if (!$loaded);
                   8044: 
                   8045: 	return %name_to_host;
                   8046:     }
                   8047: 
1.845     albertel 8048:     sub is_library {
1.852     albertel 8049: 	&load_hosts_tab() if (!$loaded);
                   8050: 
1.845     albertel 8051: 	return exists($libserv{$_[0]});
                   8052:     }
                   8053: 
                   8054:     sub all_library {
1.852     albertel 8055: 	&load_hosts_tab() if (!$loaded);
                   8056: 
1.845     albertel 8057: 	return %libserv;
                   8058:     }
                   8059: 
1.841     albertel 8060:     sub get_servers {
1.852     albertel 8061: 	&load_hosts_tab() if (!$loaded);
                   8062: 
1.841     albertel 8063: 	my ($domain,$type) = @_;
                   8064: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8065: 	                                          : %hostname;
                   8066: 	my %result;
1.842     albertel 8067: 	if (ref($domain) eq 'ARRAY') {
                   8068: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8069: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8070: 		    $result{$host} = $hostname;
                   8071: 		}
                   8072: 	    }
                   8073: 	} else {
                   8074: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8075: 		if ($hostdom{$host} eq $domain) {
                   8076: 		    $result{$host} = $hostname;
                   8077: 		}
1.841     albertel 8078: 	    }
                   8079: 	}
                   8080: 	return %result;
                   8081:     }
1.845     albertel 8082: 
1.844     albertel 8083:     sub host_domain {
1.852     albertel 8084: 	&load_hosts_tab() if (!$loaded);
                   8085: 
1.844     albertel 8086: 	my ($lonid) = @_;
                   8087: 	return $hostdom{$lonid};
                   8088:     }
                   8089: 
1.841     albertel 8090:     sub all_domains {
1.852     albertel 8091: 	&load_hosts_tab() if (!$loaded);
                   8092: 
1.841     albertel 8093: 	my %seen;
                   8094: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8095: 	return @uniq;
                   8096:     }
1.1       albertel 8097: }
                   8098: 
1.847     albertel 8099: { 
                   8100:     my %iphost;
1.856     albertel 8101:     my %name_to_ip;
                   8102:     my %lonid_to_ip;
1.869     albertel 8103: 
1.847     albertel 8104:     sub get_hosts_from_ip {
                   8105: 	my ($ip) = @_;
                   8106: 	my %iphosts = &get_iphost();
                   8107: 	if (ref($iphosts{$ip})) {
                   8108: 	    return @{$iphosts{$ip}};
                   8109: 	}
                   8110: 	return;
1.839     albertel 8111:     }
1.864     albertel 8112:     
                   8113:     sub reset_hosts_ip_info {
                   8114: 	undef(%iphost);
                   8115: 	undef(%name_to_ip);
                   8116: 	undef(%lonid_to_ip);
                   8117:     }
1.856     albertel 8118: 
                   8119:     sub get_host_ip {
                   8120: 	my ($lonid) = @_;
                   8121: 	if (exists($lonid_to_ip{$lonid})) {
                   8122: 	    return $lonid_to_ip{$lonid};
                   8123: 	}
                   8124: 	my $name=&hostname($lonid);
                   8125:    	my $ip = gethostbyname($name);
                   8126: 	return if (!$ip || length($ip) ne 4);
                   8127: 	$ip=inet_ntoa($ip);
                   8128: 	$name_to_ip{$name}   = $ip;
                   8129: 	$lonid_to_ip{$lonid} = $ip;
                   8130: 	return $ip;
                   8131:     }
1.847     albertel 8132:     
                   8133:     sub get_iphost {
1.869     albertel 8134: 	my ($ignore_cache) = @_;
1.894     albertel 8135: 
1.869     albertel 8136: 	if (!$ignore_cache) {
                   8137: 	    if (%iphost) {
                   8138: 		return %iphost;
                   8139: 	    }
                   8140: 	    my ($ip_info,$cached)=
                   8141: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8142: 	    if ($cached) {
                   8143: 		%iphost      = %{$ip_info->[0]};
                   8144: 		%name_to_ip  = %{$ip_info->[1]};
                   8145: 		%lonid_to_ip = %{$ip_info->[2]};
                   8146: 		return %iphost;
                   8147: 	    }
                   8148: 	}
1.894     albertel 8149: 
                   8150: 	# get yesterday's info for fallback
                   8151: 	my %old_name_to_ip;
                   8152: 	my ($ip_info,$cached)=
                   8153: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8154: 	if ($cached) {
                   8155: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8156: 	}
                   8157: 
1.888     albertel 8158: 	my %name_to_host = &all_names();
                   8159: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8160: 	    my $ip;
                   8161: 	    if (!exists($name_to_ip{$name})) {
                   8162: 		$ip = gethostbyname($name);
                   8163: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8164: 		    if (defined($old_name_to_ip{$name})) {
                   8165: 			$ip = $old_name_to_ip{$name};
                   8166: 			&logthis("Can't find $name defaulting to old $ip");
                   8167: 		    } else {
                   8168: 			&logthis("Name $name no IP found");
                   8169: 			next;
                   8170: 		    }
                   8171: 		} else {
                   8172: 		    $ip=inet_ntoa($ip);
1.847     albertel 8173: 		}
                   8174: 		$name_to_ip{$name} = $ip;
                   8175: 	    } else {
                   8176: 		$ip = $name_to_ip{$name};
1.653     albertel 8177: 	    }
1.888     albertel 8178: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8179: 		$lonid_to_ip{$id} = $ip;
                   8180: 	    }
                   8181: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8182: 	}
1.869     albertel 8183: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8184: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8185: 				      48*60*60);
1.869     albertel 8186: 
1.847     albertel 8187: 	return %iphost;
1.598     albertel 8188:     }
                   8189: }
                   8190: 
1.862     albertel 8191: BEGIN {
                   8192: 
                   8193: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8194:     unless ($readit) {
                   8195: {
                   8196:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8197:     %perlvar = (%perlvar,%{$configvars});
                   8198: }
                   8199: 
                   8200: 
1.1       albertel 8201: # ------------------------------------------------------ Read spare server file
                   8202: {
1.448     albertel 8203:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8204: 
                   8205:     while (my $configline=<$config>) {
                   8206:        chomp($configline);
1.284     matthew  8207:        if ($configline) {
1.784     albertel 8208: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8209: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8210: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8211:        }
                   8212:     }
1.448     albertel 8213:     close($config);
1.1       albertel 8214: }
1.11      www      8215: # ------------------------------------------------------------ Read permissions
                   8216: {
1.448     albertel 8217:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8218: 
                   8219:     while (my $configline=<$config>) {
1.448     albertel 8220: 	chomp($configline);
                   8221: 	if ($configline) {
                   8222: 	    my ($role,$perm)=split(/ /,$configline);
                   8223: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8224: 	}
1.11      www      8225:     }
1.448     albertel 8226:     close($config);
1.11      www      8227: }
                   8228: 
                   8229: # -------------------------------------------- Read plain texts for permissions
                   8230: {
1.448     albertel 8231:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8232: 
                   8233:     while (my $configline=<$config>) {
1.448     albertel 8234: 	chomp($configline);
                   8235: 	if ($configline) {
1.742     raeburn  8236: 	    my ($short,@plain)=split(/:/,$configline);
                   8237:             %{$prp{$short}} = ();
                   8238: 	    if (@plain > 0) {
                   8239:                 $prp{$short}{'std'} = $plain[0];
                   8240:                 for (my $i=1; $i<@plain; $i++) {
                   8241:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8242:                 }
                   8243:             }
1.448     albertel 8244: 	}
1.135     www      8245:     }
1.448     albertel 8246:     close($config);
1.135     www      8247: }
                   8248: 
                   8249: # ---------------------------------------------------------- Read package table
                   8250: {
1.448     albertel 8251:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8252: 
                   8253:     while (my $configline=<$config>) {
1.483     albertel 8254: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8255: 	chomp($configline);
                   8256: 	my ($short,$plain)=split(/:/,$configline);
                   8257: 	my ($pack,$name)=split(/\&/,$short);
                   8258: 	if ($plain ne '') {
                   8259: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8260: 	    $packagetab{$short}=$plain; 
                   8261: 	}
1.11      www      8262:     }
1.448     albertel 8263:     close($config);
1.329     matthew  8264: }
                   8265: 
                   8266: # ------------- set up temporary directory
                   8267: {
                   8268:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8269: 
1.11      www      8270: }
                   8271: 
1.794     albertel 8272: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8273: 				'compress_threshold'=> 20_000,
                   8274:  			        });
1.185     www      8275: 
1.281     www      8276: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8277: $dumpcount=0;
1.22      www      8278: 
1.163     harris41 8279: &logtouch();
1.672     albertel 8280: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8281: $readit=1;
1.564     albertel 8282:     {
                   8283: 	use integer;
                   8284: 	my $test=(2**32)+1;
1.568     albertel 8285: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8286: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8287:     }
1.195     www      8288: }
1.1       albertel 8289: }
1.179     www      8290: 
1.1       albertel 8291: 1;
1.191     harris41 8292: __END__
                   8293: 
1.243     albertel 8294: =pod
                   8295: 
1.191     harris41 8296: =head1 NAME
                   8297: 
1.243     albertel 8298: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8299: 
                   8300: =head1 SYNOPSIS
                   8301: 
1.243     albertel 8302: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8303: 
                   8304:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8305: 
1.243     albertel 8306: Common parameters:
                   8307: 
                   8308: =over 4
                   8309: 
                   8310: =item *
                   8311: 
                   8312: $uname : an internal username (if $cname expecting a course Id specifically)
                   8313: 
                   8314: =item *
                   8315: 
                   8316: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8317: 
                   8318: =item *
                   8319: 
                   8320: $symb : a resource instance identifier
                   8321: 
                   8322: =item *
                   8323: 
                   8324: $namespace : the name of a .db file that contains the data needed or
                   8325: being set.
                   8326: 
                   8327: =back
                   8328: 
1.394     bowersj2 8329: =head1 OVERVIEW
1.191     harris41 8330: 
1.394     bowersj2 8331: lonnet provides subroutines which interact with the
                   8332: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8333: about classes, users, and resources.
1.243     albertel 8334: 
                   8335: For many of these objects you can also use this to store data about
                   8336: them or modify them in various ways.
1.191     harris41 8337: 
1.394     bowersj2 8338: =head2 Symbs
1.191     harris41 8339: 
1.394     bowersj2 8340: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8341: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8342: map, the resource number of the resource in the map, and the URL of
                   8343: the resource itself. The latter is somewhat redundant, but might help
                   8344: if maps change.
                   8345: 
                   8346: An example is
                   8347: 
                   8348:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8349: 
                   8350: The respective map entry is
                   8351: 
                   8352:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8353:   title="Problem 2">
                   8354:  </resource>
                   8355: 
                   8356: Symbs are used by the random number generator, as well as to store and
                   8357: restore data specific to a certain instance of for example a problem.
                   8358: 
                   8359: =head2 Storing And Retrieving Data
                   8360: 
                   8361: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8362: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8363: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8364: is is the non-critical message twin of cstore. These functions are for
                   8365: handlers to store a perl hash to a user's permanent data space in an
                   8366: easy manner, and to retrieve it again on another call. It is expected
                   8367: that a handler would use this once at the beginning to retrieve data,
                   8368: and then again once at the end to send only the new data back.
                   8369: 
                   8370: The data is stored in the user's data directory on the user's
                   8371: homeserver under the ID of the course.
                   8372: 
                   8373: The hash that is returned by restore will have all of the previous
                   8374: value for all of the elements of the hash.
                   8375: 
                   8376: Example:
                   8377: 
                   8378:  #creating a hash
                   8379:  my %hash;
                   8380:  $hash{'foo'}='bar';
                   8381: 
                   8382:  #storing it
                   8383:  &Apache::lonnet::cstore(\%hash);
                   8384: 
                   8385:  #changing a value
                   8386:  $hash{'foo'}='notbar';
                   8387: 
                   8388:  #adding a new value
                   8389:  $hash{'bar'}='foo';
                   8390:  &Apache::lonnet::cstore(\%hash);
                   8391: 
                   8392:  #retrieving the hash
                   8393:  my %history=&Apache::lonnet::restore();
                   8394: 
                   8395:  #print the hash
                   8396:  foreach my $key (sort(keys(%history))) {
                   8397:    print("\%history{$key} = $history{$key}");
                   8398:  }
                   8399: 
                   8400: Will print out:
1.191     harris41 8401: 
1.394     bowersj2 8402:  %history{1:foo} = bar
                   8403:  %history{1:keys} = foo:timestamp
                   8404:  %history{1:timestamp} = 990455579
                   8405:  %history{2:bar} = foo
                   8406:  %history{2:foo} = notbar
                   8407:  %history{2:keys} = foo:bar:timestamp
                   8408:  %history{2:timestamp} = 990455580
                   8409:  %history{bar} = foo
                   8410:  %history{foo} = notbar
                   8411:  %history{timestamp} = 990455580
                   8412:  %history{version} = 2
                   8413: 
                   8414: Note that the special hash entries C<keys>, C<version> and
                   8415: C<timestamp> were added to the hash. C<version> will be equal to the
                   8416: total number of versions of the data that have been stored. The
                   8417: C<timestamp> attribute will be the UNIX time the hash was
                   8418: stored. C<keys> is available in every historical section to list which
                   8419: keys were added or changed at a specific historical revision of a
                   8420: hash.
                   8421: 
                   8422: B<Warning>: do not store the hash that restore returns directly. This
                   8423: will cause a mess since it will restore the historical keys as if the
                   8424: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8425: 
1.394     bowersj2 8426: Calling convention:
1.191     harris41 8427: 
1.394     bowersj2 8428:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8429:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8430: 
1.394     bowersj2 8431: For more detailed information, see lonnet specific documentation.
1.191     harris41 8432: 
1.394     bowersj2 8433: =head1 RETURN MESSAGES
1.191     harris41 8434: 
1.394     bowersj2 8435: =over 4
1.191     harris41 8436: 
1.394     bowersj2 8437: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8438: 
1.394     bowersj2 8439: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8440: when the connection is brought back up
1.191     harris41 8441: 
1.394     bowersj2 8442: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8443: for later delivery
1.191     harris41 8444: 
1.394     bowersj2 8445: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8446: 
1.394     bowersj2 8447: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8448: that was requested
1.191     harris41 8449: 
1.243     albertel 8450: =back
1.191     harris41 8451: 
1.243     albertel 8452: =head1 PUBLIC SUBROUTINES
1.191     harris41 8453: 
1.243     albertel 8454: =head2 Session Environment Functions
1.191     harris41 8455: 
1.243     albertel 8456: =over 4
1.191     harris41 8457: 
1.394     bowersj2 8458: =item * 
                   8459: X<appenv()>
                   8460: B<appenv(%hash)>: the value of %hash is written to
                   8461: the user envirnoment file, and will be restored for each access this
1.620     albertel 8462: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8463: process
1.191     harris41 8464: 
                   8465: =item *
1.394     bowersj2 8466: X<delenv()>
                   8467: B<delenv($regexp)>: removes all items from the session
                   8468: environment file that matches the regular expression in $regexp. The
1.620     albertel 8469: values are also delted from the current processes %env.
1.191     harris41 8470: 
1.795     albertel 8471: =item * get_env_multiple($name) 
                   8472: 
                   8473: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8474: values may be defined and end up as an array ref.
                   8475: 
                   8476: returns an array of values
                   8477: 
1.243     albertel 8478: =back
                   8479: 
                   8480: =head2 User Information
1.191     harris41 8481: 
1.243     albertel 8482: =over 4
1.191     harris41 8483: 
                   8484: =item *
1.394     bowersj2 8485: X<queryauthenticate()>
                   8486: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8487: authentication scheme
                   8488: 
                   8489: =item *
1.394     bowersj2 8490: X<authenticate()>
                   8491: B<authenticate($uname,$upass,$udom)>: try to
                   8492: authenticate user from domain's lib servers (first use the current
                   8493: one). C<$upass> should be the users password.
1.191     harris41 8494: 
                   8495: =item *
1.394     bowersj2 8496: X<homeserver()>
                   8497: B<homeserver($uname,$udom)>: find the server which has
                   8498: the user's directory and files (there must be only one), this caches
                   8499: the answer, and also caches if there is a borken connection.
1.191     harris41 8500: 
                   8501: =item *
1.394     bowersj2 8502: X<idget()>
                   8503: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8504: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8505: username, and only 1 username per ID in a specific domain) (returns
                   8506: hash: id=>name,id=>name)
1.191     harris41 8507: 
                   8508: =item *
1.394     bowersj2 8509: X<idrget()>
                   8510: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8511: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8512: 
                   8513: =item *
1.394     bowersj2 8514: X<idput()>
                   8515: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8516: 
                   8517: =item *
1.394     bowersj2 8518: X<rolesinit()>
                   8519: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8520: 
                   8521: =item *
1.551     albertel 8522: X<getsection()>
                   8523: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8524: course $cname, return section name/number or '' for "not in course"
                   8525: and '-1' for "no section"
                   8526: 
                   8527: =item *
1.394     bowersj2 8528: X<userenvironment()>
                   8529: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8530: passed in @what from the requested user's environment, returns a hash
                   8531: 
1.858     raeburn  8532: =item * 
                   8533: X<userlog_query()>
1.859     albertel 8534: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8535: activity.log file. %filters defines filters applied when parsing the
                   8536: log file. These can be start or end timestamps, or the type of action
                   8537: - log to look for Login or Logout events, check for Checkin or
                   8538: Checkout, role for role selection. The response is in the form
                   8539: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8540: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8541: 
1.243     albertel 8542: =back
                   8543: 
                   8544: =head2 User Roles
                   8545: 
                   8546: =over 4
                   8547: 
                   8548: =item *
                   8549: 
1.810     raeburn  8550: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8551:  F: full access
                   8552:  U,I,K: authentication modes (cxx only)
                   8553:  '': forbidden
                   8554:  1: user needs to choose course
                   8555:  2: browse allowed
1.766     albertel 8556:  A: passphrase authentication needed
1.243     albertel 8557: 
                   8558: =item *
                   8559: 
                   8560: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8561: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8562: and course level
                   8563: 
                   8564: =item *
                   8565: 
                   8566: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8567: explanation of a user role term
                   8568: 
1.832     raeburn  8569: =item *
                   8570: 
1.858     raeburn  8571: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8572: All arguments are optional. Returns a hash of a roles, either for
                   8573: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8574: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8575: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8576: and value is set to colon-separated start and end times for the role.
                   8577: If no username and domain are specified, will default to current
                   8578: user/domain. Types, roles, and roledoms are references to arrays,
                   8579: of role statuses (active, future or previous), roles 
                   8580: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8581: to restrict the list of roles reported. If no array ref is 
                   8582: provided for types, will default to return only active roles.
1.834     albertel 8583: 
1.243     albertel 8584: =back
                   8585: 
                   8586: =head2 User Modification
                   8587: 
                   8588: =over 4
                   8589: 
                   8590: =item *
                   8591: 
                   8592: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8593: user for the level given by URL.  Optional start and end dates (leave empty
                   8594: string or zero for "no date")
1.191     harris41 8595: 
                   8596: =item *
                   8597: 
1.243     albertel 8598: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8599: change a users, password, possible return values are: ok,
                   8600: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8601: refused
1.191     harris41 8602: 
                   8603: =item *
                   8604: 
1.243     albertel 8605: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8606: 
                   8607: =item *
                   8608: 
1.243     albertel 8609: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8610: modify user
1.191     harris41 8611: 
                   8612: =item *
                   8613: 
1.286     matthew  8614: modifystudent
                   8615: 
                   8616: modify a students enrollment and identification information.
                   8617: The course id is resolved based on the current users environment.  
                   8618: This means the envoking user must be a course coordinator or otherwise
                   8619: associated with a course.
                   8620: 
1.297     matthew  8621: This call is essentially a wrapper for lonnet::modifyuser and
                   8622: lonnet::modify_student_enrollment
1.286     matthew  8623: 
                   8624: Inputs: 
                   8625: 
                   8626: =over 4
                   8627: 
                   8628: =item B<$udom> Students loncapa domain
                   8629: 
                   8630: =item B<$uname> Students loncapa login name
                   8631: 
                   8632: =item B<$uid> Students id/student number
                   8633: 
                   8634: =item B<$umode> Students authentication mode
                   8635: 
                   8636: =item B<$upass> Students password
                   8637: 
                   8638: =item B<$first> Students first name
                   8639: 
                   8640: =item B<$middle> Students middle name
                   8641: 
                   8642: =item B<$last> Students last name
                   8643: 
                   8644: =item B<$gene> Students generation
                   8645: 
                   8646: =item B<$usec> Students section in course
                   8647: 
                   8648: =item B<$end> Unix time of the roles expiration
                   8649: 
                   8650: =item B<$start> Unix time of the roles start date
                   8651: 
                   8652: =item B<$forceid> If defined, allow $uid to be changed
                   8653: 
                   8654: =item B<$desiredhome> server to use as home server for student
                   8655: 
                   8656: =back
1.297     matthew  8657: 
                   8658: =item *
                   8659: 
                   8660: modify_student_enrollment
                   8661: 
                   8662: Change a students enrollment status in a class.  The environment variable
                   8663: 'role.request.course' must be defined for this function to proceed.
                   8664: 
                   8665: Inputs:
                   8666: 
                   8667: =over 4
                   8668: 
                   8669: =item $udom, students domain
                   8670: 
                   8671: =item $uname, students name
                   8672: 
                   8673: =item $uid, students user id
                   8674: 
                   8675: =item $first, students first name
                   8676: 
                   8677: =item $middle
                   8678: 
                   8679: =item $last
                   8680: 
                   8681: =item $gene
                   8682: 
                   8683: =item $usec
                   8684: 
                   8685: =item $end
                   8686: 
                   8687: =item $start
                   8688: 
                   8689: =back
                   8690: 
1.191     harris41 8691: 
                   8692: =item *
                   8693: 
1.243     albertel 8694: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8695: custom role; give a custom role to a user for the level given by URL.  Specify
                   8696: name and domain of role author, and role name
1.191     harris41 8697: 
                   8698: =item *
                   8699: 
1.243     albertel 8700: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8701: 
                   8702: =item *
                   8703: 
1.243     albertel 8704: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8705: 
                   8706: =back
                   8707: 
                   8708: =head2 Course Infomation
                   8709: 
                   8710: =over 4
1.191     harris41 8711: 
                   8712: =item *
                   8713: 
1.631     albertel 8714: coursedescription($courseid) : returns a hash of information about the
                   8715: specified course id, including all environment settings for the
                   8716: course, the description of the course will be in the hash under the
                   8717: key 'description'
1.191     harris41 8718: 
                   8719: =item *
                   8720: 
1.624     albertel 8721: resdata($name,$domain,$type,@which) : request for current parameter
                   8722: setting for a specific $type, where $type is either 'course' or 'user',
                   8723: @what should be a list of parameters to ask about. This routine caches
                   8724: answers for 5 minutes.
1.243     albertel 8725: 
1.877     foxr     8726: =item *
                   8727: 
                   8728: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8729: data base, returning a hash that is keyed by the resource name and has
                   8730: values that are the resource value.  I believe that the timestamps and
                   8731: versions are also returned.
                   8732: 
                   8733: 
1.243     albertel 8734: =back
                   8735: 
                   8736: =head2 Course Modification
                   8737: 
                   8738: =over 4
1.191     harris41 8739: 
                   8740: =item *
                   8741: 
1.243     albertel 8742: writecoursepref($courseid,%prefs) : write preferences (environment
                   8743: database) for a course
1.191     harris41 8744: 
                   8745: =item *
                   8746: 
1.243     albertel 8747: createcourse($udom,$description,$url) : make/modify course
                   8748: 
                   8749: =back
                   8750: 
                   8751: =head2 Resource Subroutines
                   8752: 
                   8753: =over 4
1.191     harris41 8754: 
                   8755: =item *
                   8756: 
1.243     albertel 8757: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8758: 
                   8759: =item *
                   8760: 
1.243     albertel 8761: repcopy($filename) : subscribes to the requested file, and attempts to
                   8762: replicate from the owning library server, Might return
1.607     raeburn  8763: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8764: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8765: resource. Expects the local filesystem pathname
                   8766: (/home/httpd/html/res/....)
                   8767: 
                   8768: =back
                   8769: 
                   8770: =head2 Resource Information
                   8771: 
                   8772: =over 4
1.191     harris41 8773: 
                   8774: =item *
                   8775: 
1.243     albertel 8776: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8777: a vairety of different possible values, $varname should be a request
                   8778: string, and the other parameters can be used to specify who and what
                   8779: one is asking about.
                   8780: 
                   8781: Possible values for $varname are environment.lastname (or other item
                   8782: from the envirnment hash), user.name (or someother aspect about the
                   8783: user), resource.0.maxtries (or some other part and parameter of a
                   8784: resource)
1.204     albertel 8785: 
                   8786: =item *
                   8787: 
1.243     albertel 8788: directcondval($number) : get current value of a condition; reads from a state
                   8789: string
1.204     albertel 8790: 
                   8791: =item *
                   8792: 
1.243     albertel 8793: condval($condidx) : value of condition index based on state
1.204     albertel 8794: 
                   8795: =item *
                   8796: 
1.243     albertel 8797: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8798: resource's metadata, $what should be either a specific key, or either
                   8799: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8800: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8801: 
                   8802: this function automatically caches all requests
1.191     harris41 8803: 
                   8804: =item *
                   8805: 
1.243     albertel 8806: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8807: network of library servers; returns file handle of where SQL and regex results
                   8808: will be stored for query
1.191     harris41 8809: 
                   8810: =item *
                   8811: 
1.243     albertel 8812: symbread($filename) : return symbolic list entry (filename argument optional);
                   8813: returns the data handle
1.191     harris41 8814: 
                   8815: =item *
                   8816: 
1.243     albertel 8817: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8818: a possible symb for the URL in $thisfn, and if is an encryypted
                   8819: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8820: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8821: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8822: 
1.191     harris41 8823: 
                   8824: =item *
                   8825: 
1.243     albertel 8826: symbclean($symb) : removes versions numbers from a symb, returns the
                   8827: cleaned symb
1.191     harris41 8828: 
                   8829: =item *
                   8830: 
1.243     albertel 8831: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8832: course map, user must be in a course for it to work.
1.191     harris41 8833: 
                   8834: =item *
                   8835: 
1.243     albertel 8836: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8837: 
                   8838: =item *
                   8839: 
1.243     albertel 8840: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8841: a random seed, all arguments are optional, if they aren't sent it uses the
                   8842: environment to derive them. Note: if symb isn't sent and it can't get one
                   8843: from &symbread it will use the current time as its return value
1.191     harris41 8844: 
                   8845: =item *
                   8846: 
1.243     albertel 8847: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8848: unfakeable, receipt
1.191     harris41 8849: 
                   8850: =item *
                   8851: 
1.620     albertel 8852: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8853: 
                   8854: =item *
                   8855: 
1.243     albertel 8856: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8857: 
                   8858: =item *
                   8859: 
1.243     albertel 8860: 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 8861: 
                   8862: =item *
                   8863: 
1.243     albertel 8864: 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 8865: 
                   8866: =item *
                   8867: 
1.243     albertel 8868: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8869: 
                   8870: =item *
                   8871: 
1.243     albertel 8872: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8873: forcing spreadsheet to reevaluate the resource scores next time.
                   8874: 
                   8875: =back
                   8876: 
                   8877: =head2 Storing/Retreiving Data
                   8878: 
                   8879: =over 4
1.191     harris41 8880: 
                   8881: =item *
                   8882: 
1.243     albertel 8883: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8884: for this url; hashref needs to be given and should be a \%hashname; the
                   8885: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8886: be derived from the env
1.191     harris41 8887: 
                   8888: =item *
                   8889: 
1.243     albertel 8890: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8891: uses critical subroutine
1.191     harris41 8892: 
                   8893: =item *
                   8894: 
1.243     albertel 8895: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8896: all args are optional
1.191     harris41 8897: 
                   8898: =item *
                   8899: 
1.717     albertel 8900: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8901: dumps the complete (or key matching regexp) namespace into a hash
                   8902: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8903: normally &store()ed into
                   8904: 
                   8905: $range should be either an integer '100' (give me the first 100
                   8906:                                            matching records)
                   8907:               or be  two integers sperated by a - with no spaces
                   8908:                  '30-50' (give me the 30th through the 50th matching
                   8909:                           records)
                   8910: 
                   8911: 
                   8912: =item *
                   8913: 
                   8914: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8915: replaces a &store() version of data with a replacement set of data
                   8916: for a particular resource in a namespace passed in the $storehash hash 
                   8917: reference
                   8918: 
                   8919: =item *
                   8920: 
1.243     albertel 8921: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8922: works very similar to store/cstore, but all data is stored in a
                   8923: temporary location and can be reset using tmpreset, $storehash should
                   8924: be a hash reference, returns nothing on success
1.191     harris41 8925: 
                   8926: =item *
                   8927: 
1.243     albertel 8928: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8929: similar to restore, but all data is stored in a temporary location and
                   8930: can be reset using tmpreset. Returns a hash of values on success,
                   8931: error string otherwise.
1.191     harris41 8932: 
                   8933: =item *
                   8934: 
1.243     albertel 8935: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8936: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8937: 
                   8938: =item *
                   8939: 
1.243     albertel 8940: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8941: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8942: 
                   8943: =item *
                   8944: 
1.243     albertel 8945: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8946: namesp ($udom and $uname are optional)
1.191     harris41 8947: 
                   8948: =item *
                   8949: 
1.702     albertel 8950: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8951: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8952: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8953: 
1.702     albertel 8954: $range should be either an integer '100' (give me the first 100
                   8955:                                            matching records)
                   8956:               or be  two integers sperated by a - with no spaces
                   8957:                  '30-50' (give me the 30th through the 50th matching
                   8958:                           records)
1.449     matthew  8959: =item *
                   8960: 
                   8961: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8962: $store can be a scalar, an array reference, or if the amount to be 
                   8963: incremented is > 1, a hash reference.
                   8964: 
                   8965: ($udom and $uname are optional)
1.191     harris41 8966: 
                   8967: =item *
                   8968: 
1.243     albertel 8969: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8970: ($udom and $uname are optional)
1.191     harris41 8971: 
                   8972: =item *
                   8973: 
1.243     albertel 8974: cput($namespace,$storehash,$udom,$uname) : critical put
                   8975: ($udom and $uname are optional)
1.191     harris41 8976: 
                   8977: =item *
                   8978: 
1.748     albertel 8979: newput($namespace,$storehash,$udom,$uname) :
                   8980: 
                   8981: Attempts to store the items in the $storehash, but only if they don't
                   8982: currently exist, if this succeeds you can be certain that you have 
                   8983: successfully created a new key value pair in the $namespace db.
                   8984: 
                   8985: 
                   8986: Args:
                   8987:  $namespace: name of database to store values to
                   8988:  $storehash: hashref to store to the db
                   8989:  $udom: (optional) domain of user containing the db
                   8990:  $uname: (optional) name of user caontaining the db
                   8991: 
                   8992: Returns:
                   8993:  'ok' -> succeeded in storing all keys of $storehash
                   8994:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8995:                         least <key> already existed in the db (other
                   8996:                         requested keys may also already exist)
                   8997:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8998:  'con_lost' -> unable to contact request server
                   8999:  'refused' -> action was not allowed by remote machine
                   9000: 
                   9001: 
                   9002: =item *
                   9003: 
1.243     albertel 9004: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9005: reference filled in from namesp (encrypts the return communication)
                   9006: ($udom and $uname are optional)
1.191     harris41 9007: 
                   9008: =item *
                   9009: 
1.243     albertel 9010: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9011: critical subroutine
                   9012: 
1.806     raeburn  9013: =item *
                   9014: 
1.860     raeburn  9015: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9016: array reference filled in from namespace found in domain level on either
                   9017: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9018: 
                   9019: =item *
                   9020: 
1.860     raeburn  9021: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9022: domain level either on specified domain server ($uhome) or primary domain 
                   9023: server ($udom and $uhome are optional)
1.806     raeburn  9024: 
1.243     albertel 9025: =back
                   9026: 
                   9027: =head2 Network Status Functions
                   9028: 
                   9029: =over 4
1.191     harris41 9030: 
                   9031: =item *
                   9032: 
                   9033: dirlist($uri) : return directory list based on URI
                   9034: 
                   9035: =item *
                   9036: 
1.243     albertel 9037: spareserver() : find server with least workload from spare.tab
                   9038: 
                   9039: =back
                   9040: 
                   9041: =head2 Apache Request
                   9042: 
                   9043: =over 4
1.191     harris41 9044: 
                   9045: =item *
                   9046: 
1.243     albertel 9047: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9048: localhost, posts hash
                   9049: 
                   9050: =back
                   9051: 
                   9052: =head2 Data to String to Data
                   9053: 
                   9054: =over 4
1.191     harris41 9055: 
                   9056: =item *
                   9057: 
1.243     albertel 9058: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9059: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9060: 
                   9061: =item *
                   9062: 
1.243     albertel 9063: hashref2str($hashref) : convert a hashref into a string complete with
                   9064: escaping and '=' and '&' separators, supports elements that are
                   9065: arrayrefs and hashrefs
1.191     harris41 9066: 
                   9067: =item *
                   9068: 
1.243     albertel 9069: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9070: with escaping and '&' separators, supports elements that are arrayrefs
                   9071: and hashrefs
1.191     harris41 9072: 
                   9073: =item *
                   9074: 
1.243     albertel 9075: str2hash($string) : convert string to hash using unescaping and
                   9076: splitting on '=' and '&', supports elements that are arrayrefs and
                   9077: hashrefs
1.191     harris41 9078: 
                   9079: =item *
                   9080: 
1.243     albertel 9081: str2array($string) : convert string to hash using unescaping and
                   9082: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9083: 
                   9084: =back
                   9085: 
                   9086: =head2 Logging Routines
                   9087: 
                   9088: =over 4
                   9089: 
                   9090: These routines allow one to make log messages in the lonnet.log and
                   9091: lonnet.perm logfiles.
1.191     harris41 9092: 
                   9093: =item *
                   9094: 
1.243     albertel 9095: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9096: 
                   9097: =item *
                   9098: 
1.243     albertel 9099: logthis() : append message to the normal lonnet.log file, it gets
                   9100: preiodically rolled over and deleted.
1.191     harris41 9101: 
                   9102: =item *
                   9103: 
1.243     albertel 9104: logperm() : append a permanent message to lonnet.perm.log, this log
                   9105: file never gets deleted by any automated portion of the system, only
                   9106: messages of critical importance should go in here.
                   9107: 
                   9108: =back
                   9109: 
                   9110: =head2 General File Helper Routines
                   9111: 
                   9112: =over 4
1.191     harris41 9113: 
                   9114: =item *
                   9115: 
1.481     raeburn  9116: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9117: (a) files in /uploaded
                   9118:   (i) If a local copy of the file exists - 
                   9119:       compares modification date of local copy with last-modified date for 
                   9120:       definitive version stored on home server for course. If local copy is 
                   9121:       stale, requests a new version from the home server and stores it. 
                   9122:       If the original has been removed from the home server, then local copy 
                   9123:       is unlinked.
                   9124:   (ii) If local copy does not exist -
                   9125:       requests the file from the home server and stores it. 
                   9126:   
                   9127:   If $caller is 'uploadrep':  
                   9128:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9129:     for request for files originally uploaded via DOCS. 
                   9130:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9131:   
                   9132:   Otherwise:
                   9133:      This indicates a call from the content generation phase of the request.
                   9134:      -  returns the entire contents of the file or -1.
                   9135:      
                   9136: (b) files in /res
                   9137:    - returns the entire contents of a file or -1; 
                   9138:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9139: 
1.712     albertel 9140: 
                   9141: =item *
                   9142: 
                   9143: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9144:                   reference
                   9145: 
                   9146: returns either a stat() list of data about the file or an empty list
                   9147: if the file doesn't exist or couldn't find out about it (connection
                   9148: problems or user unknown)
                   9149: 
1.191     harris41 9150: =item *
                   9151: 
1.243     albertel 9152: filelocation($dir,$file) : returns file system location of a file
                   9153: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9154: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9155: and a file of ../bob will become /a/bob)
1.191     harris41 9156: 
                   9157: =item *
                   9158: 
                   9159: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9160: filelocation except for hrefs
                   9161: 
                   9162: =item *
                   9163: 
                   9164: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9165: 
1.243     albertel 9166: =back
                   9167: 
1.608     albertel 9168: =head2 Usererfile file routines (/uploaded*)
                   9169: 
                   9170: =over 4
                   9171: 
                   9172: =item *
                   9173: 
                   9174: userfileupload(): main rotine for putting a file in a user or course's
                   9175:                   filespace, arguments are,
                   9176: 
1.620     albertel 9177:  formname - required - this is the name of the element in $env where the
1.608     albertel 9178:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9179:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9180:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9181:  coursedoc - if true, store the file in the course of the active role
                   9182:              of the current user
                   9183:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9184:          if undefined, it will be placed in "unknown"
                   9185: 
                   9186:  (This routine calls clean_filename() to remove any dangerous
                   9187:  characters from the filename, and then calls finuserfileupload() to
                   9188:  complete the transaction)
                   9189: 
                   9190:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9191:  and /adm/notfound.html if unsuccessful
                   9192: 
                   9193: =item *
                   9194: 
                   9195: clean_filename(): routine for cleaing a filename up for storage in
                   9196:                  userfile space, argument is:
                   9197: 
                   9198:  filename - proposed filename
                   9199: 
                   9200: returns: the new clean filename
                   9201: 
                   9202: =item *
                   9203: 
                   9204: finishuserfileupload(): routine that creaes and sends the file to
                   9205: userspace, probably shouldn't be called directly
                   9206: 
                   9207:   docuname: username or courseid of destination for the file
                   9208:   docudom: domain of user/course of destination for the file
                   9209:   formname: same as for userfileupload()
                   9210:   fname: filename (inculding subdirectories) for the file
                   9211: 
                   9212:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9213:  and /adm/notfound.html if unsuccessful
                   9214: 
                   9215: =item *
                   9216: 
                   9217: renameuserfile(): renames an existing userfile to a new name
                   9218: 
                   9219:   Args:
                   9220:    docuname: username or courseid of destination for the file
                   9221:    docudom: domain of user/course of destination for the file
                   9222:    old: current file name (including any subdirs under userfiles)
                   9223:    new: desired file name (including any subdirs under userfiles)
                   9224: 
                   9225: =item *
                   9226: 
                   9227: mkdiruserfile(): creates a directory is a userfiles dir
                   9228: 
                   9229:   Args:
                   9230:    docuname: username or courseid of destination for the file
                   9231:    docudom: domain of user/course of destination for the file
                   9232:    dir: dir to create (including any subdirs under userfiles)
                   9233: 
                   9234: =item *
                   9235: 
                   9236: removeuserfile(): removes a file that exists in userfiles
                   9237: 
                   9238:   Args:
                   9239:    docuname: username or courseid of destination for the file
                   9240:    docudom: domain of user/course of destination for the file
                   9241:    fname: filname to delete (including any subdirs under userfiles)
                   9242: 
                   9243: =item *
                   9244: 
                   9245: removeuploadedurl(): convience function for removeuserfile()
                   9246: 
                   9247:   Args:
                   9248:    url:  a full /uploaded/... url to delete
                   9249: 
1.747     albertel 9250: =item * 
                   9251: 
                   9252: get_portfile_permissions():
                   9253:   Args:
                   9254:     domain: domain of user or course contain the portfolio files
                   9255:     user: name of user or num of course contain the portfolio files
                   9256:   Returns:
                   9257:     hashref of a dump of the proper file_permissions.db
                   9258:    
                   9259: 
                   9260: =item * 
                   9261: 
                   9262: get_access_controls():
                   9263: 
                   9264: Args:
                   9265:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9266:   group: (optional) the group you want the files associated with
                   9267:   file: (optional) the file you want access info on
                   9268: 
                   9269: Returns:
1.749     raeburn  9270:     a hash (keys are file names) of hashes containing
                   9271:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9272:         values are XML containing access control settings (see below) 
1.747     albertel 9273: 
                   9274: Internal notes:
                   9275: 
1.749     raeburn  9276:  access controls are stored in file_permissions.db as key=value pairs.
                   9277:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9278:         where scope -> public,guest,course,group,domains or users.
                   9279:               end -> UNIX time for end of access (0 -> no end date)
                   9280:               start -> UNIX time for start of access
                   9281: 
                   9282:     value -> XML description of access control
                   9283:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9284:             <start></start>
                   9285:             <end></end>
                   9286: 
                   9287:             <password></password>  for scope type = guest
                   9288: 
                   9289:             <domain></domain>     for scope type = course or group
                   9290:             <number></number>
                   9291:             <roles id="">
                   9292:              <role></role>
                   9293:              <access></access>
                   9294:              <section></section>
                   9295:              <group></group>
                   9296:             </roles>
                   9297: 
                   9298:             <dom></dom>         for scope type = domains
                   9299: 
                   9300:             <users>             for scope type = users
                   9301:              <user>
                   9302:               <uname></uname>
                   9303:               <udom></udom>
                   9304:              </user>
                   9305:             </users>
                   9306:            </scope> 
                   9307:               
                   9308:  Access data is also aggregated for each file in an additional key=value pair:
                   9309:  key -> path to file/file_name\0accesscontrol 
                   9310:  value -> reference to hash
                   9311:           hash contains key = value pairs
                   9312:           where key = uniqueID:scope_end_start
                   9313:                 value = UNIX time record was last updated
                   9314: 
                   9315:           Used to improve speed of look-ups of access controls for each file.  
                   9316:  
                   9317:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9318: 
                   9319: modify_access_controls():
                   9320: 
                   9321: Modifies access controls for a portfolio file
                   9322: Args
                   9323: 1. file name
                   9324: 2. reference to hash of required changes,
                   9325: 3. domain
                   9326: 4. username
                   9327:   where domain,username are the domain of the portfolio owner 
                   9328:   (either a user or a course) 
                   9329: 
                   9330: Returns:
                   9331: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9332: 2. result of deletions ('ok' or 'error', with error message).
                   9333: 3. reference to hash of any new or updated access controls.
                   9334: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9335:    key = integer (inbound ID)
                   9336:    value = uniqueID  
1.747     albertel 9337: 
1.608     albertel 9338: =back
                   9339: 
1.243     albertel 9340: =head2 HTTP Helper Routines
                   9341: 
                   9342: =over 4
                   9343: 
1.191     harris41 9344: =item *
                   9345: 
                   9346: escape() : unpack non-word characters into CGI-compatible hex codes
                   9347: 
                   9348: =item *
                   9349: 
                   9350: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9351: 
1.243     albertel 9352: =back
                   9353: 
                   9354: =head1 PRIVATE SUBROUTINES
                   9355: 
                   9356: =head2 Underlying communication routines (Shouldn't call)
                   9357: 
                   9358: =over 4
                   9359: 
                   9360: =item *
                   9361: 
                   9362: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9363: 
                   9364: =item *
                   9365: 
                   9366: reply() : uses subreply to send a message to remote machine, logs all failures
                   9367: 
                   9368: =item *
                   9369: 
                   9370: critical() : passes a critical message to another server; if cannot
                   9371: get through then place message in connection buffer directory and
                   9372: returns con_delayed, if incapable of saving message, returns
                   9373: con_failed
                   9374: 
                   9375: =item *
                   9376: 
                   9377: reconlonc() : tries to reconnect lonc client processes.
                   9378: 
                   9379: =back
                   9380: 
                   9381: =head2 Resource Access Logging
                   9382: 
                   9383: =over 4
                   9384: 
                   9385: =item *
                   9386: 
                   9387: flushcourselogs() : flush (save) buffer logs and access logs
                   9388: 
                   9389: =item *
                   9390: 
                   9391: courselog($what) : save message for course in hash
                   9392: 
                   9393: =item *
                   9394: 
                   9395: courseacclog($what) : save message for course using &courselog().  Perform
                   9396: special processing for specific resource types (problems, exams, quizzes, etc).
                   9397: 
1.191     harris41 9398: =item *
                   9399: 
                   9400: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9401: as a PerlChildExitHandler
1.243     albertel 9402: 
                   9403: =back
                   9404: 
                   9405: =head2 Other
                   9406: 
                   9407: =over 4
                   9408: 
                   9409: =item *
                   9410: 
                   9411: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9412: 
                   9413: =back
                   9414: 
                   9415: =cut
1.877     foxr     9416: 

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