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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.898   ! albertel    4: # $Id: lonnet.pm,v 1.897 2007/07/19 23:02:37 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.344     www       859: # --------------------------------------------------- Assign a key to a student
                    860: 
                    861: sub assign_access_key {
1.364     www       862: #
                    863: # a valid key looks like uname:udom#comments
                    864: # comments are being appended
                    865: #
1.498     www       866:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    867:     $kdom=
1.620     albertel  868:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       869:     $knum=
1.620     albertel  870:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       871:     $cdom=
1.620     albertel  872:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       873:     $cnum=
1.620     albertel  874:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    875:     $udom=$env{'user.name'} unless (defined($udom));
                    876:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       877:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       878:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  879:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       880:                                                   # assigned to this person
                    881:                                                   # - this should not happen,
1.345     www       882:                                                   # unless something went wrong
                    883:                                                   # the first time around
                    884: # ready to assign
1.364     www       885:         $logentry=$1.'; '.$logentry;
1.496     www       886:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       887:                                                  $kdom,$knum) eq 'ok') {
1.345     www       888: # key now belongs to user
1.346     www       889: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       890:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    891:                 &appenv('environment.'.$envkey => $ckey);
                    892:                 return 'ok';
                    893:             } else {
                    894:                 return 
                    895:   'error: Count not permanently assign key, will need to be re-entered later.';
                    896: 	    }
                    897:         } else {
                    898:             return 'error: Could not assign key, try again later.';
                    899:         }
1.364     www       900:     } elsif (!$existing{$ckey}) {
1.345     www       901: # the key does not exist
                    902: 	return 'error: The key does not exist';
                    903:     } else {
                    904: # the key is somebody else's
                    905: 	return 'error: The key is already in use';
                    906:     }
1.344     www       907: }
                    908: 
1.364     www       909: # ------------------------------------------ put an additional comment on a key
                    910: 
                    911: sub comment_access_key {
                    912: #
                    913: # a valid key looks like uname:udom#comments
                    914: # comments are being appended
                    915: #
                    916:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    917:     $cdom=
1.620     albertel  918:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       919:     $cnum=
1.620     albertel  920:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       921:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    922:     if ($existing{$ckey}) {
                    923:         $existing{$ckey}.='; '.$logentry;
                    924: # ready to assign
1.367     www       925:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       926:                                                  $cdom,$cnum) eq 'ok') {
                    927: 	    return 'ok';
                    928:         } else {
                    929: 	    return 'error: Count not store comment.';
                    930:         }
                    931:     } else {
                    932: # the key does not exist
                    933: 	return 'error: The key does not exist';
                    934:     }
                    935: }
                    936: 
1.344     www       937: # ------------------------------------------------------ Generate a set of keys
                    938: 
                    939: sub generate_access_keys {
1.364     www       940:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       941:     $cdom=
1.620     albertel  942:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       943:     $cnum=
1.620     albertel  944:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       945:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       946:     unless (($cdom) && ($cnum)) { return 0; }
                    947:     if ($number>10000) { return 0; }
                    948:     sleep(2); # make sure don't get same seed twice
                    949:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    950:     my $total=0;
                    951:     for (my $i=1;$i<=$number;$i++) {
                    952:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    953:                   sprintf("%lx",int(100000*rand)).'-'.
                    954:                   sprintf("%lx",int(100000*rand));
                    955:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    956:        $newkey=~s/0/h/g; # and also 0 and O
                    957:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    958:        if ($existing{$newkey}) {
                    959:            $i--;
                    960:        } else {
1.364     www       961: 	  if (&put('accesskeys',
                    962:               { $newkey => '# generated '.localtime().
1.620     albertel  963:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       964:                            '; '.$logentry },
                    965: 		   $cdom,$cnum) eq 'ok') {
1.344     www       966:               $total++;
                    967: 	  }
                    968:        }
                    969:     }
1.620     albertel  970:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       971:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    972:     return $total;
                    973: }
                    974: 
                    975: # ------------------------------------------------------- Validate an accesskey
                    976: 
                    977: sub validate_access_key {
                    978:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    979:     $cdom=
1.620     albertel  980:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       981:     $cnum=
1.620     albertel  982:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    983:     $udom=$env{'user.domain'} unless (defined($udom));
                    984:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       985:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  986:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       987: }
                    988: 
                    989: # ------------------------------------- Find the section of student in a course
1.652     albertel  990: sub devalidate_getsection_cache {
                    991:     my ($udom,$unam,$courseid)=@_;
                    992:     my $hashid="$udom:$unam:$courseid";
                    993:     &devalidate_cache_new('getsection',$hashid);
                    994: }
1.298     matthew   995: 
1.815     albertel  996: sub courseid_to_courseurl {
                    997:     my ($courseid) = @_;
                    998:     #already url style courseid
                    999:     return $courseid if ($courseid =~ m{^/});
                   1000: 
                   1001:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1002: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1003: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1004: 	return "/$cdom/$cnum";
                   1005:     }
                   1006: 
                   1007:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1008:     if (exists($courseinfo{'num'})) {
                   1009: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1010:     }
                   1011: 
                   1012:     return undef;
                   1013: }
                   1014: 
1.298     matthew  1015: sub getsection {
                   1016:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1017:     my $cachetime=1800;
1.551     albertel 1018: 
                   1019:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1020:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1021:     if (defined($cached)) { return $result; }
                   1022: 
1.298     matthew  1023:     my %Pending; 
                   1024:     my %Expired;
                   1025:     #
                   1026:     # Each role can either have not started yet (pending), be active, 
                   1027:     #    or have expired.
                   1028:     #
                   1029:     # If there is an active role, we are done.
                   1030:     #
                   1031:     # If there is more than one role which has not started yet, 
                   1032:     #     choose the one which will start sooner
                   1033:     # If there is one role which has not started yet, return it.
                   1034:     #
                   1035:     # If there is more than one expired role, choose the one which ended last.
                   1036:     # If there is a role which has expired, return it.
                   1037:     #
1.815     albertel 1038:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1039:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1040:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1041:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1042:         my $section=$1;
                   1043:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1044:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1045:         my $now=time;
1.548     albertel 1046:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1047:             $Expired{$end}=$section;
                   1048:             next;
                   1049:         }
1.548     albertel 1050:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1051:             $Pending{$start}=$section;
                   1052:             next;
                   1053:         }
1.599     albertel 1054:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1055:     }
                   1056:     #
                   1057:     # Presumedly there will be few matching roles from the above
                   1058:     # loop and the sorting time will be negligible.
                   1059:     if (scalar(keys(%Pending))) {
                   1060:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1061:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1062:     } 
                   1063:     if (scalar(keys(%Expired))) {
                   1064:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1065:         my $time = pop(@sorted);
1.599     albertel 1066:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1067:     }
1.599     albertel 1068:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1069: }
1.70      www      1070: 
1.599     albertel 1071: sub save_cache {
                   1072:     &purge_remembered();
1.722     albertel 1073:     #&Apache::loncommon::validate_page();
1.620     albertel 1074:     undef(%env);
1.780     albertel 1075:     undef($env_loaded);
1.599     albertel 1076: }
1.452     albertel 1077: 
1.599     albertel 1078: my $to_remember=-1;
                   1079: my %remembered;
                   1080: my %accessed;
                   1081: my $kicks=0;
                   1082: my $hits=0;
1.849     albertel 1083: sub make_key {
                   1084:     my ($name,$id) = @_;
1.872     albertel 1085:     if (length($id) > 65 
                   1086: 	&& length(&escape($id)) > 200) {
                   1087: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1088:     }
1.849     albertel 1089:     return &escape($name.':'.$id);
                   1090: }
                   1091: 
1.599     albertel 1092: sub devalidate_cache_new {
                   1093:     my ($name,$id,$debug) = @_;
                   1094:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1095:     $id=&make_key($name,$id);
1.599     albertel 1096:     $memcache->delete($id);
                   1097:     delete($remembered{$id});
                   1098:     delete($accessed{$id});
                   1099: }
                   1100: 
                   1101: sub is_cached_new {
                   1102:     my ($name,$id,$debug) = @_;
1.849     albertel 1103:     $id=&make_key($name,$id);
1.599     albertel 1104:     if (exists($remembered{$id})) {
                   1105: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1106: 	$accessed{$id}=[&gettimeofday()];
                   1107: 	$hits++;
                   1108: 	return ($remembered{$id},1);
                   1109:     }
                   1110:     my $value = $memcache->get($id);
                   1111:     if (!(defined($value))) {
                   1112: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1113: 	return (undef,undef);
1.416     albertel 1114:     }
1.599     albertel 1115:     if ($value eq '__undef__') {
                   1116: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1117: 	$value=undef;
                   1118:     }
                   1119:     &make_room($id,$value,$debug);
                   1120:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1121:     return ($value,1);
                   1122: }
                   1123: 
                   1124: sub do_cache_new {
                   1125:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1126:     $id=&make_key($name,$id);
1.599     albertel 1127:     my $setvalue=$value;
                   1128:     if (!defined($setvalue)) {
                   1129: 	$setvalue='__undef__';
                   1130:     }
1.623     albertel 1131:     if (!defined($time) ) {
                   1132: 	$time=600;
                   1133:     }
1.599     albertel 1134:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.872     albertel 1135:     if (!($memcache->set($id,$setvalue,$time))) {
                   1136: 	&logthis("caching of id -> $id  failed");
                   1137:     }
1.600     albertel 1138:     # need to make a copy of $value
                   1139:     #&make_room($id,$value,$debug);
1.599     albertel 1140:     return $value;
                   1141: }
                   1142: 
                   1143: sub make_room {
                   1144:     my ($id,$value,$debug)=@_;
                   1145:     $remembered{$id}=$value;
                   1146:     if ($to_remember<0) { return; }
                   1147:     $accessed{$id}=[&gettimeofday()];
                   1148:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1149:     my $to_kick;
                   1150:     my $max_time=0;
                   1151:     foreach my $other (keys(%accessed)) {
                   1152: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1153: 	    $to_kick=$other;
                   1154: 	    $max_time=&tv_interval($accessed{$other});
                   1155: 	}
                   1156:     }
                   1157:     delete($remembered{$to_kick});
                   1158:     delete($accessed{$to_kick});
                   1159:     $kicks++;
                   1160:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1161:     return;
                   1162: }
                   1163: 
1.599     albertel 1164: sub purge_remembered {
1.604     albertel 1165:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1166:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1167:     undef(%remembered);
                   1168:     undef(%accessed);
1.428     albertel 1169: }
1.70      www      1170: # ------------------------------------- Read an entry from a user's environment
                   1171: 
                   1172: sub userenvironment {
                   1173:     my ($udom,$unam,@what)=@_;
                   1174:     my %returnhash=();
                   1175:     my @answer=split(/\&/,
                   1176:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1177:                       &homeserver($unam,$udom)));
                   1178:     my $i;
                   1179:     for ($i=0;$i<=$#what;$i++) {
                   1180: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1181:     }
                   1182:     return %returnhash;
1.1       albertel 1183: }
                   1184: 
1.617     albertel 1185: # ---------------------------------------------------------- Get a studentphoto
                   1186: sub studentphoto {
                   1187:     my ($udom,$unam,$ext) = @_;
                   1188:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1189:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1190:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1191:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1192:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1193:             } else {
                   1194:                 my ($result,$perm_reqd)=
1.707     albertel 1195: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1196:                 if ($result eq 'ok') {
                   1197:                     if (!($perm_reqd eq 'yes')) {
                   1198:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1199:                     }
                   1200:                 }
                   1201:             }
                   1202:         }
                   1203:     } else {
                   1204:         my ($result,$perm_reqd) = 
1.707     albertel 1205: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1206:         if ($result eq 'ok') {
                   1207:             if (!($perm_reqd eq 'yes')) {
                   1208:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1209:             }
                   1210:         }
                   1211:     }
                   1212:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1213: }
                   1214: 
                   1215: sub retrievestudentphoto {
                   1216:     my ($udom,$unam,$ext,$type) = @_;
                   1217:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1218:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1219:     if ($ret eq 'ok') {
                   1220:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1221:         if ($type eq 'thumbnail') {
                   1222:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1223:         }
                   1224:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1225:         return $tokenurl;
                   1226:     } else {
                   1227:         if ($type eq 'thumbnail') {
                   1228:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1229:         } else { 
                   1230:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1231:         }
1.617     albertel 1232:     }
                   1233: }
                   1234: 
1.263     www      1235: # -------------------------------------------------------------------- New chat
                   1236: 
                   1237: sub chatsend {
1.724     raeburn  1238:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1239:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1240:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1241:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1242:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1243: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1244: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1245: }
                   1246: 
                   1247: # ------------------------------------------ Find current version of a resource
                   1248: 
                   1249: sub getversion {
                   1250:     my $fname=&clutter(shift);
                   1251:     unless ($fname=~/^\/res\//) { return -1; }
                   1252:     return &currentversion(&filelocation('',$fname));
                   1253: }
                   1254: 
                   1255: sub currentversion {
                   1256:     my $fname=shift;
1.599     albertel 1257:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1258:     if (defined($cached)) { return $result; }
1.292     www      1259:     my $author=$fname;
                   1260:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1261:     my ($udom,$uname)=split(/\//,$author);
                   1262:     my $home=homeserver($uname,$udom);
                   1263:     if ($home eq 'no_host') { 
                   1264:         return -1; 
                   1265:     }
                   1266:     my $answer=reply("currentversion:$fname",$home);
                   1267:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1268: 	return -1;
                   1269:     }
1.599     albertel 1270:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1271: }
                   1272: 
1.1       albertel 1273: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1274: 
1.1       albertel 1275: sub subscribe {
                   1276:     my $fname=shift;
1.761     raeburn  1277:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1278:     $fname=~s/[\n\r]//g;
1.1       albertel 1279:     my $author=$fname;
                   1280:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1281:     my ($udom,$uname)=split(/\//,$author);
                   1282:     my $home=homeserver($uname,$udom);
1.335     albertel 1283:     if ($home eq 'no_host') {
                   1284:         return 'not_found';
1.1       albertel 1285:     }
                   1286:     my $answer=reply("sub:$fname",$home);
1.64      www      1287:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1288: 	$answer.=' by '.$home;
                   1289:     }
1.1       albertel 1290:     return $answer;
                   1291: }
                   1292:     
1.8       www      1293: # -------------------------------------------------------------- Replicate file
                   1294: 
                   1295: sub repcopy {
                   1296:     my $filename=shift;
1.23      www      1297:     $filename=~s/\/+/\//g;
1.607     raeburn  1298:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1299:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1300:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1301: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1302: 	return &repcopy_userfile($filename);
                   1303:     }
1.532     albertel 1304:     $filename=~s/[\n\r]//g;
1.8       www      1305:     my $transname="$filename.in.transfer";
1.828     www      1306: # FIXME: this should flock
1.607     raeburn  1307:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1308:     my $remoteurl=subscribe($filename);
1.64      www      1309:     if ($remoteurl =~ /^con_lost by/) {
                   1310: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1311:            return 'unavailable';
1.8       www      1312:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1313: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1314: 	   return 'not_found';
1.64      www      1315:     } elsif ($remoteurl =~ /^rejected by/) {
                   1316: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1317:            return 'forbidden';
1.20      www      1318:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1319:            return 'ok';
1.8       www      1320:     } else {
1.290     www      1321:         my $author=$filename;
                   1322:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1323:         my ($udom,$uname)=split(/\//,$author);
                   1324:         my $home=homeserver($uname,$udom);
                   1325:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1326:            my @parts=split(/\//,$filename);
                   1327:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1328:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1329:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1330: 	       return 'bad_request';
1.8       www      1331:            }
                   1332:            my $count;
                   1333:            for ($count=5;$count<$#parts;$count++) {
                   1334:                $path.="/$parts[$count]";
                   1335:                if ((-e $path)!=1) {
                   1336: 		   mkdir($path,0777);
                   1337:                }
                   1338:            }
                   1339:            my $ua=new LWP::UserAgent;
                   1340:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1341:            my $response=$ua->request($request,$transname);
                   1342:            if ($response->is_error()) {
                   1343: 	       unlink($transname);
                   1344:                my $message=$response->status_line;
1.672     albertel 1345:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1346:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1347:                return 'unavailable';
1.8       www      1348:            } else {
1.16      www      1349: 	       if ($remoteurl!~/\.meta$/) {
                   1350:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1351:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1352:                   if ($mresponse->is_error()) {
                   1353: 		      unlink($filename.'.meta');
                   1354:                       &logthis(
1.672     albertel 1355:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1356:                   }
                   1357: 	       }
1.8       www      1358:                rename($transname,$filename);
1.607     raeburn  1359:                return 'ok';
1.8       www      1360:            }
1.290     www      1361:        }
1.8       www      1362:     }
1.330     www      1363: }
                   1364: 
                   1365: # ------------------------------------------------ Get server side include body
                   1366: sub ssi_body {
1.381     albertel 1367:     my ($filelink,%form)=@_;
1.606     matthew  1368:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1369:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1370:     }
1.330     www      1371:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1372:                                      &ssi($filelink,%form));
1.778     albertel 1373:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1374:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1375:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1376:     return $output;
1.8       www      1377: }
                   1378: 
1.15      www      1379: # --------------------------------------------------------- Server Side Include
                   1380: 
1.782     albertel 1381: sub absolute_url {
                   1382:     my ($host_name) = @_;
                   1383:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1384:     if ($host_name eq '') {
                   1385: 	$host_name = $ENV{'SERVER_NAME'};
                   1386:     }
                   1387:     return $protocol.$host_name;
                   1388: }
                   1389: 
1.15      www      1390: sub ssi {
                   1391: 
1.23      www      1392:     my ($fn,%form)=@_;
1.15      www      1393: 
                   1394:     my $ua=new LWP::UserAgent;
1.23      www      1395:     
                   1396:     my $request;
1.711     albertel 1397: 
                   1398:     $form{'no_update_last_known'}=1;
1.895     albertel 1399:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1400:     if (%form) {
1.782     albertel 1401:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1402:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1403:     } else {
1.782     albertel 1404:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1405:     }
                   1406: 
1.15      www      1407:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1408:     my $response=$ua->request($request);
                   1409: 
1.324     www      1410:     return $response->content;
                   1411: }
                   1412: 
                   1413: sub externalssi {
                   1414:     my ($url)=@_;
                   1415:     my $ua=new LWP::UserAgent;
                   1416:     my $request=new HTTP::Request('GET',$url);
                   1417:     my $response=$ua->request($request);
1.15      www      1418:     return $response->content;
                   1419: }
1.254     www      1420: 
1.492     albertel 1421: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1422: 
                   1423: sub allowuploaded {
                   1424:     my ($srcurl,$url)=@_;
                   1425:     $url=&clutter(&declutter($url));
                   1426:     my $dir=$url;
                   1427:     $dir=~s/\/[^\/]+$//;
                   1428:     my %httpref=();
                   1429:     my $httpurl=&hreflocation('',$url);
                   1430:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1431:     &Apache::lonnet::appenv(%httpref);
1.254     www      1432: }
1.477     raeburn  1433: 
1.478     albertel 1434: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1435: # input: action, courseID, current domain, intended
1.637     raeburn  1436: #        path to file, source of file, instruction to parse file for objects,
                   1437: #        ref to hash for embedded objects,
                   1438: #        ref to hash for codebase of java objects.
                   1439: #
1.485     raeburn  1440: # output: url to file (if action was uploaddoc), 
                   1441: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1442: #
1.478     albertel 1443: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1444: # course.
1.477     raeburn  1445: #
1.478     albertel 1446: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1447: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1448: #          course's home server.
1.477     raeburn  1449: #
1.478     albertel 1450: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1451: #          be copied from $source (current location) to 
                   1452: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1453: #         and will then be copied to
                   1454: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1455: #         course's home server.
1.485     raeburn  1456: #
1.481     raeburn  1457: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1458: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1459: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1460: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1461: #         in course's home server.
1.637     raeburn  1462: #
1.477     raeburn  1463: 
                   1464: sub process_coursefile {
1.638     albertel 1465:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1466:     my $fetchresult;
1.638     albertel 1467:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1468:     if ($action eq 'propagate') {
1.638     albertel 1469:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1470: 			     $home);
1.481     raeburn  1471:     } else {
1.477     raeburn  1472:         my $fpath = '';
                   1473:         my $fname = $file;
1.478     albertel 1474:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1475:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1476:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1477:         if ($action eq 'copy') {
                   1478:             if ($source eq '') {
                   1479:                 $fetchresult = 'no source file';
                   1480:                 return $fetchresult;
                   1481:             } else {
                   1482:                 my $destination = $filepath.'/'.$fname;
                   1483:                 rename($source,$destination);
                   1484:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1485:                                  $home);
1.481     raeburn  1486:             }
                   1487:         } elsif ($action eq 'uploaddoc') {
                   1488:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1489:             print $fh $env{'form.'.$source};
1.481     raeburn  1490:             close($fh);
1.637     raeburn  1491:             if ($parser eq 'parse') {
                   1492:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1493:                 unless ($parse_result eq 'ok') {
                   1494:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1495:                 }
                   1496:             }
1.477     raeburn  1497:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1498:                                  $home);
1.481     raeburn  1499:             if ($fetchresult eq 'ok') {
                   1500:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1501:             } else {
                   1502:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1503:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1504:                 return '/adm/notfound.html';
                   1505:             }
1.477     raeburn  1506:         }
                   1507:     }
1.485     raeburn  1508:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1509:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1510:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1511:     }
                   1512:     return $fetchresult;
                   1513: }
                   1514: 
1.637     raeburn  1515: sub build_filepath {
                   1516:     my ($fpath) = @_;
                   1517:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1518:     unless ($fpath eq '') {
                   1519:         my @parts=split('/',$fpath);
                   1520:         foreach my $part (@parts) {
                   1521:             $filepath.= '/'.$part;
                   1522:             if ((-e $filepath)!=1) {
                   1523:                 mkdir($filepath,0777);
                   1524:             }
                   1525:         }
                   1526:     }
                   1527:     return $filepath;
                   1528: }
                   1529: 
                   1530: sub store_edited_file {
1.638     albertel 1531:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1532:     my $file = $primary_url;
                   1533:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1534:     my $fpath = '';
                   1535:     my $fname = $file;
                   1536:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1537:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1538:     my $filepath = &build_filepath($fpath);
                   1539:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1540:     print $fh $content;
                   1541:     close($fh);
1.638     albertel 1542:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1543:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1544: 			  $home);
1.637     raeburn  1545:     if ($$fetchresult eq 'ok') {
                   1546:         return '/uploaded/'.$fpath.'/'.$fname;
                   1547:     } else {
1.638     albertel 1548:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1549: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1550:         return '/adm/notfound.html';
                   1551:     }
                   1552: }
                   1553: 
1.531     albertel 1554: sub clean_filename {
1.831     albertel 1555:     my ($fname,$args)=@_;
1.315     www      1556: # Replace Windows backslashes by forward slashes
1.257     www      1557:     $fname=~s/\\/\//g;
1.831     albertel 1558:     if (!$args->{'keep_path'}) {
                   1559:         # Get rid of everything but the actual filename
                   1560: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1561:     }
1.315     www      1562: # Replace spaces by underscores
                   1563:     $fname=~s/\s+/\_/g;
                   1564: # Replace all other weird characters by nothing
1.831     albertel 1565:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1566: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1567: # numbers
                   1568:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1569:     return $fname;
                   1570: }
                   1571: 
1.608     albertel 1572: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1573: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1574: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1575: #        $coursedoc - if true up to the current course
                   1576: #                     if false
                   1577: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1578: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1579: #        $allfiles - reference to hash for embedded objects
                   1580: #        $codebase - reference to hash for codebase of java objects
                   1581: #        $desuname - username for permanent storage of uploaded file
                   1582: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1583: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1584: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1585: # 
1.686     albertel 1586: # output: url of file in userspace, or error: <message> 
                   1587: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1588: 
                   1589: 
1.531     albertel 1590: sub userfileupload {
1.860     raeburn  1591:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1592:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1593:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1594:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1595:     $fname=&clean_filename($fname);
1.315     www      1596: # See if there is anything left
1.257     www      1597:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1598:     chop($env{'form.'.$formname});
1.523     raeburn  1599:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1600:         my $now = time;
                   1601:         my $filepath = 'tmp/helprequests/'.$now;
                   1602:         my @parts=split(/\//,$filepath);
                   1603:         my $fullpath = $perlvar{'lonDaemons'};
                   1604:         for (my $i=0;$i<@parts;$i++) {
                   1605:             $fullpath .= '/'.$parts[$i];
                   1606:             if ((-e $fullpath)!=1) {
                   1607:                 mkdir($fullpath,0777);
                   1608:             }
                   1609:         }
                   1610:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1611:         print $fh $env{'form.'.$formname};
1.523     raeburn  1612:         close($fh);
1.741     raeburn  1613:         return $fullpath.'/'.$fname;
                   1614:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1615:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1616:                        '_'.$env{'user.domain'}.'/pending';
                   1617:         my @parts=split(/\//,$filepath);
                   1618:         my $fullpath = $perlvar{'lonDaemons'};
                   1619:         for (my $i=0;$i<@parts;$i++) {
                   1620:             $fullpath .= '/'.$parts[$i];
                   1621:             if ((-e $fullpath)!=1) {
                   1622:                 mkdir($fullpath,0777);
                   1623:             }
                   1624:         }
                   1625:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1626:         print $fh $env{'form.'.$formname};
                   1627:         close($fh);
                   1628:         return $fullpath.'/'.$fname;
1.523     raeburn  1629:     }
1.719     banghart 1630:     
1.258     www      1631: # Create the directory if not present
1.493     albertel 1632:     $fname="$subdir/$fname";
1.259     www      1633:     if ($coursedoc) {
1.638     albertel 1634: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1635: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1636:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1637:             return &finishuserfileupload($docuname,$docudom,
                   1638: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1639: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1640:         } else {
1.620     albertel 1641:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1642:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1643: 				       $fname,$formname,$parser,
                   1644: 				       $allfiles,$codebase);
1.481     raeburn  1645:         }
1.719     banghart 1646:     } elsif (defined($destuname)) {
                   1647:         my $docuname=$destuname;
                   1648:         my $docudom=$destudom;
1.860     raeburn  1649: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1650: 				     $parser,$allfiles,$codebase,
                   1651:                                      $thumbwidth,$thumbheight);
1.719     banghart 1652:         
1.259     www      1653:     } else {
1.638     albertel 1654:         my $docuname=$env{'user.name'};
                   1655:         my $docudom=$env{'user.domain'};
1.714     raeburn  1656:         if (exists($env{'form.group'})) {
                   1657:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1658:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1659:         }
1.860     raeburn  1660: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1661: 				     $parser,$allfiles,$codebase,
                   1662:                                      $thumbwidth,$thumbheight);
1.259     www      1663:     }
1.271     www      1664: }
                   1665: 
                   1666: sub finishuserfileupload {
1.860     raeburn  1667:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1668:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1669:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1670:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1671:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1672:     $file=$fname;
                   1673:     if ($fname=~m|/|) {
                   1674:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1675: 	$path.=$fnamepath.'/';
                   1676:     }
1.259     www      1677:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1678:     my $count;
                   1679:     for ($count=4;$count<=$#parts;$count++) {
                   1680:         $filepath.="/$parts[$count]";
                   1681:         if ((-e $filepath)!=1) {
                   1682: 	    mkdir($filepath,0777);
                   1683:         }
                   1684:     }
                   1685: # Save the file
                   1686:     {
1.701     albertel 1687: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1688: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1689: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1690: 	    return '/adm/notfound.html';
                   1691: 	}
                   1692: 	if (!print FH ($env{'form.'.$formname})) {
                   1693: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1694: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1695: 	    return '/adm/notfound.html';
                   1696: 	}
1.570     albertel 1697: 	close(FH);
1.258     www      1698:     }
1.637     raeburn  1699:     if ($parser eq 'parse') {
1.638     albertel 1700:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1701: 						   $codebase);
1.637     raeburn  1702:         unless ($parse_result eq 'ok') {
1.638     albertel 1703:             &logthis('Failed to parse '.$filepath.$file.
                   1704: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1705:         }
                   1706:     }
1.860     raeburn  1707:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1708:         my $input = $filepath.'/'.$file;
                   1709:         my $output = $filepath.'/'.'tn-'.$file;
                   1710:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1711:         system("convert -sample $thumbsize $input $output");
                   1712:         if (-e $filepath.'/'.'tn-'.$file) {
                   1713:             $fetchthumb  = 1; 
                   1714:         }
                   1715:     }
1.858     raeburn  1716:  
1.259     www      1717: # Notify homeserver to grep it
                   1718: #
1.638     albertel 1719:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1720:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1721:     if ($fetchresult eq 'ok') {
1.860     raeburn  1722:         if ($fetchthumb) {
                   1723:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1724:             if ($thumbresult ne 'ok') {
                   1725:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1726:                          $docuhome.': '.$thumbresult);
                   1727:             }
                   1728:         }
1.259     www      1729: #
1.258     www      1730: # Return the URL to it
1.494     albertel 1731:         return '/uploaded/'.$path.$file;
1.263     www      1732:     } else {
1.494     albertel 1733:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1734: 		 ': '.$fetchresult);
1.263     www      1735:         return '/adm/notfound.html';
1.858     raeburn  1736:     }
1.493     albertel 1737: }
                   1738: 
1.637     raeburn  1739: sub extract_embedded_items {
1.648     raeburn  1740:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1741:     my @state = ();
                   1742:     my %javafiles = (
                   1743:                       codebase => '',
                   1744:                       code => '',
                   1745:                       archive => ''
                   1746:                     );
                   1747:     my %mediafiles = (
                   1748:                       src => '',
                   1749:                       movie => '',
                   1750:                      );
1.648     raeburn  1751:     my $p;
                   1752:     if ($content) {
                   1753:         $p = HTML::LCParser->new($content);
                   1754:     } else {
                   1755:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1756:     }
1.641     albertel 1757:     while (my $t=$p->get_token()) {
1.640     albertel 1758: 	if ($t->[0] eq 'S') {
                   1759: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1760: 	    push(@state, $tagname);
1.648     raeburn  1761:             if (lc($tagname) eq 'allow') {
                   1762:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1763:             }
1.640     albertel 1764: 	    if (lc($tagname) eq 'img') {
                   1765: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1766: 	    }
1.886     albertel 1767: 	    if (lc($tagname) eq 'a') {
                   1768: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1769: 	    }
1.645     raeburn  1770:             if (lc($tagname) eq 'script') {
                   1771:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1772:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1773:                 } else {
                   1774:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1775:                 }
                   1776:             }
                   1777:             if (lc($tagname) eq 'link') {
                   1778:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1779:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1780:                 }
                   1781:             }
1.640     albertel 1782: 	    if (lc($tagname) eq 'object' ||
                   1783: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1784: 		foreach my $item (keys(%javafiles)) {
                   1785: 		    $javafiles{$item} = '';
                   1786: 		}
                   1787: 	    }
                   1788: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1789: 		my $name = lc($attr->{'name'});
                   1790: 		foreach my $item (keys(%javafiles)) {
                   1791: 		    if ($name eq $item) {
                   1792: 			$javafiles{$item} = $attr->{'value'};
                   1793: 			last;
                   1794: 		    }
                   1795: 		}
                   1796: 		foreach my $item (keys(%mediafiles)) {
                   1797: 		    if ($name eq $item) {
                   1798: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1799: 			last;
                   1800: 		    }
                   1801: 		}
                   1802: 	    }
                   1803: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1804: 		foreach my $item (keys(%javafiles)) {
                   1805: 		    if ($attr->{$item}) {
                   1806: 			$javafiles{$item} = $attr->{$item};
                   1807: 			last;
                   1808: 		    }
                   1809: 		}
                   1810: 		foreach my $item (keys(%mediafiles)) {
                   1811: 		    if ($attr->{$item}) {
                   1812: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1813: 			last;
                   1814: 		    }
                   1815: 		}
                   1816: 	    }
                   1817: 	} elsif ($t->[0] eq 'E') {
                   1818: 	    my ($tagname) = ($t->[1]);
                   1819: 	    if ($javafiles{'codebase'} ne '') {
                   1820: 		$javafiles{'codebase'} .= '/';
                   1821: 	    }  
                   1822: 	    if (lc($tagname) eq 'applet' ||
                   1823: 		lc($tagname) eq 'object' ||
                   1824: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1825: 		) {
                   1826: 		foreach my $item (keys(%javafiles)) {
                   1827: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1828: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1829: 			&add_filetype($allfiles,$file,$item);
                   1830: 		    }
                   1831: 		}
                   1832: 	    } 
                   1833: 	    pop @state;
                   1834: 	}
                   1835:     }
1.637     raeburn  1836:     return 'ok';
                   1837: }
                   1838: 
1.639     albertel 1839: sub add_filetype {
                   1840:     my ($allfiles,$file,$type)=@_;
                   1841:     if (exists($allfiles->{$file})) {
                   1842: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1843: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1844: 	}
                   1845:     } else {
                   1846: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1847:     }
                   1848: }
                   1849: 
1.493     albertel 1850: sub removeuploadedurl {
                   1851:     my ($url)=@_;
                   1852:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1853:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1854: }
                   1855: 
                   1856: sub removeuserfile {
                   1857:     my ($docuname,$docudom,$fname)=@_;
                   1858:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1859:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1860:     if ($result eq 'ok') {
                   1861:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1862:             my $metafile = $fname.'.meta';
                   1863:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1864: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1865:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1866:             my $sqlresult = 
1.823     albertel 1867:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1868:                                         'portfolio_metadata',$group,
                   1869:                                         'delete');
1.798     raeburn  1870:         }
                   1871:     }
                   1872:     return $result;
1.257     www      1873: }
1.15      www      1874: 
1.530     albertel 1875: sub mkdiruserfile {
                   1876:     my ($docuname,$docudom,$dir)=@_;
                   1877:     my $home=&homeserver($docuname,$docudom);
                   1878:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1879: }
                   1880: 
1.531     albertel 1881: sub renameuserfile {
                   1882:     my ($docuname,$docudom,$old,$new)=@_;
                   1883:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1884:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1885:                         &escape("$old").':'.&escape("$new"),$home);
                   1886:     if ($result eq 'ok') {
                   1887:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1888:             my $oldmeta = $old.'.meta';
                   1889:             my $newmeta = $new.'.meta';
                   1890:             my $metaresult = 
                   1891:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1892: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1893:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1894:             my $sqlresult = 
1.823     albertel 1895:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1896:                                         'portfolio_metadata',$group,
                   1897:                                         'delete');
1.798     raeburn  1898:         }
                   1899:     }
                   1900:     return $result;
1.531     albertel 1901: }
                   1902: 
1.14      www      1903: # ------------------------------------------------------------------------- Log
                   1904: 
                   1905: sub log {
                   1906:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1907:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1908: }
                   1909: 
                   1910: # ------------------------------------------------------------------ Course Log
1.352     www      1911: #
                   1912: # This routine flushes several buffers of non-mission-critical nature
                   1913: #
1.157     www      1914: 
                   1915: sub flushcourselogs {
1.352     www      1916:     &logthis('Flushing log buffers');
                   1917: #
                   1918: # course logs
                   1919: # This is a log of all transactions in a course, which can be used
                   1920: # for data mining purposes
                   1921: #
                   1922: # It also collects the courseid database, which lists last transaction
                   1923: # times and course titles for all courseids
                   1924: #
                   1925:     my %courseidbuffer=();
1.800     albertel 1926:     foreach my $crsid (keys %courselogs) {
1.352     www      1927:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1928: 		          &escape($courselogs{$crsid}),
                   1929: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1930: 	    delete $courselogs{$crsid};
                   1931:         } else {
                   1932:             &logthis('Failed to flush log buffer for '.$crsid);
                   1933:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1934:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1935:                         " exceeded maximum size, deleting.</font>");
                   1936:                delete $courselogs{$crsid};
                   1937:             }
1.352     www      1938:         }
                   1939:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1940:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1941: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1942:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1943:         } else {
                   1944:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1945: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1946:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1947:         }
1.191     harris41 1948:     }
1.352     www      1949: #
                   1950: # Write course id database (reverse lookup) to homeserver of courses 
                   1951: # Is used in pickcourse
                   1952: #
1.840     albertel 1953:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1954:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1955: 		     $crs_home);
1.352     www      1956:     }
                   1957: #
                   1958: # File accesses
                   1959: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1960: #
1.449     matthew  1961:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1962:         if ($entry =~ /___count$/) {
                   1963:             my ($dom,$name);
1.807     albertel 1964:             ($dom,$name,undef)=
1.811     albertel 1965: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1966:             if (! defined($dom) || $dom eq '' || 
                   1967:                 ! defined($name) || $name eq '') {
1.620     albertel 1968:                 my $cid = $env{'request.course.id'};
                   1969:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1970:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1971:             }
1.450     matthew  1972:             my $value = $accesshash{$entry};
                   1973:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1974:             my %temphash=($url => $value);
1.449     matthew  1975:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1976:             if ($result eq 'ok') {
                   1977:                 delete $accesshash{$entry};
                   1978:             } elsif ($result eq 'unknown_cmd') {
                   1979:                 # Target server has old code running on it.
1.450     matthew  1980:                 my %temphash=($entry => $value);
1.449     matthew  1981:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1982:                     delete $accesshash{$entry};
                   1983:                 }
                   1984:             }
                   1985:         } else {
1.811     albertel 1986:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1987:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1988:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1989:                 delete $accesshash{$entry};
                   1990:             }
1.185     www      1991:         }
1.191     harris41 1992:     }
1.352     www      1993: #
                   1994: # Roles
                   1995: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1996: #
1.800     albertel 1997:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1998:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1999: 	    split(/\:/,$entry);
                   2000:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2001:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2002:                 $rudom,$runame) eq 'ok') {
                   2003: 	    delete $userrolehash{$entry};
                   2004:         }
                   2005:     }
1.662     raeburn  2006: #
                   2007: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2008: #
                   2009:     my %domrolebuffer = ();
                   2010:     foreach my $entry (keys %domainrolehash) {
                   2011:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   2012:         if ($domrolebuffer{$rudom}) {
                   2013:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2014:                       '='.&escape($domainrolehash{$entry});
                   2015:         } else {
                   2016:             $domrolebuffer{$rudom}.=&escape($entry).
                   2017:                       '='.&escape($domainrolehash{$entry});
                   2018:         }
                   2019:         delete $domainrolehash{$entry};
                   2020:     }
                   2021:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2022: 	my %servers = &get_servers($dom,'library');
                   2023: 	foreach my $tryserver (keys(%servers)) {
                   2024: 	    unless (&reply('domroleput:'.$dom.':'.
                   2025: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2026: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2027: 	    }
1.662     raeburn  2028:         }
                   2029:     }
1.186     www      2030:     $dumpcount++;
1.157     www      2031: }
                   2032: 
                   2033: sub courselog {
                   2034:     my $what=shift;
1.158     www      2035:     $what=time.':'.$what;
1.620     albertel 2036:     unless ($env{'request.course.id'}) { return ''; }
                   2037:     $coursedombuf{$env{'request.course.id'}}=
                   2038:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2039:     $coursenumbuf{$env{'request.course.id'}}=
                   2040:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2041:     $coursehombuf{$env{'request.course.id'}}=
                   2042:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2043:     $coursedescrbuf{$env{'request.course.id'}}=
                   2044:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2045:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2046:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2047:     $courseownerbuf{$env{'request.course.id'}}=
                   2048:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2049:     $coursetypebuf{$env{'request.course.id'}}=
                   2050:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2051:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2052: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2053:     } else {
1.620     albertel 2054: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2055:     }
1.620     albertel 2056:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2057: 	&flushcourselogs();
                   2058:     }
1.158     www      2059: }
                   2060: 
                   2061: sub courseacclog {
                   2062:     my $fnsymb=shift;
1.620     albertel 2063:     unless ($env{'request.course.id'}) { return ''; }
                   2064:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2065:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2066:         $what.=':POST';
1.583     matthew  2067:         # FIXME: Probably ought to escape things....
1.800     albertel 2068: 	foreach my $key (keys(%env)) {
                   2069:             if ($key=~/^form\.(.*)/) {
                   2070: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2071:             }
1.191     harris41 2072:         }
1.583     matthew  2073:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2074:         # FIXME: We should not be depending on a form parameter that someone
                   2075:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2076:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2077:             $what.= ':POST';
                   2078:             # FIXME: Probably ought to escape things....
                   2079:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2080:                                  'crsdiscuss') {
1.620     albertel 2081:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2082:             }
                   2083:         }
1.158     www      2084:     }
                   2085:     &courselog($what);
1.149     www      2086: }
                   2087: 
1.185     www      2088: sub countacc {
                   2089:     my $url=&declutter(shift);
1.458     matthew  2090:     return if (! defined($url) || $url eq '');
1.620     albertel 2091:     unless ($env{'request.course.id'}) { return ''; }
                   2092:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2093:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2094:     $accesshash{$key}++;
1.185     www      2095: }
1.349     www      2096: 
1.361     www      2097: sub linklog {
                   2098:     my ($from,$to)=@_;
                   2099:     $from=&declutter($from);
                   2100:     $to=&declutter($to);
                   2101:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2102:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2103: }
                   2104:   
1.349     www      2105: sub userrolelog {
                   2106:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2107:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2108:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2109:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2110:         ($trole=~/^ta/)) {
1.350     www      2111:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2112:        $userrolehash
                   2113:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2114:                     =$tend.':'.$tstart;
1.662     raeburn  2115:     }
1.898   ! albertel 2116:     if (($env{'request.role'} =~ /dc\./) &&
        !          2117: 	(($trole=~/^au/) || ($trole=~/^in/) ||
        !          2118: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
        !          2119: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
        !          2120:        $userrolehash
        !          2121:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
        !          2122:                     =$tend.':'.$tstart;
        !          2123:     }
1.662     raeburn  2124:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2125:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2126:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2127:         ($trole=~/^sc/)) {
                   2128:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2129:        $domainrolehash
                   2130:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2131:                     = $tend.':'.$tstart;
                   2132:     }
1.898   ! albertel 2133:     &flushcourselogs();
1.351     www      2134: }
                   2135: 
                   2136: sub get_course_adv_roles {
                   2137:     my $cid=shift;
1.620     albertel 2138:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2139:     my %coursehash=&coursedescription($cid);
1.470     www      2140:     my %nothide=();
1.800     albertel 2141:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2142: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2143:     }
1.351     www      2144:     my %returnhash=();
                   2145:     my %dumphash=
                   2146:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2147:     my $now=time;
1.800     albertel 2148:     foreach my $entry (keys %dumphash) {
                   2149: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2150:         if (($tstart) && ($tstart<0)) { next; }
                   2151:         if (($tend) && ($tend<$now)) { next; }
                   2152:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2153:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2154: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2155: 	if ((&privileged($username,$domain)) && 
                   2156: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2157: 	if ($role eq 'cr') { next; }
1.351     www      2158:         my $key=&plaintext($role);
                   2159:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2160:         if ($returnhash{$key}) {
                   2161: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2162:         } else {
                   2163:             $returnhash{$key}=$username.':'.$domain;
                   2164:         }
1.400     www      2165:      }
                   2166:     return %returnhash;
                   2167: }
                   2168: 
                   2169: sub get_my_roles {
1.858     raeburn  2170:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2171:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2172:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2173:     my %dumphash;
                   2174:     if ($context eq 'userroles') { 
                   2175:         %dumphash = &dump('roles',$udom,$uname);
                   2176:     } else {
                   2177:         %dumphash=
1.400     www      2178:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2179:     }
1.400     www      2180:     my %returnhash=();
                   2181:     my $now=time;
1.800     albertel 2182:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2183:         my ($role,$tend,$tstart);
                   2184:         if ($context eq 'userroles') {
                   2185: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2186:         } else {
                   2187:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2188:         }
1.400     www      2189:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2190:         my $status = 'active';
                   2191:         if (($tend) && ($tend<$now)) {
                   2192:             $status = 'previous';
                   2193:         } 
                   2194:         if (($tstart) && ($now<$tstart)) {
                   2195:             $status = 'future';
                   2196:         }
                   2197:         if (ref($types) eq 'ARRAY') {
                   2198:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2199:                 next;
                   2200:             } 
                   2201:         } else {
                   2202:             if ($status ne 'active') {
                   2203:                 next;
                   2204:             }
                   2205:         }
1.867     raeburn  2206:         my ($rolecode,$username,$domain,$section,$area);
                   2207:         if ($context eq 'userroles') {
                   2208:             ($area,$rolecode) = split(/_/,$entry);
                   2209:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2210:         } else {
                   2211:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2212:         }
1.832     raeburn  2213:         if (ref($roledoms) eq 'ARRAY') {
                   2214:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2215:                 next;
                   2216:             }
                   2217:         }
                   2218:         if (ref($roles) eq 'ARRAY') {
                   2219:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2220:                 next;
                   2221:             }
1.867     raeburn  2222:         }
1.400     www      2223: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2224:     }
1.373     www      2225:     return %returnhash;
1.399     www      2226: }
                   2227: 
                   2228: # ----------------------------------------------------- Frontpage Announcements
                   2229: #
                   2230: #
                   2231: 
                   2232: sub postannounce {
                   2233:     my ($server,$text)=@_;
1.844     albertel 2234:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2235:     unless ($text=~/\w/) { $text=''; }
                   2236:     return &reply('setannounce:'.&escape($text),$server);
                   2237: }
                   2238: 
                   2239: sub getannounce {
1.448     albertel 2240: 
                   2241:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2242: 	my $announcement='';
1.800     albertel 2243: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2244: 	close($fh);
1.399     www      2245: 	if ($announcement=~/\w/) { 
                   2246: 	    return 
                   2247:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2248:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2249: 	} else {
                   2250: 	    return '';
                   2251: 	}
                   2252:     } else {
                   2253: 	return '';
                   2254:     }
1.351     www      2255: }
1.353     www      2256: 
                   2257: # ---------------------------------------------------------- Course ID routines
                   2258: # Deal with domain's nohist_courseid.db files
                   2259: #
                   2260: 
                   2261: sub courseidput {
                   2262:     my ($domain,$what,$coursehome)=@_;
                   2263:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2264: }
                   2265: 
                   2266: sub courseiddump {
1.791     raeburn  2267:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2268:     my %returnhash=();
1.355     www      2269:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2270:     my %libserv = &all_library();
                   2271:     foreach my $tryserver (keys(%libserv)) {
                   2272:         if ( (  $hostidflag == 1 
                   2273: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2274: 	     || (!defined($hostidflag)) ) {
                   2275: 
                   2276: 	    if ($domfilter eq ''
                   2277: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2278: 	        foreach my $line (
1.844     albertel 2279:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2280: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2281:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2282:                                $tryserver))) {
1.800     albertel 2283: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2284:                     if (($key) && ($value)) {
1.516     raeburn  2285: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2286:                     }
1.353     www      2287:                 }
                   2288:             }
                   2289:         }
                   2290:     }
                   2291:     return %returnhash;
                   2292: }
                   2293: 
1.658     raeburn  2294: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2295: 
                   2296: sub dcmailput {
1.685     raeburn  2297:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2298:     my $status = &Apache::lonnet::critical(
1.740     www      2299:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2300:        &escape($message),$server);
1.662     raeburn  2301:     return $status;
                   2302: }
                   2303: 
1.658     raeburn  2304: sub dcmaildump {
                   2305:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2306:     my %returnhash=();
1.846     albertel 2307: 
                   2308:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2309:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2310:                                                          &escape($enddate).':';
                   2311: 	my @esc_senders=map { &escape($_)} @$senders;
                   2312: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2313: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2314:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2315:             if (($key) && ($value)) {
                   2316:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2317:             }
                   2318:         }
                   2319:     }
                   2320:     return %returnhash;
                   2321: }
1.662     raeburn  2322: # ---------------------------------------------------------- Domain roles
                   2323: 
                   2324: sub get_domain_roles {
                   2325:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2326:     if (undef($startdate) || $startdate eq '') {
                   2327:         $startdate = '.';
                   2328:     }
                   2329:     if (undef($enddate) || $enddate eq '') {
                   2330:         $enddate = '.';
                   2331:     }
                   2332:     my $rolelist = join(':',@{$roles});
                   2333:     my %personnel = ();
1.841     albertel 2334: 
                   2335:     my %servers = &get_servers($dom,'library');
                   2336:     foreach my $tryserver (keys(%servers)) {
                   2337: 	%{$personnel{$tryserver}}=();
                   2338: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2339: 					    &escape($startdate).':'.
                   2340: 					    &escape($enddate).':'.
                   2341: 					    &escape($rolelist), $tryserver))) {
                   2342: 	    my ($key,$value) = split(/\=/,$line,2);
                   2343: 	    if (($key) && ($value)) {
                   2344: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2345: 	    }
                   2346: 	}
1.662     raeburn  2347:     }
                   2348:     return %personnel;
                   2349: }
1.658     raeburn  2350: 
1.149     www      2351: # ----------------------------------------------------------- Check out an item
                   2352: 
1.504     albertel 2353: sub get_first_access {
                   2354:     my ($type,$argsymb)=@_;
1.790     albertel 2355:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2356:     if ($argsymb) { $symb=$argsymb; }
                   2357:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2358:     if ($type eq 'map') {
                   2359: 	$res=&symbread($map);
                   2360:     } else {
                   2361: 	$res=$symb;
                   2362:     }
                   2363:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2364:     return $times{"$courseid\0$res"};
1.504     albertel 2365: }
                   2366: 
                   2367: sub set_first_access {
                   2368:     my ($type)=@_;
1.790     albertel 2369:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2370:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2371:     if ($type eq 'map') {
                   2372: 	$res=&symbread($map);
                   2373:     } else {
                   2374: 	$res=$symb;
                   2375:     }
                   2376:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2377:     if (!$firstaccess) {
1.588     albertel 2378: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2379:     }
                   2380:     return 'already_set';
1.504     albertel 2381: }
                   2382: 
1.149     www      2383: sub checkout {
                   2384:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2385:     my $now=time;
                   2386:     my $lonhost=$perlvar{'lonHostID'};
                   2387:     my $infostr=&escape(
1.234     www      2388:                  'CHECKOUTTOKEN&'.
1.149     www      2389:                  $tuname.'&'.
                   2390:                  $tudom.'&'.
                   2391:                  $tcrsid.'&'.
                   2392:                  $symb.'&'.
                   2393: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2394:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2395:     if ($token=~/^error\:/) { 
1.672     albertel 2396:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2397:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2398:                  "</font>");
                   2399:         return ''; 
                   2400:     }
                   2401: 
1.149     www      2402:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2403:     $token=~tr/a-z/A-Z/;
                   2404: 
1.153     www      2405:     my %infohash=('resource.0.outtoken' => $token,
                   2406:                   'resource.0.checkouttime' => $now,
                   2407:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2408: 
                   2409:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2410:        return '';
1.151     www      2411:     } else {
1.672     albertel 2412:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2413:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2414:                  "</font>");
1.149     www      2415:     }    
                   2416: 
                   2417:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2418:                          &escape('Checkout '.$infostr.' - '.
                   2419:                                                  $token)) ne 'ok') {
                   2420: 	return '';
1.151     www      2421:     } else {
1.672     albertel 2422:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2423:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2424:                  "</font>");
1.149     www      2425:     }
1.151     www      2426:     return $token;
1.149     www      2427: }
                   2428: 
                   2429: # ------------------------------------------------------------ Check in an item
                   2430: 
                   2431: sub checkin {
                   2432:     my $token=shift;
1.150     www      2433:     my $now=time;
                   2434:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2435:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2436:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2437:     $dtoken=~s/\W/\_/g;
1.234     www      2438:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2439:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2440: 
1.154     www      2441:     unless (($tuname) && ($tudom)) {
                   2442:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2443:         return '';
                   2444:     }
                   2445:     
                   2446:     unless (&allowed('mgr',$tcrsid)) {
                   2447:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2448:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2449:         return '';
                   2450:     }
                   2451: 
1.153     www      2452:     my %infohash=('resource.0.intoken' => $token,
                   2453:                   'resource.0.checkintime' => $now,
                   2454:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2455: 
                   2456:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2457:        return '';
                   2458:     }    
                   2459: 
                   2460:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2461:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2462: 	return '';
                   2463:     }
                   2464: 
                   2465:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2466: }
                   2467: 
                   2468: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2469: 
                   2470: sub expirespread {
                   2471:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2472:     my $cid=$env{'request.course.id'}; 
1.110     www      2473:     if ($cid) {
                   2474:        my $now=time;
                   2475:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2476:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2477:                             $env{'course.'.$cid.'.num'}.
1.110     www      2478: 	        	    ':nohist_expirationdates:'.
                   2479:                             &escape($key).'='.$now,
1.620     albertel 2480:                             $env{'course.'.$cid.'.home'})
1.110     www      2481:     }
                   2482:     return 'ok';
1.14      www      2483: }
                   2484: 
1.109     www      2485: # ----------------------------------------------------- Devalidate Spreadsheets
                   2486: 
                   2487: sub devalidate {
1.325     www      2488:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2489:     my $cid=$env{'request.course.id'}; 
1.109     www      2490:     if ($cid) {
1.391     matthew  2491:         # delete the stored spreadsheets for
                   2492:         # - the student level sheet of this user in course's homespace
                   2493:         # - the assessment level sheet for this resource 
                   2494:         #   for this user in user's homespace
1.553     albertel 2495: 	# - current conditional state info
1.325     www      2496: 	my $key=$uname.':'.$udom.':';
1.109     www      2497:         my $status=
1.299     matthew  2498: 	    &del('nohist_calculatedsheets',
1.391     matthew  2499: 		 [$key.'studentcalc:'],
1.620     albertel 2500: 		 $env{'course.'.$cid.'.domain'},
                   2501: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2502: 		.' '.
                   2503: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2504: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2505:         unless ($status eq 'ok ok') {
                   2506:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2507:                     $uname.' at '.$udom.' for '.
1.109     www      2508: 		    $symb.': '.$status);
1.133     albertel 2509:         }
1.553     albertel 2510: 	&delenv('user.state.'.$cid);
1.109     www      2511:     }
                   2512: }
                   2513: 
1.265     albertel 2514: sub get_scalar {
                   2515:     my ($string,$end) = @_;
                   2516:     my $value;
                   2517:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2518: 	$value = $1;
                   2519:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2520: 	$value = $1;
                   2521:     }
                   2522:     return &unescape($value);
                   2523: }
                   2524: 
                   2525: sub array2str {
                   2526:   my (@array) = @_;
                   2527:   my $result=&arrayref2str(\@array);
                   2528:   $result=~s/^__ARRAY_REF__//;
                   2529:   $result=~s/__END_ARRAY_REF__$//;
                   2530:   return $result;
                   2531: }
                   2532: 
1.204     albertel 2533: sub arrayref2str {
                   2534:   my ($arrayref) = @_;
1.265     albertel 2535:   my $result='__ARRAY_REF__';
1.204     albertel 2536:   foreach my $elem (@$arrayref) {
1.265     albertel 2537:     if(ref($elem) eq 'ARRAY') {
                   2538:       $result.=&arrayref2str($elem).'&';
                   2539:     } elsif(ref($elem) eq 'HASH') {
                   2540:       $result.=&hashref2str($elem).'&';
                   2541:     } elsif(ref($elem)) {
                   2542:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2543:     } else {
                   2544:       $result.=&escape($elem).'&';
                   2545:     }
                   2546:   }
                   2547:   $result=~s/\&$//;
1.265     albertel 2548:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2549:   return $result;
                   2550: }
                   2551: 
1.168     albertel 2552: sub hash2str {
1.204     albertel 2553:   my (%hash) = @_;
                   2554:   my $result=&hashref2str(\%hash);
1.265     albertel 2555:   $result=~s/^__HASH_REF__//;
                   2556:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2557:   return $result;
                   2558: }
                   2559: 
                   2560: sub hashref2str {
                   2561:   my ($hashref)=@_;
1.265     albertel 2562:   my $result='__HASH_REF__';
1.800     albertel 2563:   foreach my $key (sort(keys(%$hashref))) {
                   2564:     if (ref($key) eq 'ARRAY') {
                   2565:       $result.=&arrayref2str($key).'=';
                   2566:     } elsif (ref($key) eq 'HASH') {
                   2567:       $result.=&hashref2str($key).'=';
                   2568:     } elsif (ref($key)) {
1.265     albertel 2569:       $result.='=';
1.800     albertel 2570:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2571:     } else {
1.800     albertel 2572: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2573:     }
                   2574: 
1.800     albertel 2575:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2576:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2577:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2578:       $result.=&hashref2str($hashref->{$key}).'&';
                   2579:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2580:        $result.='&';
1.800     albertel 2581:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2582:     } else {
1.800     albertel 2583:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2584:     }
                   2585:   }
1.168     albertel 2586:   $result=~s/\&$//;
1.265     albertel 2587:   $result .= '__END_HASH_REF__';
1.168     albertel 2588:   return $result;
                   2589: }
                   2590: 
                   2591: sub str2hash {
1.265     albertel 2592:     my ($string)=@_;
                   2593:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2594:     return %$hash;
                   2595: }
                   2596: 
                   2597: sub str2hashref {
1.168     albertel 2598:   my ($string) = @_;
1.265     albertel 2599: 
                   2600:   my %hash;
                   2601: 
                   2602:   if($string !~ /^__HASH_REF__/) {
                   2603:       if (! ($string eq '' || !defined($string))) {
                   2604: 	  $hash{'error'}='Not hash reference';
                   2605:       }
                   2606:       return (\%hash, $string);
                   2607:   }
                   2608: 
                   2609:   $string =~ s/^__HASH_REF__//;
                   2610: 
                   2611:   while($string !~ /^__END_HASH_REF__/) {
                   2612:       #key
                   2613:       my $key='';
                   2614:       if($string =~ /^__HASH_REF__/) {
                   2615:           ($key, $string)=&str2hashref($string);
                   2616:           if(defined($key->{'error'})) {
                   2617:               $hash{'error'}='Bad data';
                   2618:               return (\%hash, $string);
                   2619:           }
                   2620:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2621:           ($key, $string)=&str2arrayref($string);
                   2622:           if($key->[0] eq 'Array reference error') {
                   2623:               $hash{'error'}='Bad data';
                   2624:               return (\%hash, $string);
                   2625:           }
                   2626:       } else {
                   2627:           $string =~ s/^(.*?)=//;
1.267     albertel 2628: 	  $key=&unescape($1);
1.265     albertel 2629:       }
                   2630:       $string =~ s/^=//;
                   2631: 
                   2632:       #value
                   2633:       my $value='';
                   2634:       if($string =~ /^__HASH_REF__/) {
                   2635:           ($value, $string)=&str2hashref($string);
                   2636:           if(defined($value->{'error'})) {
                   2637:               $hash{'error'}='Bad data';
                   2638:               return (\%hash, $string);
                   2639:           }
                   2640:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2641:           ($value, $string)=&str2arrayref($string);
                   2642:           if($value->[0] eq 'Array reference error') {
                   2643:               $hash{'error'}='Bad data';
                   2644:               return (\%hash, $string);
                   2645:           }
                   2646:       } else {
                   2647: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2648:       }
                   2649:       $string =~ s/^&//;
                   2650: 
                   2651:       $hash{$key}=$value;
1.204     albertel 2652:   }
1.265     albertel 2653: 
                   2654:   $string =~ s/^__END_HASH_REF__//;
                   2655: 
                   2656:   return (\%hash, $string);
1.204     albertel 2657: }
                   2658: 
                   2659: sub str2array {
1.265     albertel 2660:     my ($string)=@_;
                   2661:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2662:     return @$array;
                   2663: }
                   2664: 
                   2665: sub str2arrayref {
1.204     albertel 2666:   my ($string) = @_;
1.265     albertel 2667:   my @array;
                   2668: 
                   2669:   if($string !~ /^__ARRAY_REF__/) {
                   2670:       if (! ($string eq '' || !defined($string))) {
                   2671: 	  $array[0]='Array reference error';
                   2672:       }
                   2673:       return (\@array, $string);
                   2674:   }
                   2675: 
                   2676:   $string =~ s/^__ARRAY_REF__//;
                   2677: 
                   2678:   while($string !~ /^__END_ARRAY_REF__/) {
                   2679:       my $value='';
                   2680:       if($string =~ /^__HASH_REF__/) {
                   2681:           ($value, $string)=&str2hashref($string);
                   2682:           if(defined($value->{'error'})) {
                   2683:               $array[0] ='Array reference error';
                   2684:               return (\@array, $string);
                   2685:           }
                   2686:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2687:           ($value, $string)=&str2arrayref($string);
                   2688:           if($value->[0] eq 'Array reference error') {
                   2689:               $array[0] ='Array reference error';
                   2690:               return (\@array, $string);
                   2691:           }
                   2692:       } else {
                   2693: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2694:       }
                   2695:       $string =~ s/^&//;
                   2696: 
                   2697:       push(@array, $value);
1.191     harris41 2698:   }
1.265     albertel 2699: 
                   2700:   $string =~ s/^__END_ARRAY_REF__//;
                   2701: 
                   2702:   return (\@array, $string);
1.168     albertel 2703: }
                   2704: 
1.167     albertel 2705: # -------------------------------------------------------------------Temp Store
                   2706: 
1.168     albertel 2707: sub tmpreset {
                   2708:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2709:   if (!$symb) {
                   2710:     $symb=&symbread();
1.620     albertel 2711:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2712:   }
                   2713:   $symb=escape($symb);
                   2714: 
1.620     albertel 2715:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2716:   $namespace=~s/\//\_/g;
                   2717:   $namespace=~s/\W//g;
                   2718: 
1.620     albertel 2719:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2720:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2721:   if ($domain eq 'public' && $stuname eq 'public') {
                   2722:       $stuname=$ENV{'REMOTE_ADDR'};
                   2723:   }
1.168     albertel 2724:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2725:   my %hash;
                   2726:   if (tie(%hash,'GDBM_File',
                   2727: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2728: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2729:     foreach my $key (keys %hash) {
1.180     albertel 2730:       if ($key=~ /:$symb/) {
1.168     albertel 2731: 	delete($hash{$key});
                   2732:       }
                   2733:     }
                   2734:   }
                   2735: }
                   2736: 
1.167     albertel 2737: sub tmpstore {
1.168     albertel 2738:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2739: 
                   2740:   if (!$symb) {
                   2741:     $symb=&symbread();
1.620     albertel 2742:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2743:   }
                   2744:   $symb=escape($symb);
                   2745: 
                   2746:   if (!$namespace) {
                   2747:     # I don't think we would ever want to store this for a course.
                   2748:     # it seems this will only be used if we don't have a course.
1.620     albertel 2749:     #$namespace=$env{'request.course.id'};
1.168     albertel 2750:     #if (!$namespace) {
1.620     albertel 2751:       $namespace=$env{'request.state'};
1.168     albertel 2752:     #}
                   2753:   }
                   2754:   $namespace=~s/\//\_/g;
                   2755:   $namespace=~s/\W//g;
1.620     albertel 2756:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2757:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2758:   if ($domain eq 'public' && $stuname eq 'public') {
                   2759:       $stuname=$ENV{'REMOTE_ADDR'};
                   2760:   }
1.168     albertel 2761:   my $now=time;
                   2762:   my %hash;
                   2763:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2764:   if (tie(%hash,'GDBM_File',
                   2765: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2766: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2767:     $hash{"version:$symb"}++;
                   2768:     my $version=$hash{"version:$symb"};
                   2769:     my $allkeys=''; 
                   2770:     foreach my $key (keys(%$storehash)) {
                   2771:       $allkeys.=$key.':';
1.591     albertel 2772:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2773:     }
                   2774:     $hash{"$version:$symb:timestamp"}=$now;
                   2775:     $allkeys.='timestamp';
                   2776:     $hash{"$version:keys:$symb"}=$allkeys;
                   2777:     if (untie(%hash)) {
                   2778:       return 'ok';
                   2779:     } else {
                   2780:       return "error:$!";
                   2781:     }
                   2782:   } else {
                   2783:     return "error:$!";
                   2784:   }
                   2785: }
1.167     albertel 2786: 
1.168     albertel 2787: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2788: 
1.168     albertel 2789: sub tmprestore {
                   2790:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2791: 
1.168     albertel 2792:   if (!$symb) {
                   2793:     $symb=&symbread();
1.620     albertel 2794:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2795:   }
                   2796:   $symb=escape($symb);
                   2797: 
1.620     albertel 2798:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2799: 
1.620     albertel 2800:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2801:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2802:   if ($domain eq 'public' && $stuname eq 'public') {
                   2803:       $stuname=$ENV{'REMOTE_ADDR'};
                   2804:   }
1.168     albertel 2805:   my %returnhash;
                   2806:   $namespace=~s/\//\_/g;
                   2807:   $namespace=~s/\W//g;
                   2808:   my %hash;
                   2809:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2810:   if (tie(%hash,'GDBM_File',
                   2811: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2812: 	  &GDBM_READER(),0640)) {
1.168     albertel 2813:     my $version=$hash{"version:$symb"};
                   2814:     $returnhash{'version'}=$version;
                   2815:     my $scope;
                   2816:     for ($scope=1;$scope<=$version;$scope++) {
                   2817:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2818:       my @keys=split(/:/,$vkeys);
                   2819:       my $key;
                   2820:       $returnhash{"$scope:keys"}=$vkeys;
                   2821:       foreach $key (@keys) {
1.591     albertel 2822: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2823: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2824:       }
                   2825:     }
1.168     albertel 2826:     if (!(untie(%hash))) {
                   2827:       return "error:$!";
                   2828:     }
                   2829:   } else {
                   2830:     return "error:$!";
                   2831:   }
                   2832:   return %returnhash;
1.167     albertel 2833: }
                   2834: 
1.9       www      2835: # ----------------------------------------------------------------------- Store
                   2836: 
                   2837: sub store {
1.124     www      2838:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2839:     my $home='';
                   2840: 
1.168     albertel 2841:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2842: 
1.213     www      2843:     $symb=&symbclean($symb);
1.122     albertel 2844:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2845: 
1.620     albertel 2846:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2847:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2848: 
                   2849:     &devalidate($symb,$stuname,$domain);
1.109     www      2850: 
                   2851:     $symb=escape($symb);
1.187     www      2852:     if (!$namespace) { 
1.620     albertel 2853:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2854:           return ''; 
                   2855:        } 
                   2856:     }
1.620     albertel 2857:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2858: 
                   2859:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2860:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2861: 
1.12      www      2862:     my $namevalue='';
1.800     albertel 2863:     foreach my $key (keys(%$storehash)) {
                   2864:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2865:     }
1.12      www      2866:     $namevalue=~s/\&$//;
1.187     www      2867:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2868:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2869: }
                   2870: 
1.47      www      2871: # -------------------------------------------------------------- Critical Store
                   2872: 
                   2873: sub cstore {
1.124     www      2874:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2875:     my $home='';
                   2876: 
1.168     albertel 2877:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2878: 
1.213     www      2879:     $symb=&symbclean($symb);
1.122     albertel 2880:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2881: 
1.620     albertel 2882:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2883:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2884: 
                   2885:     &devalidate($symb,$stuname,$domain);
1.109     www      2886: 
                   2887:     $symb=escape($symb);
1.187     www      2888:     if (!$namespace) { 
1.620     albertel 2889:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2890:           return ''; 
                   2891:        } 
                   2892:     }
1.620     albertel 2893:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2894: 
                   2895:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2896:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2897: 
1.47      www      2898:     my $namevalue='';
1.800     albertel 2899:     foreach my $key (keys(%$storehash)) {
                   2900:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2901:     }
1.47      www      2902:     $namevalue=~s/\&$//;
1.187     www      2903:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2904:     return critical
                   2905:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2906: }
                   2907: 
1.9       www      2908: # --------------------------------------------------------------------- Restore
                   2909: 
                   2910: sub restore {
1.124     www      2911:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2912:     my $home='';
                   2913: 
1.168     albertel 2914:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2915: 
1.122     albertel 2916:     if (!$symb) {
                   2917:       unless ($symb=escape(&symbread())) { return ''; }
                   2918:     } else {
1.213     www      2919:       $symb=&escape(&symbclean($symb));
1.122     albertel 2920:     }
1.188     www      2921:     if (!$namespace) { 
1.620     albertel 2922:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2923:           return ''; 
                   2924:        } 
                   2925:     }
1.620     albertel 2926:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2927:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2928:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2929:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2930: 
1.12      www      2931:     my %returnhash=();
1.800     albertel 2932:     foreach my $line (split(/\&/,$answer)) {
                   2933: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2934:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2935:     }
1.75      www      2936:     my $version;
                   2937:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2938:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2939:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2940:        }
1.75      www      2941:     }
1.13      www      2942:     return %returnhash;
1.34      www      2943: }
                   2944: 
                   2945: # ---------------------------------------------------------- Course Description
                   2946: 
                   2947: sub coursedescription {
1.731     albertel 2948:     my ($courseid,$args)=@_;
1.34      www      2949:     $courseid=~s/^\///;
1.49      www      2950:     $courseid=~s/\_/\//g;
1.34      www      2951:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2952:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2953:     my $normalid=$cdomain.'_'.$cnum;
                   2954:     # need to always cache even if we get errors otherwise we keep 
                   2955:     # trying and trying and trying to get the course description.
                   2956:     my %envhash=();
                   2957:     my %returnhash=();
1.731     albertel 2958:     
                   2959:     my $expiretime=600;
                   2960:     if ($env{'request.course.id'} eq $normalid) {
                   2961: 	$expiretime=120;
                   2962:     }
                   2963: 
                   2964:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2965:     if (!$args->{'freshen_cache'}
                   2966: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2967: 	foreach my $key (keys(%env)) {
                   2968: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2969: 	    my ($setting) = $1;
                   2970: 	    $returnhash{$setting} = $env{$key};
                   2971: 	}
                   2972: 	return %returnhash;
                   2973:     }
                   2974: 
                   2975:     # get the data agin
                   2976:     if (!$args->{'one_time'}) {
                   2977: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2978:     }
1.811     albertel 2979: 
1.34      www      2980:     if ($chome ne 'no_host') {
1.302     albertel 2981:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2982:        if (!exists($returnhash{'con_lost'})) {
                   2983:            $returnhash{'home'}= $chome;
                   2984: 	   $returnhash{'domain'} = $cdomain;
                   2985: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2986:            if (!defined($returnhash{'type'})) {
                   2987:                $returnhash{'type'} = 'Course';
                   2988:            }
1.130     albertel 2989:            while (my ($name,$value) = each %returnhash) {
1.53      www      2990:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2991:            }
1.270     www      2992:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2993:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2994: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2995:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2996:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2997:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2998:        }
                   2999:     }
1.731     albertel 3000:     if (!$args->{'one_time'}) {
                   3001: 	&appenv(%envhash);
                   3002:     }
1.302     albertel 3003:     return %returnhash;
1.461     www      3004: }
                   3005: 
                   3006: # -------------------------------------------------See if a user is privileged
                   3007: 
                   3008: sub privileged {
                   3009:     my ($username,$domain)=@_;
                   3010:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3011: 			&homeserver($username,$domain));
                   3012:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3013:     my $now=time;
                   3014:     if ($rolesdump ne '') {
1.800     albertel 3015:         foreach my $entry (split(/&/,$rolesdump)) {
                   3016: 	    if ($entry!~/^rolesdef_/) {
                   3017: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3018: 		$area=~s/\_\w\w$//;
                   3019: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3020: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3021: 		    my $active=1;
                   3022: 		    if ($tend) {
                   3023: 			if ($tend<$now) { $active=0; }
                   3024: 		    }
                   3025: 		    if ($tstart) {
                   3026: 			if ($tstart>$now) { $active=0; }
                   3027: 		    }
                   3028: 		    if ($active) { return 1; }
                   3029: 		}
                   3030: 	    }
                   3031: 	}
                   3032:     }
                   3033:     return 0;
1.9       www      3034: }
1.1       albertel 3035: 
1.103     harris41 3036: # -------------------------------------------------------- Get user privileges
1.11      www      3037: 
                   3038: sub rolesinit {
                   3039:     my ($domain,$username,$authhost)=@_;
                   3040:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3041:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3042:     my %allroles=();
1.678     raeburn  3043:     my %allgroups=();   
1.11      www      3044:     my $now=time;
1.743     albertel 3045:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3046:     my $group_privs;
1.11      www      3047: 
                   3048:     if ($rolesdump ne '') {
1.800     albertel 3049:         foreach my $entry (split(/&/,$rolesdump)) {
                   3050: 	  if ($entry!~/^rolesdef_/) {
                   3051:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3052: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3053:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3054: 	    if ($role=~/^cr/) { 
1.807     albertel 3055: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3056: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3057: 		    ($tend,$tstart)=split('_',$trest);
                   3058: 		} else {
                   3059: 		    $trole=$role;
                   3060: 		}
1.678     raeburn  3061:             } elsif ($role =~ m|^gr/|) {
                   3062:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3063:                 ($trole,$group_privs) = split(/\//,$trole);
                   3064:                 $group_privs = &unescape($group_privs);
1.587     albertel 3065: 	    } else {
                   3066: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3067: 	    }
1.743     albertel 3068: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3069: 					 $username);
                   3070: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3071:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3072:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3073:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3074: 		my $spec=$trole.'.'.$area;
                   3075: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3076: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3077:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3078:                 } elsif ($trole eq 'gr') {
                   3079:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3080: 		} else {
1.567     raeburn  3081:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3082: 		}
1.12      www      3083:             }
1.662     raeburn  3084:           }
1.191     harris41 3085:         }
1.743     albertel 3086:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3087:         $userroles{'user.adv'}    = $adv;
                   3088: 	$userroles{'user.author'} = $author;
1.620     albertel 3089:         $env{'user.adv'}=$adv;
1.11      www      3090:     }
1.743     albertel 3091:     return \%userroles;  
1.11      www      3092: }
                   3093: 
1.567     raeburn  3094: sub set_arearole {
                   3095:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3096: # log the associated role with the area
                   3097:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3098:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3099: }
                   3100: 
                   3101: sub custom_roleprivs {
                   3102:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3103:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3104:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3105:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3106:         my ($rdummy,$roledef)=
                   3107:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3108:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3109:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3110:             if (defined($syspriv)) {
                   3111:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3112:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3113:             }
                   3114:             if ($tdomain ne '') {
                   3115:                 if (defined($dompriv)) {
                   3116:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3117:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3118:                 }
                   3119:                 if (($trest ne '') && (defined($coursepriv))) {
                   3120:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3121:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3122:                 }
                   3123:             }
                   3124:         }
                   3125:     }
                   3126: }
                   3127: 
1.678     raeburn  3128: sub group_roleprivs {
                   3129:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3130:     my $access = 1;
                   3131:     my $now = time;
                   3132:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3133:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3134:     if ($access) {
1.811     albertel 3135:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3136:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3137:     }
                   3138: }
1.567     raeburn  3139: 
                   3140: sub standard_roleprivs {
                   3141:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3142:     if (defined($pr{$trole.':s'})) {
                   3143:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3144:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3145:     }
                   3146:     if ($tdomain ne '') {
                   3147:         if (defined($pr{$trole.':d'})) {
                   3148:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3149:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3150:         }
                   3151:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3152:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3153:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3154:         }
                   3155:     }
                   3156: }
                   3157: 
                   3158: sub set_userprivs {
1.678     raeburn  3159:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3160:     my $author=0;
                   3161:     my $adv=0;
1.678     raeburn  3162:     my %grouproles = ();
                   3163:     if (keys(%{$allgroups}) > 0) {
                   3164:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3165:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3166:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3167:                 $trole = $1;
                   3168:                 $area = $2;
1.681     raeburn  3169:                 $sec = $3;
                   3170:                 $extendedarea = $area.$sec;
                   3171:                 if (exists($$allgroups{$area})) {
                   3172:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3173:                         my $spec = $trole.'.'.$extendedarea;
                   3174:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3175:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3176:                     }
                   3177:                 }
                   3178:             }
                   3179:         }
                   3180:     }
1.800     albertel 3181:     foreach my $group (keys(%grouproles)) {
                   3182:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3183:     }
1.800     albertel 3184:     foreach my $role (keys(%{$allroles})) {
                   3185:         my %thesepriv;
                   3186:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3187:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3188:             if ($item ne '') {
                   3189:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3190:                 if ($restrictions eq '') {
                   3191:                     $thesepriv{$privilege}='F';
                   3192:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3193:                     $thesepriv{$privilege}.=$restrictions;
                   3194:                 }
                   3195:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3196:             }
                   3197:         }
                   3198:         my $thesestr='';
1.800     albertel 3199:         foreach my $priv (keys(%thesepriv)) {
                   3200: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3201: 	}
                   3202:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3203:     }
                   3204:     return ($author,$adv);
                   3205: }
                   3206: 
1.12      www      3207: # --------------------------------------------------------------- get interface
                   3208: 
                   3209: sub get {
1.131     albertel 3210:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3211:    my $items='';
1.800     albertel 3212:    foreach my $item (@$storearr) {
                   3213:        $items.=&escape($item).'&';
1.191     harris41 3214:    }
1.12      www      3215:    $items=~s/\&$//;
1.620     albertel 3216:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3217:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3218:    my $uhome=&homeserver($uname,$udomain);
                   3219: 
1.133     albertel 3220:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3221:    my @pairs=split(/\&/,$rep);
1.273     albertel 3222:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3223:      return @pairs;
                   3224:    }
1.15      www      3225:    my %returnhash=();
1.42      www      3226:    my $i=0;
1.800     albertel 3227:    foreach my $item (@$storearr) {
                   3228:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3229:       $i++;
1.191     harris41 3230:    }
1.15      www      3231:    return %returnhash;
1.27      www      3232: }
                   3233: 
                   3234: # --------------------------------------------------------------- del interface
                   3235: 
                   3236: sub del {
1.133     albertel 3237:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3238:    my $items='';
1.800     albertel 3239:    foreach my $item (@$storearr) {
                   3240:        $items.=&escape($item).'&';
1.191     harris41 3241:    }
1.27      www      3242:    $items=~s/\&$//;
1.620     albertel 3243:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3244:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3245:    my $uhome=&homeserver($uname,$udomain);
                   3246: 
                   3247:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3248: }
                   3249: 
                   3250: # -------------------------------------------------------------- dump interface
                   3251: 
                   3252: sub dump {
1.755     albertel 3253:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3254:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3255:     if (!$uname) { $uname=$env{'user.name'}; }
                   3256:     my $uhome=&homeserver($uname,$udomain);
                   3257:     if ($regexp) {
                   3258: 	$regexp=&escape($regexp);
                   3259:     } else {
                   3260: 	$regexp='.';
                   3261:     }
                   3262:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3263:     my @pairs=split(/\&/,$rep);
                   3264:     my %returnhash=();
                   3265:     foreach my $item (@pairs) {
                   3266: 	my ($key,$value)=split(/=/,$item,2);
                   3267: 	$key = &unescape($key);
                   3268: 	next if ($key =~ /^error: 2 /);
                   3269: 	$returnhash{$key}=&thaw_unescape($value);
                   3270:     }
                   3271:     return %returnhash;
1.407     www      3272: }
                   3273: 
1.717     albertel 3274: # --------------------------------------------------------- dumpstore interface
                   3275: 
                   3276: sub dumpstore {
                   3277:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3278:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3279:    if (!$uname) { $uname=$env{'user.name'}; }
                   3280:    my $uhome=&homeserver($uname,$udomain);
                   3281:    if ($regexp) {
                   3282:        $regexp=&escape($regexp);
                   3283:    } else {
                   3284:        $regexp='.';
                   3285:    }
                   3286:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3287:    my @pairs=split(/\&/,$rep);
                   3288:    my %returnhash=();
                   3289:    foreach my $item (@pairs) {
                   3290:        my ($key,$value)=split(/=/,$item,2);
                   3291:        next if ($key =~ /^error: 2 /);
                   3292:        $returnhash{$key}=&thaw_unescape($value);
                   3293:    }
                   3294:    return %returnhash;
1.717     albertel 3295: }
                   3296: 
1.407     www      3297: # -------------------------------------------------------------- keys interface
                   3298: 
                   3299: sub getkeys {
                   3300:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3301:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3302:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3303:    my $uhome=&homeserver($uname,$udomain);
                   3304:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3305:    my @keyarray=();
1.800     albertel 3306:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3307:       next if ($key =~ /^error: 2 /);
1.800     albertel 3308:       push(@keyarray,&unescape($key));
1.407     www      3309:    }
                   3310:    return @keyarray;
1.318     matthew  3311: }
                   3312: 
1.319     matthew  3313: # --------------------------------------------------------------- currentdump
                   3314: sub currentdump {
1.328     matthew  3315:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3316:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3317:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3318:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3319:    my $uhome = &homeserver($sname,$sdom);
                   3320:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3321:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3322:    #
1.318     matthew  3323:    my %returnhash=();
1.319     matthew  3324:    #
                   3325:    if ($rep eq "unknown_cmd") { 
                   3326:        # an old lond will not know currentdump
                   3327:        # Do a dump and make it look like a currentdump
1.822     albertel 3328:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3329:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3330:        my %hash = @tmp;
                   3331:        @tmp=();
1.424     matthew  3332:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3333:    } else {
                   3334:        my @pairs=split(/\&/,$rep);
1.800     albertel 3335:        foreach my $pair (@pairs) {
                   3336:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3337:            my ($symb,$param) = split(/:/,$key);
                   3338:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3339:                                                         &thaw_unescape($value);
1.319     matthew  3340:        }
1.191     harris41 3341:    }
1.12      www      3342:    return %returnhash;
1.424     matthew  3343: }
                   3344: 
                   3345: sub convert_dump_to_currentdump{
                   3346:     my %hash = %{shift()};
                   3347:     my %returnhash;
                   3348:     # Code ripped from lond, essentially.  The only difference
                   3349:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3350:     # we might run in to problems with parameter names =~ /^v\./
                   3351:     while (my ($key,$value) = each(%hash)) {
                   3352:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3353: 	$symb  = &unescape($symb);
                   3354: 	$param = &unescape($param);
1.424     matthew  3355:         next if ($v eq 'version' || $symb eq 'keys');
                   3356:         next if (exists($returnhash{$symb}) &&
                   3357:                  exists($returnhash{$symb}->{$param}) &&
                   3358:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3359:         $returnhash{$symb}->{$param}=$value;
                   3360:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3361:     }
                   3362:     #
                   3363:     # Remove all of the keys in the hashes which keep track of
                   3364:     # the version of the parameter.
                   3365:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3366:         # use a foreach because we are going to delete from the hash.
                   3367:         foreach my $key (keys(%$param_hash)) {
                   3368:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3369:         }
                   3370:     }
                   3371:     return \%returnhash;
1.12      www      3372: }
                   3373: 
1.627     albertel 3374: # ------------------------------------------------------ critical inc interface
                   3375: 
                   3376: sub cinc {
                   3377:     return &inc(@_,'critical');
                   3378: }
                   3379: 
1.449     matthew  3380: # --------------------------------------------------------------- inc interface
                   3381: 
                   3382: sub inc {
1.627     albertel 3383:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3384:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3385:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3386:     my $uhome=&homeserver($uname,$udomain);
                   3387:     my $items='';
                   3388:     if (! ref($store)) {
                   3389:         # got a single value, so use that instead
                   3390:         $items = &escape($store).'=&';
                   3391:     } elsif (ref($store) eq 'SCALAR') {
                   3392:         $items = &escape($$store).'=&';        
                   3393:     } elsif (ref($store) eq 'ARRAY') {
                   3394:         $items = join('=&',map {&escape($_);} @{$store});
                   3395:     } elsif (ref($store) eq 'HASH') {
                   3396:         while (my($key,$value) = each(%{$store})) {
                   3397:             $items.= &escape($key).'='.&escape($value).'&';
                   3398:         }
                   3399:     }
                   3400:     $items=~s/\&$//;
1.627     albertel 3401:     if ($critical) {
                   3402: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3403:     } else {
                   3404: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3405:     }
1.449     matthew  3406: }
                   3407: 
1.12      www      3408: # --------------------------------------------------------------- put interface
                   3409: 
                   3410: sub put {
1.134     albertel 3411:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3412:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3413:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3414:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3415:    my $items='';
1.800     albertel 3416:    foreach my $item (keys(%$storehash)) {
                   3417:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3418:    }
1.12      www      3419:    $items=~s/\&$//;
1.134     albertel 3420:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3421: }
                   3422: 
1.631     albertel 3423: # ------------------------------------------------------------ newput interface
                   3424: 
                   3425: sub newput {
                   3426:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3427:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3428:    if (!$uname) { $uname=$env{'user.name'}; }
                   3429:    my $uhome=&homeserver($uname,$udomain);
                   3430:    my $items='';
                   3431:    foreach my $key (keys(%$storehash)) {
                   3432:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3433:    }
                   3434:    $items=~s/\&$//;
                   3435:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3436: }
                   3437: 
                   3438: # ---------------------------------------------------------  putstore interface
                   3439: 
1.524     raeburn  3440: sub putstore {
1.715     albertel 3441:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3442:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3443:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3444:    my $uhome=&homeserver($uname,$udomain);
                   3445:    my $items='';
1.715     albertel 3446:    foreach my $key (keys(%$storehash)) {
                   3447:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3448:    }
1.715     albertel 3449:    $items=~s/\&$//;
1.716     albertel 3450:    my $esc_symb=&escape($symb);
                   3451:    my $esc_v=&escape($version);
1.715     albertel 3452:    my $reply =
1.716     albertel 3453:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3454: 	      $uhome);
                   3455:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3456:        # gfall back to way things use to be done
1.715     albertel 3457:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3458: 			    $uname);
1.524     raeburn  3459:    }
1.715     albertel 3460:    return $reply;
                   3461: }
                   3462: 
                   3463: sub old_putstore {
1.716     albertel 3464:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3465:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3466:     if (!$uname) { $uname=$env{'user.name'}; }
                   3467:     my $uhome=&homeserver($uname,$udomain);
                   3468:     my %newstorehash;
1.800     albertel 3469:     foreach my $item (keys(%$storehash)) {
                   3470: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3471: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3472:     }
                   3473:     my $items='';
                   3474:     my %allitems = ();
1.800     albertel 3475:     foreach my $item (keys(%newstorehash)) {
                   3476: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3477: 	    my $key = $1.':keys:'.$2;
                   3478: 	    $allitems{$key} .= $3.':';
                   3479: 	}
1.800     albertel 3480: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3481:     }
1.800     albertel 3482:     foreach my $item (keys(%allitems)) {
                   3483: 	$allitems{$item} =~ s/\:$//;
                   3484: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3485:     }
                   3486:     $items=~s/\&$//;
                   3487:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3488: }
                   3489: 
1.47      www      3490: # ------------------------------------------------------ critical put interface
                   3491: 
                   3492: sub cput {
1.134     albertel 3493:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3494:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3495:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3496:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3497:    my $items='';
1.800     albertel 3498:    foreach my $item (keys(%$storehash)) {
                   3499:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3500:    }
1.47      www      3501:    $items=~s/\&$//;
1.134     albertel 3502:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3503: }
                   3504: 
                   3505: # -------------------------------------------------------------- eget interface
                   3506: 
                   3507: sub eget {
1.133     albertel 3508:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3509:    my $items='';
1.800     albertel 3510:    foreach my $item (@$storearr) {
                   3511:        $items.=&escape($item).'&';
1.191     harris41 3512:    }
1.12      www      3513:    $items=~s/\&$//;
1.620     albertel 3514:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3515:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3516:    my $uhome=&homeserver($uname,$udomain);
                   3517:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3518:    my @pairs=split(/\&/,$rep);
                   3519:    my %returnhash=();
1.42      www      3520:    my $i=0;
1.800     albertel 3521:    foreach my $item (@$storearr) {
                   3522:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3523:       $i++;
1.191     harris41 3524:    }
1.12      www      3525:    return %returnhash;
                   3526: }
                   3527: 
1.667     albertel 3528: # ------------------------------------------------------------ tmpput interface
                   3529: sub tmpput {
1.802     raeburn  3530:     my ($storehash,$server,$context)=@_;
1.667     albertel 3531:     my $items='';
1.800     albertel 3532:     foreach my $item (keys(%$storehash)) {
                   3533: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3534:     }
                   3535:     $items=~s/\&$//;
1.802     raeburn  3536:     if (defined($context)) {
                   3537:         $items .= ':'.&escape($context);
                   3538:     }
1.667     albertel 3539:     return &reply("tmpput:$items",$server);
                   3540: }
                   3541: 
                   3542: # ------------------------------------------------------------ tmpget interface
                   3543: sub tmpget {
1.688     albertel 3544:     my ($token,$server)=@_;
                   3545:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3546:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3547:     my %returnhash;
                   3548:     foreach my $item (split(/\&/,$rep)) {
                   3549: 	my ($key,$value)=split(/=/,$item);
                   3550: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3551:     }
                   3552:     return %returnhash;
                   3553: }
                   3554: 
1.688     albertel 3555: # ------------------------------------------------------------ tmpget interface
                   3556: sub tmpdel {
                   3557:     my ($token,$server)=@_;
                   3558:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3559:     return &reply("tmpdel:$token",$server);
                   3560: }
                   3561: 
1.765     albertel 3562: # -------------------------------------------------- portfolio access checking
                   3563: 
                   3564: sub portfolio_access {
1.766     albertel 3565:     my ($requrl) = @_;
1.765     albertel 3566:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3567:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3568:     if ($result) {
                   3569:         my %setters;
                   3570:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3571:             my ($startblock,$endblock) =
                   3572:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3573:             if ($startblock && $endblock) {
                   3574:                 return 'B';
                   3575:             }
                   3576:         } else {
                   3577:             my ($startblock,$endblock) =
                   3578:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3579:             if ($startblock && $endblock) {
                   3580:                 return 'B';
                   3581:             }
                   3582:         }
                   3583:     }
1.765     albertel 3584:     if ($result eq 'ok') {
1.766     albertel 3585:        return 'F';
1.765     albertel 3586:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3587:        return 'A';
1.765     albertel 3588:     }
1.766     albertel 3589:     return '';
1.765     albertel 3590: }
                   3591: 
                   3592: sub get_portfolio_access {
1.767     albertel 3593:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3594: 
                   3595:     if (!ref($access_hash)) {
                   3596: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3597: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3598: 						   $file_name);
                   3599: 	$access_hash = $access_controls{$file_name};
                   3600:     }
                   3601: 
1.765     albertel 3602:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3603:     my $now = time;
                   3604:     if (ref($access_hash) eq 'HASH') {
                   3605:         foreach my $key (keys(%{$access_hash})) {
                   3606:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3607:             if ($start > $now) {
                   3608:                 next;
                   3609:             }
                   3610:             if ($end && $end<$now) {
                   3611:                 next;
                   3612:             }
                   3613:             if ($scope eq 'public') {
                   3614:                 $public = $key;
                   3615:                 last;
                   3616:             } elsif ($scope eq 'guest') {
                   3617:                 $guest = $key;
                   3618:             } elsif ($scope eq 'domains') {
                   3619:                 push(@domains,$key);
                   3620:             } elsif ($scope eq 'users') {
                   3621:                 push(@users,$key);
                   3622:             } elsif ($scope eq 'course') {
                   3623:                 push(@courses,$key);
                   3624:             } elsif ($scope eq 'group') {
                   3625:                 push(@groups,$key);
                   3626:             }
                   3627:         }
                   3628:         if ($public) {
                   3629:             return 'ok';
                   3630:         }
                   3631:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3632:             if ($guest) {
                   3633:                 return $guest;
                   3634:             }
                   3635:         } else {
                   3636:             if (@domains > 0) {
                   3637:                 foreach my $domkey (@domains) {
                   3638:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3639:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3640:                             return 'ok';
                   3641:                         }
                   3642:                     }
                   3643:                 }
                   3644:             }
                   3645:             if (@users > 0) {
                   3646:                 foreach my $userkey (@users) {
1.865     raeburn  3647:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3648:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3649:                             if (ref($item) eq 'HASH') {
                   3650:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3651:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3652:                                     return 'ok';
                   3653:                                 }
                   3654:                             }
                   3655:                         }
                   3656:                     } 
1.765     albertel 3657:                 }
                   3658:             }
                   3659:             my %roleshash;
                   3660:             my @courses_and_groups = @courses;
                   3661:             push(@courses_and_groups,@groups); 
                   3662:             if (@courses_and_groups > 0) {
                   3663:                 my (%allgroups,%allroles); 
                   3664:                 my ($start,$end,$role,$sec,$group);
                   3665:                 foreach my $envkey (%env) {
1.811     albertel 3666:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3667:                         my $cid = $2.'_'.$3; 
                   3668:                         if ($1 eq 'gr') {
                   3669:                             $group = $4;
                   3670:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3671:                         } else {
                   3672:                             if ($4 eq '') {
                   3673:                                 $sec = 'none';
                   3674:                             } else {
                   3675:                                 $sec = $4;
                   3676:                             }
                   3677:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3678:                         }
1.811     albertel 3679:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3680:                         my $cid = $2.'_'.$3;
                   3681:                         if ($4 eq '') {
                   3682:                             $sec = 'none';
                   3683:                         } else {
                   3684:                             $sec = $4;
                   3685:                         }
                   3686:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3687:                     }
                   3688:                 }
                   3689:                 if (keys(%allroles) == 0) {
                   3690:                     return;
                   3691:                 }
                   3692:                 foreach my $key (@courses_and_groups) {
                   3693:                     my %content = %{$$access_hash{$key}};
                   3694:                     my $cnum = $content{'number'};
                   3695:                     my $cdom = $content{'domain'};
                   3696:                     my $cid = $cdom.'_'.$cnum;
                   3697:                     if (!exists($allroles{$cid})) {
                   3698:                         next;
                   3699:                     }    
                   3700:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3701:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3702:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3703:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3704:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3705:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3706:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3707:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3708:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3709:                                         if (grep/^all$/,@sections) {
                   3710:                                             return 'ok';
                   3711:                                         } else {
                   3712:                                             if (grep/^$sec$/,@sections) {
                   3713:                                                 return 'ok';
                   3714:                                             }
                   3715:                                         }
                   3716:                                     }
                   3717:                                 }
                   3718:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3719:                                     if (grep/^none$/,@groups) {
                   3720:                                         return 'ok';
                   3721:                                     }
                   3722:                                 } else {
                   3723:                                     if (grep/^all$/,@groups) {
                   3724:                                         return 'ok';
                   3725:                                     } 
                   3726:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3727:                                         if (grep/^$group$/,@groups) {
                   3728:                                             return 'ok';
                   3729:                                         }
                   3730:                                     }
                   3731:                                 } 
                   3732:                             }
                   3733:                         }
                   3734:                     }
                   3735:                 }
                   3736:             }
                   3737:             if ($guest) {
                   3738:                 return $guest;
                   3739:             }
                   3740:         }
                   3741:     }
                   3742:     return;
                   3743: }
                   3744: 
                   3745: sub course_group_datechecker {
                   3746:     my ($dates,$now,$status) = @_;
                   3747:     my ($start,$end) = split(/\./,$dates);
                   3748:     if (!$start && !$end) {
                   3749:         return 'ok';
                   3750:     }
                   3751:     if (grep/^active$/,@{$status}) {
                   3752:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3753:             return 'ok';
                   3754:         }
                   3755:     }
                   3756:     if (grep/^previous$/,@{$status}) {
                   3757:         if ($end > $now ) {
                   3758:             return 'ok';
                   3759:         }
                   3760:     }
                   3761:     if (grep/^future$/,@{$status}) {
                   3762:         if ($start > $now) {
                   3763:             return 'ok';
                   3764:         }
                   3765:     }
                   3766:     return; 
                   3767: }
                   3768: 
                   3769: sub parse_portfolio_url {
                   3770:     my ($url) = @_;
                   3771: 
                   3772:     my ($type,$udom,$unum,$group,$file_name);
                   3773:     
1.823     albertel 3774:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3775: 	$type = 1;
                   3776:         $udom = $1;
                   3777:         $unum = $2;
                   3778:         $file_name = $3;
1.823     albertel 3779:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3780: 	$type = 2;
                   3781:         $udom = $1;
                   3782:         $unum = $2;
                   3783:         $group = $3;
                   3784:         $file_name = $3.'/'.$4;
                   3785:     }
                   3786:     if (wantarray) {
                   3787: 	return ($type,$udom,$unum,$file_name,$group);
                   3788:     }
                   3789:     return $type;
                   3790: }
                   3791: 
                   3792: sub is_portfolio_url {
                   3793:     my ($url) = @_;
                   3794:     return scalar(&parse_portfolio_url($url));
                   3795: }
                   3796: 
1.798     raeburn  3797: sub is_portfolio_file {
                   3798:     my ($file) = @_;
1.820     raeburn  3799:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3800:         return 1;
                   3801:     }
                   3802:     return;
                   3803: }
                   3804: 
                   3805: 
1.341     www      3806: # ---------------------------------------------- Custom access rule evaluation
                   3807: 
                   3808: sub customaccess {
                   3809:     my ($priv,$uri)=@_;
1.807     albertel 3810:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3811:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3812:     $udom = &LONCAPA::clean_domain($udom);
                   3813:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3814:     my $access=0;
1.800     albertel 3815:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 3816: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   3817: 	if ($type eq 'user') {
                   3818: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 3819: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 3820: 		if ($tdom) {
                   3821: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   3822: 		}
1.896     albertel 3823: 		if ($tuname) {
                   3824: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 3825: 		}
                   3826: 		$access=($effect eq 'allow');
                   3827: 		last;
                   3828: 	    }
                   3829: 	} else {
                   3830: 	    if ($role) {
                   3831: 		if ($role ne $urole) { next; }
                   3832: 	    }
                   3833: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3834: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   3835: 		if ($tdom) {
                   3836: 		    if ($tdom ne $udom) { next; }
                   3837: 		}
                   3838: 		if ($tcrs) {
                   3839: 		    if ($tcrs ne $ucrs) { next; }
                   3840: 		}
                   3841: 		if ($tsec) {
                   3842: 		    if ($tsec ne $usec) { next; }
                   3843: 		}
                   3844: 		$access=($effect eq 'allow');
                   3845: 		last;
                   3846: 	    }
                   3847: 	    if ($realm eq '' && $role eq '') {
                   3848: 		$access=($effect eq 'allow');
                   3849: 	    }
1.402     bowersj2 3850: 	}
1.341     www      3851:     }
                   3852:     return $access;
                   3853: }
                   3854: 
1.103     harris41 3855: # ------------------------------------------------- Check for a user privilege
1.12      www      3856: 
                   3857: sub allowed {
1.810     raeburn  3858:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3859:     my $ver_orguri=$uri;
1.439     www      3860:     $uri=&deversion($uri);
1.152     www      3861:     my $orguri=$uri;
1.52      www      3862:     $uri=&declutter($uri);
1.809     raeburn  3863: 
1.810     raeburn  3864:     if ($priv eq 'evb') {
                   3865: # Evade communication block restrictions for specified role in a course
                   3866:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3867:             return $1;
                   3868:         } else {
                   3869:             return;
                   3870:         }
                   3871:     }
                   3872: 
1.620     albertel 3873:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3874: # Free bre access to adm and meta resources
1.775     albertel 3875:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3876: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3877: 	&& ($priv eq 'bre')) {
1.14      www      3878: 	return 'F';
1.159     www      3879:     }
                   3880: 
1.545     banghart 3881: # Free bre access to user's own portfolio contents
1.714     raeburn  3882:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3883:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3884: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3885:         my %setters;
                   3886:         my ($startblock,$endblock) = 
                   3887:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3888:         if ($startblock && $endblock) {
                   3889:             return 'B';
                   3890:         } else {
                   3891:             return 'F';
                   3892:         }
1.545     banghart 3893:     }
                   3894: 
1.762     raeburn  3895: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3896:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3897:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3898:         if (exists($env{'request.course.id'})) {
                   3899:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3900:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3901:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3902:                 my $courseprivid=$env{'request.course.id'};
                   3903:                 $courseprivid=~s/\_/\//;
                   3904:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3905:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3906:                     return $1; 
1.762     raeburn  3907:                 } else {
                   3908:                     if ($env{'request.course.sec'}) {
                   3909:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3910:                     }
                   3911:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3912:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3913:                         return $2;
                   3914:                     }
1.714     raeburn  3915:                 }
                   3916:             }
                   3917:         }
                   3918:     }
                   3919: 
1.159     www      3920: # Free bre to public access
                   3921: 
                   3922:     if ($priv eq 'bre') {
1.238     www      3923:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3924: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3925:            return 'F'; 
                   3926:         }
1.238     www      3927:         if ($copyright eq 'priv') {
                   3928:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3929: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3930: 		return '';
                   3931:             }
                   3932:         }
                   3933:         if ($copyright eq 'domain') {
                   3934:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3935: 	    unless (($env{'user.domain'} eq $1) ||
                   3936:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3937: 		return '';
                   3938:             }
1.262     matthew  3939:         }
1.620     albertel 3940:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3941:             # Library role, so allow browsing of resources in this domain.
                   3942:             return 'F';
1.238     www      3943:         }
1.341     www      3944:         if ($copyright eq 'custom') {
                   3945: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3946:         }
1.14      www      3947:     }
1.264     matthew  3948:     # Domain coordinator is trying to create a course
1.620     albertel 3949:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3950:         # uri is the requested domain in this case.
                   3951:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3952:         # a role of dc for the domain in question.
1.620     albertel 3953:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3954:     }
1.29      www      3955: 
1.52      www      3956:     my $thisallowed='';
                   3957:     my $statecond=0;
                   3958:     my $courseprivid='';
                   3959: 
                   3960: # Course
                   3961: 
1.620     albertel 3962:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3963:        $thisallowed.=$1;
                   3964:     }
1.29      www      3965: 
1.52      www      3966: # Domain
                   3967: 
1.620     albertel 3968:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3969:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3970:        $thisallowed.=$1;
                   3971:     }
1.52      www      3972: 
                   3973: # Course: uri itself is a course
1.66      www      3974:     my $courseuri=$uri;
                   3975:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3976:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3977: 
1.620     albertel 3978:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3979:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3980:        $thisallowed.=$1;
                   3981:     }
1.29      www      3982: 
1.665     albertel 3983: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3984: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3985:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3986: 	$thisallowed='';
1.671     raeburn  3987:         my ($match)=&is_on_map($uri);
                   3988:         if ($match) {
                   3989:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3990:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3991:                 $thisallowed.=$1;
                   3992:             }
                   3993:         } else {
1.705     albertel 3994:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3995:             if ($refuri) {
                   3996:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3997:                     $thisallowed='F';
1.671     raeburn  3998:                 } else {
                   3999:                     $refuri=&declutter($refuri);
                   4000:                     my ($match) = &is_on_map($refuri);
                   4001:                     if ($match) {
                   4002:                         $thisallowed='F';
                   4003:                     }
1.669     raeburn  4004:                 }
1.671     raeburn  4005:             }
                   4006:         }
1.314     www      4007:     }
1.492     albertel 4008: 
1.766     albertel 4009:     if ($priv eq 'bre'
                   4010: 	&& $thisallowed ne 'F' 
                   4011: 	&& $thisallowed ne '2'
                   4012: 	&& &is_portfolio_url($uri)) {
                   4013: 	$thisallowed = &portfolio_access($uri);
                   4014:     }
                   4015:     
1.52      www      4016: # Full access at system, domain or course-wide level? Exit.
1.29      www      4017: 
                   4018:     if ($thisallowed=~/F/) {
                   4019: 	return 'F';
                   4020:     }
                   4021: 
1.52      www      4022: # If this is generating or modifying users, exit with special codes
1.29      www      4023: 
1.643     www      4024:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4025: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4026: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4027: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4028: 	    unless ($auname) { return $thisallowed; }
                   4029: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4030: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4031: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4032: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4033: 	}
1.52      www      4034: 	return $thisallowed;
                   4035:     }
                   4036: #
1.103     harris41 4037: # Gathered so far: system, domain and course wide privileges
1.52      www      4038: #
                   4039: # Course: See if uri or referer is an individual resource that is part of 
                   4040: # the course
                   4041: 
1.620     albertel 4042:     if ($env{'request.course.id'}) {
1.232     www      4043: 
1.620     albertel 4044:        $courseprivid=$env{'request.course.id'};
                   4045:        if ($env{'request.course.sec'}) {
                   4046:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4047:        }
                   4048:        $courseprivid=~s/\_/\//;
                   4049:        my $checkreferer=1;
1.232     www      4050:        my ($match,$cond)=&is_on_map($uri);
                   4051:        if ($match) {
                   4052:            $statecond=$cond;
1.620     albertel 4053:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4054:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4055:                $thisallowed.=$1;
                   4056:                $checkreferer=0;
                   4057:            }
1.29      www      4058:        }
1.83      www      4059:        
1.148     www      4060:        if ($checkreferer) {
1.620     albertel 4061: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4062:             unless ($refuri) {
1.800     albertel 4063:                 foreach my $key (keys(%env)) {
                   4064: 		    if ($key=~/^httpref\..*\*/) {
                   4065: 			my $pattern=$key;
1.156     www      4066:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4067:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4068:                         $pattern=~s/\//\\\//g;
1.152     www      4069:                         if ($orguri=~/$pattern/) {
1.800     albertel 4070: 			    $refuri=$env{$key};
1.148     www      4071:                         }
                   4072:                     }
1.191     harris41 4073:                 }
1.148     www      4074:             }
1.232     www      4075: 
1.148     www      4076:          if ($refuri) { 
1.152     www      4077: 	  $refuri=&declutter($refuri);
1.232     www      4078:           my ($match,$cond)=&is_on_map($refuri);
                   4079:             if ($match) {
                   4080:               my $refstatecond=$cond;
1.620     albertel 4081:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4082:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4083:                   $thisallowed.=$1;
1.53      www      4084:                   $uri=$refuri;
                   4085:                   $statecond=$refstatecond;
1.52      www      4086:               }
                   4087:           }
1.148     www      4088:         }
1.29      www      4089:        }
1.52      www      4090:    }
1.29      www      4091: 
1.52      www      4092: #
1.103     harris41 4093: # Gathered now: all privileges that could apply, and condition number
1.52      www      4094: # 
                   4095: #
                   4096: # Full or no access?
                   4097: #
1.29      www      4098: 
1.52      www      4099:     if ($thisallowed=~/F/) {
                   4100: 	return 'F';
                   4101:     }
1.29      www      4102: 
1.52      www      4103:     unless ($thisallowed) {
                   4104:         return '';
                   4105:     }
1.29      www      4106: 
1.52      www      4107: # Restrictions exist, deal with them
                   4108: #
                   4109: #   C:according to course preferences
                   4110: #   R:according to resource settings
                   4111: #   L:unless locked
                   4112: #   X:according to user session state
                   4113: #
                   4114: 
                   4115: # Possibly locked functionality, check all courses
1.54      www      4116: # Locks might take effect only after 10 minutes cache expiration for other
                   4117: # courses, and 2 minutes for current course
1.52      www      4118: 
                   4119:     my $envkey;
                   4120:     if ($thisallowed=~/L/) {
1.620     albertel 4121:         foreach $envkey (keys %env) {
1.54      www      4122:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4123:                my $courseid=$2;
                   4124:                my $roleid=$1.'.'.$2;
1.92      www      4125:                $courseid=~s/^\///;
1.54      www      4126:                my $expiretime=600;
1.620     albertel 4127:                if ($env{'request.role'} eq $roleid) {
1.54      www      4128: 		  $expiretime=120;
                   4129:                }
                   4130: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4131:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4132:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4133: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4134:                }
1.620     albertel 4135:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4136:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4137: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4138:                        &log($env{'user.domain'},$env{'user.name'},
                   4139:                             $env{'user.home'},
1.57      www      4140:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4141:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4142:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4143: 		       return '';
                   4144:                    }
                   4145:                }
1.620     albertel 4146:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4147:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4148: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4149:                        &log($env{'user.domain'},$env{'user.name'},
                   4150:                             $env{'user.home'},
1.57      www      4151:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4152:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4153:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4154: 		       return '';
                   4155:                    }
                   4156:                }
                   4157: 	   }
1.29      www      4158:        }
1.52      www      4159:     }
                   4160:    
                   4161: #
                   4162: # Rest of the restrictions depend on selected course
                   4163: #
                   4164: 
1.620     albertel 4165:     unless ($env{'request.course.id'}) {
1.766     albertel 4166: 	if ($thisallowed eq 'A') {
                   4167: 	    return 'A';
1.814     raeburn  4168:         } elsif ($thisallowed eq 'B') {
                   4169:             return 'B';
1.766     albertel 4170: 	} else {
                   4171: 	    return '1';
                   4172: 	}
1.52      www      4173:     }
1.29      www      4174: 
1.52      www      4175: #
                   4176: # Now user is definitely in a course
                   4177: #
1.53      www      4178: 
                   4179: 
                   4180: # Course preferences
                   4181: 
                   4182:    if ($thisallowed=~/C/) {
1.620     albertel 4183:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4184:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4185:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4186: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4187: 	   if ($priv ne 'pch') { 
                   4188: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4189: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4190: 			$env{'request.course.id'});
                   4191: 	   }
1.237     www      4192:            return '';
                   4193:        }
                   4194: 
1.620     albertel 4195:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4196: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4197: 	   if ($priv ne 'pch') { 
                   4198: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4199: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4200: 			$env{'request.course.id'});
                   4201: 	   }
1.54      www      4202:            return '';
                   4203:        }
1.53      www      4204:    }
                   4205: 
                   4206: # Resource preferences
                   4207: 
                   4208:    if ($thisallowed=~/R/) {
1.620     albertel 4209:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4210:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4211: 	   if ($priv ne 'pch') { 
                   4212: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4213: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4214: 	   }
                   4215: 	   return '';
1.54      www      4216:        }
1.53      www      4217:    }
1.30      www      4218: 
1.246     www      4219: # Restricted by state or randomout?
1.30      www      4220: 
1.52      www      4221:    if ($thisallowed=~/X/) {
1.620     albertel 4222:       if ($env{'acc.randomout'}) {
1.579     albertel 4223: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4224:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4225:             return ''; 
                   4226:          }
1.247     www      4227:       }
                   4228:       if (&condval($statecond)) {
1.52      www      4229: 	 return '2';
                   4230:       } else {
                   4231:          return '';
                   4232:       }
                   4233:    }
1.30      www      4234: 
1.766     albertel 4235:     if ($thisallowed eq 'A') {
                   4236: 	return 'A';
1.814     raeburn  4237:     } elsif ($thisallowed eq 'B') {
                   4238:         return 'B';
1.766     albertel 4239:     }
1.52      www      4240:    return 'F';
1.232     www      4241: }
                   4242: 
1.710     albertel 4243: sub split_uri_for_cond {
                   4244:     my $uri=&deversion(&declutter(shift));
                   4245:     my @uriparts=split(/\//,$uri);
                   4246:     my $filename=pop(@uriparts);
                   4247:     my $pathname=join('/',@uriparts);
                   4248:     return ($pathname,$filename);
                   4249: }
1.232     www      4250: # --------------------------------------------------- Is a resource on the map?
                   4251: 
                   4252: sub is_on_map {
1.710     albertel 4253:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4254:     #Trying to find the conditional for the file
1.620     albertel 4255:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4256: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4257:     if ($match) {
1.289     bowersj2 4258: 	return (1,$1);
                   4259:     } else {
1.434     www      4260: 	return (0,0);
1.289     bowersj2 4261:     }
1.12      www      4262: }
                   4263: 
1.427     www      4264: # --------------------------------------------------------- Get symb from alias
                   4265: 
                   4266: sub get_symb_from_alias {
                   4267:     my $symb=shift;
                   4268:     my ($map,$resid,$url)=&decode_symb($symb);
                   4269: # Already is a symb
                   4270:     if ($url) { return $symb; }
                   4271: # Must be an alias
                   4272:     my $aliassymb='';
                   4273:     my %bighash;
1.620     albertel 4274:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4275:                             &GDBM_READER(),0640)) {
                   4276:         my $rid=$bighash{'mapalias_'.$symb};
                   4277: 	if ($rid) {
                   4278: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4279: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4280: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4281: 	}
                   4282:         untie %bighash;
                   4283:     }
                   4284:     return $aliassymb;
                   4285: }
                   4286: 
1.12      www      4287: # ----------------------------------------------------------------- Define Role
                   4288: 
                   4289: sub definerole {
                   4290:   if (allowed('mcr','/')) {
                   4291:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4292:     foreach my $role (split(':',$sysrole)) {
                   4293: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4294:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4295:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4296: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4297:                return "refused:s:$crole&$cqual"; 
                   4298:             }
                   4299:         }
1.191     harris41 4300:     }
1.800     albertel 4301:     foreach my $role (split(':',$domrole)) {
                   4302: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4303:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4304:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4305: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4306:                return "refused:d:$crole&$cqual"; 
                   4307:             }
                   4308:         }
1.191     harris41 4309:     }
1.800     albertel 4310:     foreach my $role (split(':',$courole)) {
                   4311: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4312:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4313:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4314: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4315:                return "refused:c:$crole&$cqual"; 
                   4316:             }
                   4317:         }
1.191     harris41 4318:     }
1.620     albertel 4319:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4320:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4321: 	        "rolesdef_$rolename=".
                   4322:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4323:     return reply($command,$env{'user.home'});
1.12      www      4324:   } else {
                   4325:     return 'refused';
                   4326:   }
1.105     harris41 4327: }
                   4328: 
                   4329: # ---------------- Make a metadata query against the network of library servers
                   4330: 
                   4331: sub metadata_query {
1.244     matthew  4332:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4333:     my %rhash;
1.845     albertel 4334:     my %libserv = &all_library();
1.244     matthew  4335:     my @server_list = (defined($server_array) ? @$server_array
                   4336:                                               : keys(%libserv) );
                   4337:     for my $server (@server_list) {
1.118     harris41 4338: 	unless ($custom or $customshow) {
                   4339: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4340: 	    $rhash{$server}=$reply;
                   4341: 	}
                   4342: 	else {
                   4343: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4344: 			     &escape($custom).':'.&escape($customshow),
                   4345: 			     $server);
                   4346: 	    $rhash{$server}=$reply;
                   4347: 	}
1.112     harris41 4348:     }
1.118     harris41 4349:     return \%rhash;
1.240     www      4350: }
                   4351: 
                   4352: # ----------------------------------------- Send log queries and wait for reply
                   4353: 
                   4354: sub log_query {
                   4355:     my ($uname,$udom,$query,%filters)=@_;
                   4356:     my $uhome=&homeserver($uname,$udom);
                   4357:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4358:     my $uhost=&hostname($uhome);
1.800     albertel 4359:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4360:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4361:                        $uhome);
1.479     albertel 4362:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4363:     return get_query_reply($queryid);
                   4364: }
                   4365: 
1.818     raeburn  4366: # -------------------------- Update MySQL table for portfolio file
                   4367: 
                   4368: sub update_portfolio_table {
1.821     raeburn  4369:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4370:     my $homeserver = &homeserver($uname,$udom);
                   4371:     my $queryid=
1.821     raeburn  4372:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4373:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4374:     my $reply = &get_query_reply($queryid);
                   4375:     return $reply;
                   4376: }
                   4377: 
1.508     raeburn  4378: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4379: 
                   4380: sub fetch_enrollment_query {
1.511     raeburn  4381:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4382:     my $homeserver;
1.547     raeburn  4383:     my $maxtries = 1;
1.508     raeburn  4384:     if ($context eq 'automated') {
                   4385:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4386:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4387:     } else {
                   4388:         $homeserver = &homeserver($cnum,$dom);
                   4389:     }
1.838     albertel 4390:     my $host=&hostname($homeserver);
1.506     raeburn  4391:     my $cmd = '';
1.800     albertel 4392:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4393:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4394:     }
                   4395:     $cmd =~ s/%%$//;
                   4396:     $cmd = &escape($cmd);
                   4397:     my $query = 'fetchenrollment';
1.620     albertel 4398:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4399:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4400:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4401:         return 'error: '.$queryid;
                   4402:     }
1.506     raeburn  4403:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4404:     my $tries = 1;
                   4405:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4406:         $reply = &get_query_reply($queryid);
                   4407:         $tries ++;
                   4408:     }
1.526     raeburn  4409:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4410:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4411:     } else {
1.515     raeburn  4412:         my @responses = split/:/,$reply;
                   4413:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4414:             foreach my $line (@responses) {
                   4415:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4416:                 $$replyref{$key} = $value;
                   4417:             }
                   4418:         } else {
1.506     raeburn  4419:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4420:             foreach my $line (@responses) {
                   4421:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4422:                 $$replyref{$key} = $value;
                   4423:                 if ($value > 0) {
1.800     albertel 4424:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4425:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4426:                         my $destname = $pathname.'/'.$filename;
                   4427:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4428:                         if ($xml_classlist =~ /^error/) {
                   4429:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4430:                         } else {
1.506     raeburn  4431:                             if ( open(FILE,">$destname") ) {
                   4432:                                 print FILE &unescape($xml_classlist);
                   4433:                                 close(FILE);
1.526     raeburn  4434:                             } else {
                   4435:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4436:                             }
                   4437:                         }
                   4438:                     }
                   4439:                 }
                   4440:             }
                   4441:         }
                   4442:         return 'ok';
                   4443:     }
                   4444:     return 'error';
                   4445: }
                   4446: 
1.242     www      4447: sub get_query_reply {
                   4448:     my $queryid=shift;
1.240     www      4449:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4450:     my $reply='';
                   4451:     for (1..100) {
                   4452: 	sleep 2;
                   4453:         if (-e $replyfile.'.end') {
1.448     albertel 4454: 	    if (open(my $fh,$replyfile)) {
1.240     www      4455:                $reply.=<$fh>;
1.448     albertel 4456:                close($fh);
1.240     www      4457: 	   } else { return 'error: reply_file_error'; }
1.242     www      4458:            return &unescape($reply);
                   4459: 	}
1.240     www      4460:     }
1.242     www      4461:     return 'timeout:'.$queryid;
1.240     www      4462: }
                   4463: 
                   4464: sub courselog_query {
1.241     www      4465: #
                   4466: # possible filters:
                   4467: # url: url or symb
                   4468: # username
                   4469: # domain
                   4470: # action: view, submit, grade
                   4471: # start: timestamp
                   4472: # end: timestamp
                   4473: #
1.240     www      4474:     my (%filters)=@_;
1.620     albertel 4475:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4476:     if ($filters{'url'}) {
                   4477: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4478:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4479:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4480:     }
1.620     albertel 4481:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4482:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4483:     return &log_query($cname,$cdom,'courselog',%filters);
                   4484: }
                   4485: 
                   4486: sub userlog_query {
1.858     raeburn  4487: #
                   4488: # possible filters:
                   4489: # action: log check role
                   4490: # start: timestamp
                   4491: # end: timestamp
                   4492: #
1.240     www      4493:     my ($uname,$udom,%filters)=@_;
                   4494:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4495: }
                   4496: 
1.506     raeburn  4497: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4498: 
                   4499: sub auto_run {
1.508     raeburn  4500:     my ($cnum,$cdom) = @_;
1.876     raeburn  4501:     my $response = 0;
                   4502:     my $settings;
                   4503:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4504:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4505:         $settings = $domconfig{'autoenroll'};
                   4506:         if ($settings->{'run'} eq '1') {
                   4507:             $response = 1;
                   4508:         }
                   4509:     } else {
                   4510:         my $homeserver = &homeserver($cnum,$cdom);
                   4511:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4512:     }
1.506     raeburn  4513:     return $response;
                   4514: }
1.776     albertel 4515: 
1.506     raeburn  4516: sub auto_get_sections {
1.508     raeburn  4517:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4518:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4519:     my @secs = ();
1.511     raeburn  4520:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4521:     unless ($response eq 'refused') {
                   4522:         @secs = split/:/,$response;
                   4523:     }
                   4524:     return @secs;
                   4525: }
1.776     albertel 4526: 
1.506     raeburn  4527: sub auto_new_course {
1.508     raeburn  4528:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4529:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4530:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4531:     return $response;
                   4532: }
1.776     albertel 4533: 
1.506     raeburn  4534: sub auto_validate_courseID {
1.508     raeburn  4535:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4536:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4537:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4538:     return $response;
                   4539: }
1.776     albertel 4540: 
1.506     raeburn  4541: sub auto_create_password {
1.873     raeburn  4542:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4543:     my ($homeserver,$response);
1.506     raeburn  4544:     my $create_passwd = 0;
                   4545:     my $authchk = '';
1.873     raeburn  4546:     if ($udom =~ /^$match_domain$/) {
                   4547:         $homeserver = &domain($udom,'primary');
                   4548:     }
                   4549:     if ($homeserver eq '') {
                   4550:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4551:             $homeserver = &homeserver($cnum,$cdom);
                   4552:         }
                   4553:     }
                   4554:     if ($homeserver eq '') {
                   4555:         $authchk = 'nodomain';
1.506     raeburn  4556:     } else {
1.873     raeburn  4557:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4558:         if ($response eq 'refused') {
                   4559:             $authchk = 'refused';
                   4560:         } else {
                   4561:             ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4562:         }
1.506     raeburn  4563:     }
                   4564:     return ($authparam,$create_passwd,$authchk);
                   4565: }
                   4566: 
1.706     raeburn  4567: sub auto_photo_permission {
                   4568:     my ($cnum,$cdom,$students) = @_;
                   4569:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4570:     my ($outcome,$perm_reqd,$conditions) = 
                   4571: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4572:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4573: 	return (undef,undef);
                   4574:     }
1.706     raeburn  4575:     return ($outcome,$perm_reqd,$conditions);
                   4576: }
                   4577: 
                   4578: sub auto_checkphotos {
                   4579:     my ($uname,$udom,$pid) = @_;
                   4580:     my $homeserver = &homeserver($uname,$udom);
                   4581:     my ($result,$resulttype);
                   4582:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4583: 				   &escape($uname).':'.&escape($pid),
                   4584: 				   $homeserver));
1.709     albertel 4585:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4586: 	return (undef,undef);
                   4587:     }
1.706     raeburn  4588:     if ($outcome) {
                   4589:         ($result,$resulttype) = split(/:/,$outcome);
                   4590:     } 
                   4591:     return ($result,$resulttype);
                   4592: }
                   4593: 
                   4594: sub auto_photochoice {
                   4595:     my ($cnum,$cdom) = @_;
                   4596:     my $homeserver = &homeserver($cnum,$cdom);
                   4597:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4598: 						       &escape($cdom),
                   4599: 						       $homeserver)));
1.709     albertel 4600:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4601: 	return (undef,undef);
                   4602:     }
1.706     raeburn  4603:     return ($update,$comment);
                   4604: }
                   4605: 
                   4606: sub auto_photoupdate {
                   4607:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4608:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4609:     my $host=&hostname($homeserver);
1.706     raeburn  4610:     my $cmd = '';
                   4611:     my $maxtries = 1;
1.800     albertel 4612:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4613:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4614:     }
                   4615:     $cmd =~ s/%%$//;
                   4616:     $cmd = &escape($cmd);
                   4617:     my $query = 'institutionalphotos';
                   4618:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4619:     unless ($queryid=~/^\Q$host\E\_/) {
                   4620:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4621:         return 'error: '.$queryid;
                   4622:     }
                   4623:     my $reply = &get_query_reply($queryid);
                   4624:     my $tries = 1;
                   4625:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4626:         $reply = &get_query_reply($queryid);
                   4627:         $tries ++;
                   4628:     }
                   4629:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4630:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4631:     } else {
                   4632:         my @responses = split(/:/,$reply);
                   4633:         my $outcome = shift(@responses); 
                   4634:         foreach my $item (@responses) {
                   4635:             my ($key,$value) = split(/=/,$item);
                   4636:             $$photo{$key} = $value;
                   4637:         }
                   4638:         return $outcome;
                   4639:     }
                   4640:     return 'error';
                   4641: }
                   4642: 
1.521     raeburn  4643: sub auto_instcode_format {
1.793     albertel 4644:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4645: 	$cat_order) = @_;
1.521     raeburn  4646:     my $courses = '';
1.772     raeburn  4647:     my @homeservers;
1.521     raeburn  4648:     if ($caller eq 'global') {
1.841     albertel 4649: 	my %servers = &get_servers($codedom,'library');
                   4650: 	foreach my $tryserver (keys(%servers)) {
                   4651: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4652: 		push(@homeservers,$tryserver);
                   4653: 	    }
1.584     raeburn  4654:         }
1.521     raeburn  4655:     } else {
1.772     raeburn  4656:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4657:     }
1.793     albertel 4658:     foreach my $code (keys(%{$instcodes})) {
                   4659:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4660:     }
                   4661:     chop($courses);
1.772     raeburn  4662:     my $ok_response = 0;
                   4663:     my $response;
                   4664:     while (@homeservers > 0 && $ok_response == 0) {
                   4665:         my $server = shift(@homeservers); 
                   4666:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4667:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4668:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4669: 		split/:/,$response;
1.772     raeburn  4670:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4671:             push(@{$codetitles},&str2array($codetitles_str));
                   4672:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4673:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4674:             $ok_response = 1;
                   4675:         }
                   4676:     }
                   4677:     if ($ok_response) {
1.521     raeburn  4678:         return 'ok';
1.772     raeburn  4679:     } else {
                   4680:         return $response;
1.521     raeburn  4681:     }
                   4682: }
                   4683: 
1.792     raeburn  4684: sub auto_instcode_defaults {
                   4685:     my ($domain,$returnhash,$code_order) = @_;
                   4686:     my @homeservers;
1.841     albertel 4687: 
                   4688:     my %servers = &get_servers($domain,'library');
                   4689:     foreach my $tryserver (keys(%servers)) {
                   4690: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4691: 	    push(@homeservers,$tryserver);
                   4692: 	}
1.792     raeburn  4693:     }
1.841     albertel 4694: 
1.792     raeburn  4695:     my $response;
1.841     albertel 4696:     foreach my $server (@homeservers) {
1.792     raeburn  4697:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4698:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4699: 	
                   4700: 	foreach my $pair (split(/\&/,$response)) {
                   4701: 	    my ($name,$value)=split(/\=/,$pair);
                   4702: 	    if ($name eq 'code_order') {
                   4703: 		@{$code_order} = split(/\&/,&unescape($value));
                   4704: 	    } else {
                   4705: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4706: 	    }
                   4707: 	}
                   4708: 	return 'ok';
1.792     raeburn  4709:     }
1.841     albertel 4710: 
                   4711:     return $response;
1.792     raeburn  4712: } 
                   4713: 
1.777     albertel 4714: sub auto_validate_class_sec {
1.773     raeburn  4715:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4716:     my $homeserver = &homeserver($cnum,$cdom);
                   4717:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4718:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4719:     return $response;
                   4720: }
                   4721: 
1.679     raeburn  4722: # ------------------------------------------------------- Course Group routines
                   4723: 
                   4724: sub get_coursegroups {
1.809     raeburn  4725:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4726:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4727: }
                   4728: 
1.679     raeburn  4729: sub modify_coursegroup {
                   4730:     my ($cdom,$cnum,$groupsettings) = @_;
                   4731:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4732: }
                   4733: 
1.809     raeburn  4734: sub toggle_coursegroup_status {
                   4735:     my ($cdom,$cnum,$group,$action) = @_;
                   4736:     my ($from_namespace,$to_namespace);
                   4737:     if ($action eq 'delete') {
                   4738:         $from_namespace = 'coursegroups';
                   4739:         $to_namespace = 'deleted_groups';
                   4740:     } else {
                   4741:         $from_namespace = 'deleted_groups';
                   4742:         $to_namespace = 'coursegroups';
                   4743:     }
                   4744:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4745:     if (my $tmp = &error(%curr_group)) {
                   4746:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4747:         return ('read error',$tmp);
                   4748:     } else {
                   4749:         my %savedsettings = %curr_group; 
1.809     raeburn  4750:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4751:         my $deloutcome;
                   4752:         if ($result eq 'ok') {
1.809     raeburn  4753:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4754:         } else {
                   4755:             return ('write error',$result);
                   4756:         }
                   4757:         if ($deloutcome eq 'ok') {
                   4758:             return 'ok';
                   4759:         } else {
                   4760:             return ('delete error',$deloutcome);
                   4761:         }
                   4762:     }
                   4763: }
                   4764: 
1.679     raeburn  4765: sub modify_group_roles {
                   4766:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4767:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4768:     my $role = 'gr/'.&escape($userprivs);
                   4769:     my ($uname,$udom) = split(/:/,$user);
                   4770:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4771:     if ($result eq 'ok') {
                   4772:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4773:     }
1.679     raeburn  4774:     return $result;
                   4775: }
                   4776: 
                   4777: sub modify_coursegroup_membership {
                   4778:     my ($cdom,$cnum,$membership) = @_;
                   4779:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4780:     return $result;
                   4781: }
                   4782: 
1.682     raeburn  4783: sub get_active_groups {
                   4784:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4785:     my $now = time;
                   4786:     my %groups = ();
                   4787:     foreach my $key (keys(%env)) {
1.811     albertel 4788:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4789:             my ($start,$end) = split(/\./,$env{$key});
                   4790:             if (($end!=0) && ($end<$now)) { next; }
                   4791:             if (($start!=0) && ($start>$now)) { next; }
                   4792:             if ($1 eq $cdom && $2 eq $cnum) {
                   4793:                 $groups{$3} = $env{$key} ;
                   4794:             }
                   4795:         }
                   4796:     }
                   4797:     return %groups;
                   4798: }
                   4799: 
1.683     raeburn  4800: sub get_group_membership {
                   4801:     my ($cdom,$cnum,$group) = @_;
                   4802:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4803: }
                   4804: 
                   4805: sub get_users_groups {
                   4806:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4807:     my @usersgroups;
1.683     raeburn  4808:     my $cachetime=1800;
                   4809: 
                   4810:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4811:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4812:     if (defined($cached)) {
1.734     albertel 4813:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4814:     } else {  
                   4815:         $grouplist = '';
1.816     raeburn  4816:         my $courseurl = &courseid_to_courseurl($courseid);
                   4817:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4818:         my $access_end = $env{'course.'.$courseid.
                   4819:                               '.default_enrollment_end_date'};
                   4820:         my $now = time;
                   4821:         foreach my $key (keys(%roleshash)) {
                   4822:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4823:                 my $group = $1;
                   4824:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4825:                     my $start = $2;
                   4826:                     my $end = $1;
                   4827:                     if ($start == -1) { next; } # deleted from group
                   4828:                     if (($start!=0) && ($start>$now)) { next; }
                   4829:                     if (($end!=0) && ($end<$now)) {
                   4830:                         if ($access_end && $access_end < $now) {
                   4831:                             if ($access_end - $end < 86400) {
                   4832:                                 push(@usersgroups,$group);
1.733     raeburn  4833:                             }
                   4834:                         }
1.817     raeburn  4835:                         next;
1.733     raeburn  4836:                     }
1.817     raeburn  4837:                     push(@usersgroups,$group);
1.683     raeburn  4838:                 }
                   4839:             }
                   4840:         }
1.817     raeburn  4841:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4842:         $grouplist = join(':',@usersgroups);
                   4843:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4844:     }
1.733     raeburn  4845:     return @usersgroups;
1.683     raeburn  4846: }
                   4847: 
                   4848: sub devalidate_getgroups_cache {
                   4849:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4850:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4851: 
1.683     raeburn  4852:     my $hashid="$udom:$uname:$courseid";
                   4853:     &devalidate_cache_new('getgroups',$hashid);
                   4854: }
                   4855: 
1.12      www      4856: # ------------------------------------------------------------------ Plain Text
                   4857: 
                   4858: sub plaintext {
1.742     raeburn  4859:     my ($short,$type,$cid) = @_;
1.758     albertel 4860:     if ($short =~ /^cr/) {
                   4861: 	return (split('/',$short))[-1];
                   4862:     }
1.742     raeburn  4863:     if (!defined($cid)) {
                   4864:         $cid = $env{'request.course.id'};
                   4865:     }
                   4866:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4867:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4868:                                           '.plaintext'});
                   4869:     }
                   4870:     my %rolenames = (
                   4871:                       Course => 'std',
                   4872:                       Group => 'alt1',
                   4873:                     );
                   4874:     if (defined($type) && 
                   4875:          defined($rolenames{$type}) && 
                   4876:          defined($prp{$short}{$rolenames{$type}})) {
                   4877:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4878:     } else {
                   4879:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4880:     }
1.12      www      4881: }
                   4882: 
                   4883: # ----------------------------------------------------------------- Assign Role
                   4884: 
                   4885: sub assignrole {
1.357     www      4886:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4887:     my $mrole;
                   4888:     if ($role =~ /^cr\//) {
1.393     www      4889:         my $cwosec=$url;
1.811     albertel 4890:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4891: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4892:            &logthis('Refused custom assignrole: '.
                   4893:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4894: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4895:            return 'refused'; 
                   4896:         }
1.21      www      4897:         $mrole='cr';
1.678     raeburn  4898:     } elsif ($role =~ /^gr\//) {
                   4899:         my $cwogrp=$url;
1.811     albertel 4900:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4901:         unless (&allowed('mdg',$cwogrp)) {
                   4902:             &logthis('Refused group assignrole: '.
                   4903:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4904:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4905:             return 'refused';
                   4906:         }
                   4907:         $mrole='gr';
1.21      www      4908:     } else {
1.82      www      4909:         my $cwosec=$url;
1.811     albertel 4910:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4911:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4912:            &logthis('Refused assignrole: '.
                   4913:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4914: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4915:            return 'refused'; 
                   4916:         }
1.21      www      4917:         $mrole=$role;
                   4918:     }
1.620     albertel 4919:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4920:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4921:     if ($end) { $command.='_'.$end; }
1.21      www      4922:     if ($start) {
                   4923: 	if ($end) { 
1.81      www      4924:            $command.='_'.$start; 
1.21      www      4925:         } else {
1.81      www      4926:            $command.='_0_'.$start;
1.21      www      4927:         }
                   4928:     }
1.739     raeburn  4929:     my $origstart = $start;
                   4930:     my $origend = $end;
1.357     www      4931: # actually delete
                   4932:     if ($deleteflag) {
1.373     www      4933: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4934: # modify command to delete the role
1.620     albertel 4935:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4936:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4937: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4938: # set start and finish to negative values for userrolelog
                   4939:            $start=-1;
                   4940:            $end=-1;
                   4941:         }
                   4942:     }
                   4943: # send command
1.349     www      4944:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4945: # log new user role if status is ok
1.349     www      4946:     if ($answer eq 'ok') {
1.663     raeburn  4947: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4948: # for course roles, perform group memberships changes triggered by role change.
                   4949:         unless ($role =~ /^gr/) {
                   4950:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4951:                                              $origstart);
                   4952:         }
1.349     www      4953:     }
                   4954:     return $answer;
1.169     harris41 4955: }
                   4956: 
                   4957: # -------------------------------------------------- Modify user authentication
1.197     www      4958: # Overrides without validation
                   4959: 
1.169     harris41 4960: sub modifyuserauth {
                   4961:     my ($udom,$uname,$umode,$upass)=@_;
                   4962:     my $uhome=&homeserver($uname,$udom);
1.197     www      4963:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4964:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4965:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4966:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4967:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4968: 		     &escape($upass),$uhome);
1.620     albertel 4969:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4970:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4971:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4972:     &log($udom,,$uname,$uhome,
1.620     albertel 4973:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4974:                                      $env{'user.name'}.', '.$umode.
1.197     www      4975:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4976:     unless ($reply eq 'ok') {
1.197     www      4977:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4978: 	return 'error: '.$reply;
                   4979:     }   
1.170     harris41 4980:     return 'ok';
1.80      www      4981: }
                   4982: 
1.81      www      4983: # --------------------------------------------------------------- Modify a user
1.80      www      4984: 
1.81      www      4985: sub modifyuser {
1.206     matthew  4986:     my ($udom,    $uname, $uid,
                   4987:         $umode,   $upass, $first,
                   4988:         $middle,  $last,  $gene,
1.387     www      4989:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4990:     $udom= &LONCAPA::clean_domain($udom);
                   4991:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4992:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4993:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4994: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4995:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4996:                                      ' desiredhome not specified'). 
1.620     albertel 4997:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4998:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4999:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5000: # ----------------------------------------------------------------- Create User
1.406     albertel 5001:     if (($uhome eq 'no_host') && 
                   5002: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5003:         my $unhome='';
1.844     albertel 5004:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5005:             $unhome = $desiredhome;
1.620     albertel 5006: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5007: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5008:         } else { # load balancing routine for determining $unhome
1.81      www      5009:             my $loadm=10000000;
1.841     albertel 5010: 	    my %servers = &get_servers($udom,'library');
                   5011: 	    foreach my $tryserver (keys(%servers)) {
                   5012: 		my $answer=reply('load',$tryserver);
                   5013: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5014: 		    $loadm=$answer;
                   5015: 		    $unhome=$tryserver;
                   5016: 		}
1.80      www      5017: 	    }
                   5018:         }
                   5019:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5020: 	    return 'error: unable to find a home server for '.$uname.
                   5021:                    ' in domain '.$udom;
1.80      www      5022:         }
                   5023:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5024:                          &escape($upass),$unhome);
                   5025: 	unless ($reply eq 'ok') {
                   5026:             return 'error: '.$reply;
                   5027:         }   
1.230     stredwic 5028:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5029:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5030: 	    return 'error: unable verify users home machine.';
1.80      www      5031:         }
1.209     matthew  5032:     }   # End of creation of new user
1.80      www      5033: # ---------------------------------------------------------------------- Add ID
                   5034:     if ($uid) {
                   5035:        $uid=~tr/A-Z/a-z/;
                   5036:        my %uidhash=&idrget($udom,$uname);
1.196     www      5037:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5038:          && (!$forceid)) {
1.80      www      5039: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5040: 	      return 'error: user id "'.$uid.'" does not match '.
                   5041:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5042:           }
                   5043:        } else {
                   5044: 	  &idput($udom,($uname => $uid));
                   5045:        }
                   5046:     }
                   5047: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5048:     my @tmp=&get('environment',
1.134     albertel 5049: 		   ['firstname','middlename','lastname','generation'],
                   5050: 		   $udom,$uname);
1.313     matthew  5051:     my %names;
                   5052:     if ($tmp[0] =~ m/^error:.*/) { 
                   5053:         %names=(); 
                   5054:     } else {
                   5055:         %names = @tmp;
                   5056:     }
1.388     www      5057: #
                   5058: # Make sure to not trash student environment if instructor does not bother
                   5059: # to supply name and email information
                   5060: #
                   5061:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5062:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5063:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5064:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5065:     if ($email) {
                   5066:        $email=~s/[^\w\@\.\-\,]//gs;
                   5067:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5068: 			   $names{'critnotification'} = $email;
                   5069: 			   $names{'permanentemail'} = $email; }
                   5070:     }
1.134     albertel 5071:     my $reply = &put('environment', \%names, $udom,$uname);
                   5072:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      5073:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5074:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5075:              $umode.', '.$first.', '.$middle.', '.
                   5076: 	     $last.', '.$gene.' by '.
1.620     albertel 5077:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5078:     return 'ok';
1.80      www      5079: }
                   5080: 
1.81      www      5081: # -------------------------------------------------------------- Modify student
1.80      www      5082: 
1.81      www      5083: sub modifystudent {
                   5084:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5085:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5086:     if (!$cid) {
1.620     albertel 5087: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5088: 	    return 'not_in_class';
                   5089: 	}
1.80      www      5090:     }
                   5091: # --------------------------------------------------------------- Make the user
1.81      www      5092:     my $reply=&modifyuser
1.209     matthew  5093: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5094:          $desiredhome,$email);
1.80      www      5095:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5096:     # This will cause &modify_student_enrollment to get the uid from the
                   5097:     # students environment
                   5098:     $uid = undef if (!$forceid);
1.455     albertel 5099:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5100: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5101:     return $reply;
                   5102: }
                   5103: 
                   5104: sub modify_student_enrollment {
1.515     raeburn  5105:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5106:     my ($cdom,$cnum,$chome);
                   5107:     if (!$cid) {
1.620     albertel 5108: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5109: 	    return 'not_in_class';
                   5110: 	}
1.620     albertel 5111: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5112: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5113:     } else {
                   5114: 	($cdom,$cnum)=split(/_/,$cid);
                   5115:     }
1.620     albertel 5116:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5117:     if (!$chome) {
1.457     raeburn  5118: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5119:     }
1.455     albertel 5120:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5121:     # Make sure the user exists
1.81      www      5122:     my $uhome=&homeserver($uname,$udom);
                   5123:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5124: 	return 'error: no such user';
                   5125:     }
1.297     matthew  5126:     # Get student data if we were not given enough information
                   5127:     if (!defined($first)  || $first  eq '' || 
                   5128:         !defined($last)   || $last   eq '' || 
                   5129:         !defined($uid)    || $uid    eq '' || 
                   5130:         !defined($middle) || $middle eq '' || 
                   5131:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5132:         # They did not supply us with enough data to enroll the student, so
                   5133:         # we need to pick up more information.
1.297     matthew  5134:         my %tmp = &get('environment',
1.294     matthew  5135:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5136:                        ,$udom,$uname);
                   5137: 
1.800     albertel 5138:         #foreach my $key (keys(%tmp)) {
                   5139:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5140:         #}
1.294     matthew  5141:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5142:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5143:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5144:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5145:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5146:     }
1.556     albertel 5147:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5148:     my $reply=cput('classlist',
                   5149: 		   {"$uname:$udom" => 
1.515     raeburn  5150: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5151: 		   $cdom,$cnum);
1.81      www      5152:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5153: 	return 'error: '.$reply;
1.652     albertel 5154:     } else {
                   5155: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5156:     }
1.297     matthew  5157:     # Add student role to user
1.83      www      5158:     my $uurl='/'.$cid;
1.81      www      5159:     $uurl=~s/\_/\//g;
                   5160:     if ($usec) {
                   5161: 	$uurl.='/'.$usec;
                   5162:     }
                   5163:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5164: }
                   5165: 
1.556     albertel 5166: sub format_name {
                   5167:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5168:     my $name;
                   5169:     if ($first ne 'lastname') {
                   5170: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5171:     } else {
                   5172: 	if ($lastname=~/\S/) {
                   5173: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5174: 	    $name=~s/\s+,/,/;
                   5175: 	} else {
                   5176: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5177: 	}
                   5178:     }
                   5179:     $name=~s/^\s+//;
                   5180:     $name=~s/\s+$//;
                   5181:     $name=~s/\s+/ /g;
                   5182:     return $name;
                   5183: }
                   5184: 
1.84      www      5185: # ------------------------------------------------- Write to course preferences
                   5186: 
                   5187: sub writecoursepref {
                   5188:     my ($courseid,%prefs)=@_;
                   5189:     $courseid=~s/^\///;
                   5190:     $courseid=~s/\_/\//g;
                   5191:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5192:     my $chome=homeserver($cnum,$cdomain);
                   5193:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5194: 	return 'error: no such course';
                   5195:     }
                   5196:     my $cstring='';
1.800     albertel 5197:     foreach my $pref (keys(%prefs)) {
                   5198: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5199:     }
1.84      www      5200:     $cstring=~s/\&$//;
                   5201:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5202: }
                   5203: 
                   5204: # ---------------------------------------------------------- Make/modify course
                   5205: 
                   5206: sub createcourse {
1.741     raeburn  5207:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5208:         $course_owner,$crstype)=@_;
1.84      www      5209:     $url=&declutter($url);
                   5210:     my $cid='';
1.264     matthew  5211:     unless (&allowed('ccc',$udom)) {
1.84      www      5212:         return 'refused';
                   5213:     }
                   5214: # ------------------------------------------------------------------- Create ID
1.674     www      5215:    my $uname=int(1+rand(9)).
                   5216:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5217:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5218:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5219: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5220:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5221:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5222:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5223:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5224:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5225:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5226:            return 'error: unable to generate unique course-ID';
                   5227:        } 
                   5228:    }
1.264     matthew  5229: # ------------------------------------------------ Check supplied server name
1.620     albertel 5230:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5231:     if (! &is_library($course_server)) {
1.264     matthew  5232:         return 'error:bad server name '.$course_server;
                   5233:     }
1.84      www      5234: # ------------------------------------------------------------- Make the course
                   5235:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5236:                       $course_server);
1.84      www      5237:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5238:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5239:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5240: 	return 'error: no such course';
                   5241:     }
1.271     www      5242: # ----------------------------------------------------------------- Course made
1.516     raeburn  5243: # log existence
                   5244:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5245:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5246:                   &escape($crstype),$uhome);
1.358     www      5247:     &flushcourselogs();
                   5248: # set toplevel url
1.271     www      5249:     my $topurl=$url;
                   5250:     unless ($nonstandard) {
                   5251: # ------------------------------------------ For standard courses, make top url
                   5252:         my $mapurl=&clutter($url);
1.278     www      5253:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5254:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5255: <map>
                   5256: <resource id="1" type="start"></resource>
                   5257: <resource id="2" src="$mapurl"></resource>
                   5258: <resource id="3" type="finish"></resource>
                   5259: <link index="1" from="1" to="2"></link>
                   5260: <link index="2" from="2" to="3"></link>
                   5261: </map>
                   5262: ENDINITMAP
                   5263:         $topurl=&declutter(
1.638     albertel 5264:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5265:                           );
                   5266:     }
                   5267: # ----------------------------------------------------------- Write preferences
1.84      www      5268:     &writecoursepref($udom.'_'.$uname,
                   5269:                      ('description' => $description,
1.271     www      5270:                       'url'         => $topurl));
1.84      www      5271:     return '/'.$udom.'/'.$uname;
                   5272: }
                   5273: 
1.813     albertel 5274: sub is_course {
                   5275:     my ($cdom,$cnum) = @_;
                   5276:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5277: 				undef,'.');
                   5278:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5279:         return 1;
                   5280:     }
                   5281:     return 0;
                   5282: }
                   5283: 
1.21      www      5284: # ---------------------------------------------------------- Assign Custom Role
                   5285: 
                   5286: sub assigncustomrole {
1.357     www      5287:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5288:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5289:                        $end,$start,$deleteflag);
1.21      www      5290: }
                   5291: 
                   5292: # ----------------------------------------------------------------- Revoke Role
                   5293: 
                   5294: sub revokerole {
1.357     www      5295:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5296:     my $now=time;
1.357     www      5297:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5298: }
                   5299: 
                   5300: # ---------------------------------------------------------- Revoke Custom Role
                   5301: 
                   5302: sub revokecustomrole {
1.357     www      5303:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5304:     my $now=time;
1.357     www      5305:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5306:            $deleteflag);
1.17      www      5307: }
                   5308: 
1.533     banghart 5309: # ------------------------------------------------------------ Disk usage
1.535     albertel 5310: sub diskusage {
1.533     banghart 5311:     my ($udom,$uname,$directoryRoot)=@_;
                   5312:     $directoryRoot =~ s/\/$//;
1.535     albertel 5313:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5314:     return $listing;
1.512     banghart 5315: }
                   5316: 
1.566     banghart 5317: sub is_locked {
                   5318:     my ($file_name, $domain, $user) = @_;
                   5319:     my @check;
                   5320:     my $is_locked;
                   5321:     push @check, $file_name;
1.613     albertel 5322:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5323: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5324:     my ($tmp)=keys(%locked);
                   5325:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5326:     
1.566     banghart 5327:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5328:         $is_locked = 'false';
                   5329:         foreach my $entry (@{$locked{$file_name}}) {
                   5330:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5331:                $is_locked = 'true';
                   5332:                last;
1.745     raeburn  5333:            }
                   5334:        }
1.566     banghart 5335:     } else {
                   5336:         $is_locked = 'false';
                   5337:     }
                   5338: }
                   5339: 
1.759     albertel 5340: sub declutter_portfile {
                   5341:     my ($file) = @_;
1.833     albertel 5342:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5343:     return $file;
                   5344: }
                   5345: 
1.559     banghart 5346: # ------------------------------------------------------------- Mark as Read Only
                   5347: 
                   5348: sub mark_as_readonly {
                   5349:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5350:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5351:     my ($tmp)=keys(%current_permissions);
                   5352:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5353:     foreach my $file (@{$files}) {
1.759     albertel 5354: 	$file = &declutter_portfile($file);
1.561     banghart 5355:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5356:     }
1.613     albertel 5357:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5358:     return;
                   5359: }
                   5360: 
1.572     banghart 5361: # ------------------------------------------------------------Save Selected Files
                   5362: 
                   5363: sub save_selected_files {
                   5364:     my ($user, $path, @files) = @_;
                   5365:     my $filename = $user."savedfiles";
1.573     banghart 5366:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5367:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5368:     foreach my $file (@files) {
1.620     albertel 5369:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5370:     }
                   5371:     foreach my $file (@other_files) {
1.574     banghart 5372:         print (OUT $file."\n");
1.572     banghart 5373:     }
1.574     banghart 5374:     close (OUT);
1.572     banghart 5375:     return 'ok';
                   5376: }
                   5377: 
1.574     banghart 5378: sub clear_selected_files {
                   5379:     my ($user) = @_;
                   5380:     my $filename = $user."savedfiles";
                   5381:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5382:     print (OUT undef);
                   5383:     close (OUT);
                   5384:     return ("ok");    
                   5385: }
                   5386: 
1.572     banghart 5387: sub files_in_path {
                   5388:     my ($user, $path) = @_;
                   5389:     my $filename = $user."savedfiles";
                   5390:     my %return_files;
1.574     banghart 5391:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5392:     while (my $line_in = <IN>) {
1.574     banghart 5393:         chomp ($line_in);
                   5394:         my @paths_and_file = split (m!/!, $line_in);
                   5395:         my $file_part = pop (@paths_and_file);
                   5396:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5397:         $path_part.='/';
                   5398:         my $path_and_file = $path_part.$file_part;
                   5399:         if ($path_part eq $path) {
                   5400:             $return_files{$file_part}= 'selected';
                   5401:         }
                   5402:     }
1.574     banghart 5403:     close (IN);
                   5404:     return (\%return_files);
1.572     banghart 5405: }
                   5406: 
                   5407: # called in portfolio select mode, to show files selected NOT in current directory
                   5408: sub files_not_in_path {
                   5409:     my ($user, $path) = @_;
                   5410:     my $filename = $user."savedfiles";
                   5411:     my @return_files;
                   5412:     my $path_part;
1.800     albertel 5413:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5414:     while (my $line = <IN>) {
1.572     banghart 5415:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5416:         my @paths_and_file = split(m|/|, $line);
                   5417:         my $file_part = pop(@paths_and_file);
                   5418:         chomp($file_part);
                   5419:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5420:         $path_part .= '/';
                   5421:         my $path_and_file = $path_part.$file_part;
                   5422:         if ($path_part ne $path) {
1.800     albertel 5423:             push(@return_files, ($path_and_file));
1.572     banghart 5424:         }
                   5425:     }
1.800     albertel 5426:     close(OUT);
1.574     banghart 5427:     return (@return_files);
1.572     banghart 5428: }
                   5429: 
1.745     raeburn  5430: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5431: 
1.745     raeburn  5432: sub get_portfile_permissions {
                   5433:     my ($domain,$user) = @_;
1.613     albertel 5434:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5435:     my ($tmp)=keys(%current_permissions);
                   5436:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5437:     return \%current_permissions;
                   5438: }
                   5439: 
                   5440: #---------------------------------------------Get portfolio file access controls
                   5441: 
1.749     raeburn  5442: sub get_access_controls {
1.745     raeburn  5443:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5444:     my %access;
                   5445:     my $real_file = $file;
                   5446:     $file =~ s/\.meta$//;
1.745     raeburn  5447:     if (defined($file)) {
1.749     raeburn  5448:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5449:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5450:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5451:             }
                   5452:         }
1.745     raeburn  5453:     } else {
1.749     raeburn  5454:         foreach my $key (keys(%{$current_permissions})) {
                   5455:             if ($key =~ /\0accesscontrol$/) {
                   5456:                 if (defined($group)) {
                   5457:                     if ($key !~ m-^\Q$group\E/-) {
                   5458:                         next;
                   5459:                     }
                   5460:                 }
                   5461:                 my ($fullpath) = split(/\0/,$key);
                   5462:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5463:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5464:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5465:                     }
                   5466:                 }
                   5467:             }
                   5468:         }
                   5469:     }
                   5470:     return %access;
                   5471: }
                   5472: 
                   5473: sub modify_access_controls {
                   5474:     my ($file_name,$changes,$domain,$user)=@_;
                   5475:     my ($outcome,$deloutcome);
                   5476:     my %store_permissions;
                   5477:     my %new_values;
                   5478:     my %new_control;
                   5479:     my %translation;
                   5480:     my @deletions = ();
                   5481:     my $now = time;
                   5482:     if (exists($$changes{'activate'})) {
                   5483:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5484:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5485:             my $numnew = scalar(@newitems);
                   5486:             for (my $i=0; $i<$numnew; $i++) {
                   5487:                 my $newkey = $newitems[$i];
                   5488:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5489:                 if ($newkey =~ /^\d+:/) { 
                   5490:                     $newkey =~ s/^(\d+)/$newid/;
                   5491:                     $translation{$1} = $newid;
                   5492:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5493:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5494:                     $translation{$1} = $newid;
                   5495:                 }
1.749     raeburn  5496:                 $new_values{$file_name."\0".$newkey} = 
                   5497:                                           $$changes{'activate'}{$newitems[$i]};
                   5498:                 $new_control{$newkey} = $now;
                   5499:             }
                   5500:         }
                   5501:     }
                   5502:     my %todelete;
                   5503:     my %changed_items;
                   5504:     foreach my $action ('delete','update') {
                   5505:         if (exists($$changes{$action})) {
                   5506:             if (ref($$changes{$action}) eq 'HASH') {
                   5507:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5508:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5509:                     if ($action eq 'delete') { 
                   5510:                         $todelete{$itemnum} = 1;
                   5511:                     } else {
                   5512:                         $changed_items{$itemnum} = $key;
                   5513:                     }
                   5514:                 }
1.745     raeburn  5515:             }
                   5516:         }
1.749     raeburn  5517:     }
                   5518:     # get lock on access controls for file.
                   5519:     my $lockhash = {
                   5520:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5521:                                                        ':'.$env{'user.domain'},
                   5522:                    }; 
                   5523:     my $tries = 0;
                   5524:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5525:    
                   5526:     while (($gotlock ne 'ok') && $tries <3) {
                   5527:         $tries ++;
                   5528:         sleep 1;
                   5529:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5530:     }
                   5531:     if ($gotlock eq 'ok') {
                   5532:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5533:         my ($tmp)=keys(%curr_permissions);
                   5534:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5535:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5536:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5537:             if (ref($curr_controls) eq 'HASH') {
                   5538:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5539:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5540:                     if (defined($todelete{$itemnum})) {
                   5541:                         push(@deletions,$file_name."\0".$control_item);
                   5542:                     } else {
                   5543:                         if (defined($changed_items{$itemnum})) {
                   5544:                             $new_control{$changed_items{$itemnum}} = $now;
                   5545:                             push(@deletions,$file_name."\0".$control_item);
                   5546:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5547:                         } else {
                   5548:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5549:                         }
                   5550:                     }
1.745     raeburn  5551:                 }
                   5552:             }
                   5553:         }
1.749     raeburn  5554:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5555:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5556:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5557:         #  remove lock
                   5558:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5559:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5560:         my ($file,$group);
                   5561:         if (&is_course($domain,$user)) {
                   5562:             ($group,$file) = split(/\//,$file_name,2);
                   5563:         } else {
                   5564:             $file = $file_name;
                   5565:         }
                   5566:         my $sqlresult =
                   5567:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5568:                                     $group);
1.749     raeburn  5569:     } else {
                   5570:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5571:     }
1.749     raeburn  5572:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5573: }
                   5574: 
1.827     raeburn  5575: sub make_public_indefinitely {
                   5576:     my ($requrl) = @_;
                   5577:     my $now = time;
                   5578:     my $action = 'activate';
                   5579:     my $aclnum = 0;
                   5580:     if (&is_portfolio_url($requrl)) {
                   5581:         my (undef,$udom,$unum,$file_name,$group) =
                   5582:             &parse_portfolio_url($requrl);
                   5583:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5584:         my %access_controls = &get_access_controls($current_perms,
                   5585:                                                    $group,$file_name);
                   5586:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5587:             my ($num,$scope,$end,$start) = 
                   5588:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5589:             if ($scope eq 'public') {
                   5590:                 if ($start <= $now && $end == 0) {
                   5591:                     $action = 'none';
                   5592:                 } else {
                   5593:                     $action = 'update';
                   5594:                     $aclnum = $num;
                   5595:                 }
                   5596:                 last;
                   5597:             }
                   5598:         }
                   5599:         if ($action eq 'none') {
                   5600:              return 'ok';
                   5601:         } else {
                   5602:             my %changes;
                   5603:             my $newend = 0;
                   5604:             my $newstart = $now;
                   5605:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5606:             $changes{$action}{$newkey} = {
                   5607:                 type => 'public',
                   5608:                 time => {
                   5609:                     start => $newstart,
                   5610:                     end   => $newend,
                   5611:                 },
                   5612:             };
                   5613:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5614:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5615:             return $outcome;
                   5616:         }
                   5617:     } else {
                   5618:         return 'invalid';
                   5619:     }
                   5620: }
                   5621: 
1.745     raeburn  5622: #------------------------------------------------------Get Marked as Read Only
                   5623: 
                   5624: sub get_marked_as_readonly {
                   5625:     my ($domain,$user,$what,$group) = @_;
                   5626:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5627:     my @readonly_files;
1.629     banghart 5628:     my $cmp1=$what;
                   5629:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5630:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5631:         if (defined($group)) {
                   5632:             if ($file_name !~ m-^\Q$group\E/-) {
                   5633:                 next;
                   5634:             }
                   5635:         }
1.561     banghart 5636:         if (ref($value) eq "ARRAY"){
                   5637:             foreach my $stored_what (@{$value}) {
1.629     banghart 5638:                 my $cmp2=$stored_what;
1.759     albertel 5639:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5640:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5641:                 }
1.629     banghart 5642:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5643:                     push(@readonly_files, $file_name);
1.745     raeburn  5644:                     last;
1.563     banghart 5645:                 } elsif (!defined($what)) {
                   5646:                     push(@readonly_files, $file_name);
1.745     raeburn  5647:                     last;
1.561     banghart 5648:                 }
                   5649:             }
1.745     raeburn  5650:         }
1.561     banghart 5651:     }
                   5652:     return @readonly_files;
                   5653: }
1.577     banghart 5654: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5655: 
1.577     banghart 5656: sub get_marked_as_readonly_hash {
1.745     raeburn  5657:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5658:     my %readonly_files;
1.745     raeburn  5659:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5660:         if (defined($group)) {
                   5661:             if ($file_name !~ m-^\Q$group\E/-) {
                   5662:                 next;
                   5663:             }
                   5664:         }
1.577     banghart 5665:         if (ref($value) eq "ARRAY"){
                   5666:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5667:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5668:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5669:                         if ($lock_descriptor eq 'graded') {
                   5670:                             $readonly_files{$file_name} = 'graded';
                   5671:                         } elsif ($lock_descriptor eq 'handback') {
                   5672:                             $readonly_files{$file_name} = 'handback';
                   5673:                         } else {
                   5674:                             if (!exists($readonly_files{$file_name})) {
                   5675:                                 $readonly_files{$file_name} = 'locked';
                   5676:                             }
                   5677:                         }
1.745     raeburn  5678:                     }
1.750     banghart 5679:                 } 
1.577     banghart 5680:             }
                   5681:         } 
                   5682:     }
                   5683:     return %readonly_files;
                   5684: }
1.559     banghart 5685: # ------------------------------------------------------------ Unmark as Read Only
                   5686: 
                   5687: sub unmark_as_readonly {
1.629     banghart 5688:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5689:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5690:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5691:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5692:     my $symb_crs = $what;
                   5693:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5694:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5695:     my ($tmp)=keys(%current_permissions);
                   5696:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5697:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5698:     foreach my $file (@readonly_files) {
1.759     albertel 5699: 	my $clean_file = &declutter_portfile($file);
                   5700: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5701: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5702:         my @new_locks;
                   5703:         my @del_keys;
                   5704:         if (ref($current_locks) eq "ARRAY"){
                   5705:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5706:                 my $compare=$locker;
1.749     raeburn  5707:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5708:                     $compare=join('',@{$locker});
1.746     raeburn  5709:                     if ($compare ne $symb_crs) {
                   5710:                         push(@new_locks, $locker);
                   5711:                     }
1.563     banghart 5712:                 }
                   5713:             }
1.650     albertel 5714:             if (scalar(@new_locks) > 0) {
1.563     banghart 5715:                 $current_permissions{$file} = \@new_locks;
                   5716:             } else {
                   5717:                 push(@del_keys, $file);
1.613     albertel 5718:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5719:                 delete($current_permissions{$file});
1.563     banghart 5720:             }
                   5721:         }
1.561     banghart 5722:     }
1.613     albertel 5723:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5724:     return;
                   5725: }
1.512     banghart 5726: 
1.17      www      5727: # ------------------------------------------------------------ Directory lister
                   5728: 
                   5729: sub dirlist {
1.253     stredwic 5730:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5731: 
1.18      www      5732:     $uri=~s/^\///;
                   5733:     $uri=~s/\/$//;
1.253     stredwic 5734:     my ($udom, $uname);
                   5735:     (undef,$udom,$uname)=split(/\//,$uri);
                   5736:     if(defined($userdomain)) {
                   5737:         $udom = $userdomain;
                   5738:     }
                   5739:     if(defined($username)) {
                   5740:         $uname = $username;
                   5741:     }
                   5742: 
                   5743:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5744:     if(defined($alternateDirectoryRoot)) {
                   5745:         $dirRoot = $alternateDirectoryRoot;
                   5746:         $dirRoot =~ s/\/$//;
1.751     banghart 5747:     }
1.253     stredwic 5748: 
                   5749:     if($udom) {
                   5750:         if($uname) {
1.800     albertel 5751:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5752: 				 &homeserver($uname,$udom));
1.605     matthew  5753:             my @listing_results;
                   5754:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5755:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5756: 				  &homeserver($uname,$udom));
1.605     matthew  5757:                 @listing_results = split(/:/,$listing);
                   5758:             } else {
                   5759:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5760:             }
                   5761:             return @listing_results;
1.253     stredwic 5762:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5763:             my %allusers;
1.841     albertel 5764: 	    my %servers = &get_servers($udom,'library');
                   5765: 	    foreach my $tryserver (keys(%servers)) {
                   5766: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5767: 				     $udom, $tryserver);
                   5768: 		my @listing_results;
                   5769: 		if ($listing eq 'unknown_cmd') {
                   5770: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5771: 				      $udom, $tryserver);
                   5772: 		    @listing_results = split(/:/,$listing);
                   5773: 		} else {
                   5774: 		    @listing_results =
                   5775: 			map { &unescape($_); } split(/:/,$listing);
                   5776: 		}
                   5777: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5778: 		    $listing_results[0] ne 'empty'       &&
                   5779: 		    $listing_results[0] ne 'con_lost') {
                   5780: 		    foreach my $line (@listing_results) {
                   5781: 			my ($entry) = split(/&/,$line,2);
                   5782: 			$allusers{$entry} = 1;
                   5783: 		    }
                   5784: 		}
1.253     stredwic 5785:             }
                   5786:             my $alluserstr='';
1.800     albertel 5787:             foreach my $user (sort(keys(%allusers))) {
                   5788:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5789:             }
                   5790:             $alluserstr=~s/:$//;
                   5791:             return split(/:/,$alluserstr);
                   5792:         } else {
1.800     albertel 5793:             return ('missing user name');
1.253     stredwic 5794:         }
                   5795:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5796:         my @all_domains = sort(&all_domains());
                   5797:          foreach my $domain (@all_domains) {
                   5798:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5799:          }
                   5800:          return @all_domains;
                   5801:      } else {
1.800     albertel 5802:         return ('missing domain');
1.275     stredwic 5803:     }
                   5804: }
                   5805: 
                   5806: # --------------------------------------------- GetFileTimestamp
                   5807: # This function utilizes dirlist and returns the date stamp for
                   5808: # when it was last modified.  It will also return an error of -1
                   5809: # if an error occurs
                   5810: 
1.410     matthew  5811: ##
                   5812: ## FIXME: This subroutine assumes its caller knows something about the
                   5813: ## directory structure of the home server for the student ($root).
                   5814: ## Not a good assumption to make.  Since this is for looking up files
                   5815: ## in user directories, the full path should be constructed by lond, not
                   5816: ## whatever machine we request data from.
                   5817: ##
1.275     stredwic 5818: sub GetFileTimestamp {
                   5819:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5820:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5821:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5822:     my $subdir=$studentName.'__';
                   5823:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5824:     my $proname="$studentDomain/$subdir/$studentName";
                   5825:     $proname .= '/'.$filename;
1.375     matthew  5826:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5827:                                               $studentName, $root);
1.275     stredwic 5828:     my @stats = split('&', $fileStat);
                   5829:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5830:         # @stats contains first the filename, then the stat output
                   5831:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5832:     } else {
                   5833:         return -1;
1.253     stredwic 5834:     }
1.26      www      5835: }
                   5836: 
1.712     albertel 5837: sub stat_file {
                   5838:     my ($uri) = @_;
1.787     albertel 5839:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5840: 
1.712     albertel 5841:     my ($udom,$uname,$file,$dir);
                   5842:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5843: 	($udom,$uname,$file) =
1.811     albertel 5844: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5845: 	$file = 'userfiles/'.$file;
1.740     www      5846: 	$dir = &propath($udom,$uname);
1.712     albertel 5847:     }
                   5848:     if ($uri =~ m-^/res/-) {
                   5849: 	($udom,$uname) = 
1.807     albertel 5850: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5851: 	$file = $uri;
                   5852:     }
                   5853: 
                   5854:     if (!$udom || !$uname || !$file) {
                   5855: 	# unable to handle the uri
                   5856: 	return ();
                   5857:     }
                   5858: 
                   5859:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5860:     my @stats = split('&', $result);
1.721     banghart 5861:     
1.712     albertel 5862:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5863: 	shift(@stats); #filename is first
                   5864: 	return @stats;
                   5865:     }
                   5866:     return ();
                   5867: }
                   5868: 
1.26      www      5869: # -------------------------------------------------------- Value of a Condition
                   5870: 
1.713     albertel 5871: # gets the value of a specific preevaluated condition
                   5872: #    stored in the string  $env{user.state.<cid>}
                   5873: # or looks up a condition reference in the bighash and if if hasn't
                   5874: # already been evaluated recurses into docondval to get the value of
                   5875: # the condition, then memoizing it to 
                   5876: #   $env{user.state.<cid>.<condition>}
1.40      www      5877: sub directcondval {
                   5878:     my $number=shift;
1.620     albertel 5879:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5880: 	&Apache::lonuserstate::evalstate();
                   5881:     }
1.713     albertel 5882:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5883: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5884:     } elsif ($number =~ /^_/) {
                   5885: 	my $sub_condition;
                   5886: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5887: 		&GDBM_READER(),0640)) {
                   5888: 	    $sub_condition=$bighash{'conditions'.$number};
                   5889: 	    untie(%bighash);
                   5890: 	}
                   5891: 	my $value = &docondval($sub_condition);
                   5892: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5893: 	return $value;
                   5894:     }
1.620     albertel 5895:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5896:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5897:     } else {
                   5898:        return 2;
                   5899:     }
                   5900: }
                   5901: 
1.713     albertel 5902: # get the collection of conditions for this resource
1.26      www      5903: sub condval {
                   5904:     my $condidx=shift;
1.54      www      5905:     my $allpathcond='';
1.713     albertel 5906:     foreach my $cond (split(/\|/,$condidx)) {
                   5907: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5908: 	    $allpathcond.=
                   5909: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5910: 	}
1.191     harris41 5911:     }
1.54      www      5912:     $allpathcond=~s/\|$//;
1.713     albertel 5913:     return &docondval($allpathcond);
                   5914: }
                   5915: 
                   5916: #evaluates an expression of conditions
                   5917: sub docondval {
                   5918:     my ($allpathcond) = @_;
                   5919:     my $result=0;
                   5920:     if ($env{'request.course.id'}
                   5921: 	&& defined($allpathcond)) {
                   5922: 	my $operand='|';
                   5923: 	my @stack;
                   5924: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5925: 	    if ($chunk eq '(') {
                   5926: 		push @stack,($operand,$result);
                   5927: 	    } elsif ($chunk eq ')') {
                   5928: 		my $before=pop @stack;
                   5929: 		if (pop @stack eq '&') {
                   5930: 		    $result=$result>$before?$before:$result;
                   5931: 		} else {
                   5932: 		    $result=$result>$before?$result:$before;
                   5933: 		}
                   5934: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5935: 		$operand=$chunk;
                   5936: 	    } else {
                   5937: 		my $new=directcondval($chunk);
                   5938: 		if ($operand eq '&') {
                   5939: 		    $result=$result>$new?$new:$result;
                   5940: 		} else {
                   5941: 		    $result=$result>$new?$result:$new;
                   5942: 		}
                   5943: 	    }
                   5944: 	}
1.26      www      5945:     }
                   5946:     return $result;
1.421     albertel 5947: }
                   5948: 
                   5949: # ---------------------------------------------------- Devalidate courseresdata
                   5950: 
                   5951: sub devalidatecourseresdata {
                   5952:     my ($coursenum,$coursedomain)=@_;
                   5953:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5954:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5955: }
                   5956: 
1.763     www      5957: 
1.200     www      5958: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     5959: #
                   5960: #  Parameters:
                   5961: #      $coursenum    - Number of the course.
                   5962: #      $coursedomain - Domain at which the course was created.
                   5963: #  Returns:
                   5964: #     A hash of the course parameters along (I think) with timestamps
                   5965: #     and version info.
1.877     foxr     5966: 
1.624     albertel 5967: sub get_courseresdata {
                   5968:     my ($coursenum,$coursedomain)=@_;
1.200     www      5969:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5970:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5971:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5972:     my %dumpreply;
1.417     albertel 5973:     unless (defined($cached)) {
1.624     albertel 5974: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5975: 	$result=\%dumpreply;
1.251     albertel 5976: 	my ($tmp) = keys(%dumpreply);
                   5977: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5978: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5979: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5980: 	    return $tmp;
1.416     albertel 5981: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5982: 	    $result=undef;
1.599     albertel 5983: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5984: 	}
                   5985:     }
1.624     albertel 5986:     return $result;
                   5987: }
                   5988: 
1.633     albertel 5989: sub devalidateuserresdata {
                   5990:     my ($uname,$udom)=@_;
                   5991:     my $hashid="$udom:$uname";
                   5992:     &devalidate_cache_new('userres',$hashid);
                   5993: }
                   5994: 
1.624     albertel 5995: sub get_userresdata {
                   5996:     my ($uname,$udom)=@_;
                   5997:     #most student don\'t have any data set, check if there is some data
                   5998:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5999: 
                   6000:     my $hashid="$udom:$uname";
                   6001:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6002:     if (!defined($cached)) {
                   6003: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6004: 	$result=\%resourcedata;
                   6005: 	&do_cache_new('userres',$hashid,$result,600);
                   6006:     }
                   6007:     my ($tmp)=keys(%$result);
                   6008:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6009: 	return $result;
                   6010:     }
                   6011:     #error 2 occurs when the .db doesn't exist
                   6012:     if ($tmp!~/error: 2 /) {
1.672     albertel 6013: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6014: 		 " Trying to get resource data for ".
                   6015: 		 $uname." at ".$udom.": ".
                   6016: 		 $tmp."</font>");
                   6017:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6018: 	#&EXT_cache_set($udom,$uname);
                   6019: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6020: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6021:     }
                   6022:     return $tmp;
                   6023: }
1.879     foxr     6024: #----------------------------------------------- resdata - return resource data
                   6025: #  Purpose:
                   6026: #    Return resource data for either users or for a course.
                   6027: #  Parameters:
                   6028: #     $name      - Course/user name.
                   6029: #     $domain    - Name of the domain the user/course is registered on.
                   6030: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6031: #     @which     - Array of names of resources desired.
                   6032: #  Returns:
                   6033: #     The value of the first reasource in @which that is found in the
                   6034: #     resource hash.
                   6035: #  Exceptional Conditions:
                   6036: #     If the $type passed in is not valid (not the string 'course' or 
                   6037: #     'user', an undefined  reference is returned.
                   6038: #     If none of the resources are found, an undef is returned
1.624     albertel 6039: sub resdata {
                   6040:     my ($name,$domain,$type,@which)=@_;
                   6041:     my $result;
                   6042:     if ($type eq 'course') {
                   6043: 	$result=&get_courseresdata($name,$domain);
                   6044:     } elsif ($type eq 'user') {
                   6045: 	$result=&get_userresdata($name,$domain);
                   6046:     }
                   6047:     if (!ref($result)) { return $result; }    
1.251     albertel 6048:     foreach my $item (@which) {
1.417     albertel 6049: 	if (defined($result->{$item})) {
                   6050: 	    return $result->{$item};
1.251     albertel 6051: 	}
1.250     albertel 6052:     }
1.291     albertel 6053:     return undef;
1.200     www      6054: }
                   6055: 
1.379     matthew  6056: #
                   6057: # EXT resource caching routines
                   6058: #
                   6059: 
                   6060: sub clear_EXT_cache_status {
1.383     albertel 6061:     &delenv('cache.EXT.');
1.379     matthew  6062: }
                   6063: 
                   6064: sub EXT_cache_status {
                   6065:     my ($target_domain,$target_user) = @_;
1.383     albertel 6066:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6067:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6068:         # We know already the user has no data
                   6069:         return 1;
                   6070:     } else {
                   6071:         return 0;
                   6072:     }
                   6073: }
                   6074: 
                   6075: sub EXT_cache_set {
                   6076:     my ($target_domain,$target_user) = @_;
1.383     albertel 6077:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6078:     #&appenv($cachename => time);
1.379     matthew  6079: }
                   6080: 
1.28      www      6081: # --------------------------------------------------------- Value of a Variable
1.58      www      6082: sub EXT {
1.715     albertel 6083: 
1.395     albertel 6084:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6085:     unless ($varname) { return ''; }
1.218     albertel 6086:     #get real user name/domain, courseid and symb
                   6087:     my $courseid;
1.359     albertel 6088:     my $publicuser;
1.427     www      6089:     if ($symbparm) {
                   6090: 	$symbparm=&get_symb_from_alias($symbparm);
                   6091:     }
1.218     albertel 6092:     if (!($uname && $udom)) {
1.790     albertel 6093:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6094:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6095:     } else {
1.620     albertel 6096: 	$courseid=$env{'request.course.id'};
1.218     albertel 6097:     }
1.48      www      6098:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6099:     my $rest;
1.320     albertel 6100:     if (defined($therest[0])) {
1.48      www      6101:        $rest=join('.',@therest);
                   6102:     } else {
                   6103:        $rest='';
                   6104:     }
1.320     albertel 6105: 
1.57      www      6106:     my $qualifierrest=$qualifier;
                   6107:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6108:     my $spacequalifierrest=$space;
                   6109:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6110:     if ($realm eq 'user') {
1.48      www      6111: # --------------------------------------------------------------- user.resource
                   6112: 	if ($space eq 'resource') {
1.651     albertel 6113: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6114: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6115: 		 &&
1.744     albertel 6116: 		 ($symbparm eq &symbread()) ) {	
                   6117: 		# if we are in the middle of processing the resource the
                   6118: 		# get the value we are planning on committing
                   6119:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6120:                     return $Apache::lonhomework::results{$qualifierrest};
                   6121:                 } else {
                   6122:                     return $Apache::lonhomework::history{$qualifierrest};
                   6123:                 }
1.335     albertel 6124: 	    } else {
1.359     albertel 6125: 		my %restored;
1.620     albertel 6126: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6127: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6128: 		} else {
                   6129: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6130: 		}
1.335     albertel 6131: 		return $restored{$qualifierrest};
                   6132: 	    }
1.48      www      6133: # ----------------------------------------------------------------- user.access
                   6134:         } elsif ($space eq 'access') {
1.218     albertel 6135: 	    # FIXME - not supporting calls for a specific user
1.48      www      6136:             return &allowed($qualifier,$rest);
                   6137: # ------------------------------------------ user.preferences, user.environment
                   6138:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6139: 	    if (($uname eq $env{'user.name'}) &&
                   6140: 		($udom eq $env{'user.domain'})) {
                   6141: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6142: 	    } else {
1.359     albertel 6143: 		my %returnhash;
                   6144: 		if (!$publicuser) {
                   6145: 		    %returnhash=&userenvironment($udom,$uname,
                   6146: 						 $qualifierrest);
                   6147: 		}
1.218     albertel 6148: 		return $returnhash{$qualifierrest};
                   6149: 	    }
1.48      www      6150: # ----------------------------------------------------------------- user.course
                   6151:         } elsif ($space eq 'course') {
1.218     albertel 6152: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6153:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6154: # ------------------------------------------------------------------- user.role
                   6155:         } elsif ($space eq 'role') {
1.218     albertel 6156: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6157:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6158:             if ($qualifier eq 'value') {
                   6159: 		return $role;
                   6160:             } elsif ($qualifier eq 'extent') {
                   6161:                 return $where;
                   6162:             }
                   6163: # ----------------------------------------------------------------- user.domain
                   6164:         } elsif ($space eq 'domain') {
1.218     albertel 6165:             return $udom;
1.48      www      6166: # ------------------------------------------------------------------- user.name
                   6167:         } elsif ($space eq 'name') {
1.218     albertel 6168:             return $uname;
1.48      www      6169: # ---------------------------------------------------- Any other user namespace
1.29      www      6170:         } else {
1.359     albertel 6171: 	    my %reply;
                   6172: 	    if (!$publicuser) {
                   6173: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6174: 	    }
                   6175: 	    return $reply{$qualifierrest};
1.48      www      6176:         }
1.236     www      6177:     } elsif ($realm eq 'query') {
                   6178: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6179:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6180: 						[$spacequalifierrest]);
1.620     albertel 6181: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6182:    } elsif ($realm eq 'request') {
1.48      www      6183: # ------------------------------------------------------------- request.browser
                   6184:         if ($space eq 'browser') {
1.430     www      6185: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6186: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6187: 		    return 1;
                   6188: 		} else {
                   6189: 		    return 0;
                   6190: 		}
                   6191: 	    } else {
1.620     albertel 6192: 		return $env{'browser.'.$qualifier};
1.430     www      6193: 	    }
1.57      www      6194: # ------------------------------------------------------------ request.filename
                   6195:         } else {
1.620     albertel 6196:             return $env{'request.'.$spacequalifierrest};
1.29      www      6197:         }
1.28      www      6198:     } elsif ($realm eq 'course') {
1.48      www      6199: # ---------------------------------------------------------- course.description
1.620     albertel 6200:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6201:     } elsif ($realm eq 'resource') {
1.165     www      6202: 
1.620     albertel 6203: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6204: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6205: 	}
1.693     albertel 6206: 
                   6207: 	if ($space eq 'title') {
                   6208: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6209: 	    return &gettitle($symbparm);
                   6210: 	}
                   6211: 	
                   6212: 	if ($space eq 'map') {
                   6213: 	    my ($map) = &decode_symb($symbparm);
                   6214: 	    return &symbread($map);
                   6215: 	}
                   6216: 
                   6217: 	my ($section, $group, @groups);
1.593     albertel 6218: 	my ($courselevelm,$courselevel);
1.539     albertel 6219: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6220: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6221: 
1.218     albertel 6222: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6223: 
1.60      www      6224: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6225: 	    my $symbp=$symbparm;
1.735     albertel 6226: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6227: 
                   6228: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6229: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6230: 
1.620     albertel 6231: 	    if (($env{'user.name'} eq $uname) &&
                   6232: 		($env{'user.domain'} eq $udom)) {
                   6233: 		$section=$env{'request.course.sec'};
1.733     raeburn  6234:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6235:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6236: 	    } else {
1.539     albertel 6237: 		if (! defined($usection)) {
1.551     albertel 6238: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6239: 		} else {
                   6240: 		    $section = $usection;
                   6241: 		}
1.733     raeburn  6242:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6243: 	    }
                   6244: 
                   6245: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6246: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6247: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6248: 
1.593     albertel 6249: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6250: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6251: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6252: 
1.60      www      6253: # ----------------------------------------------------------- first, check user
1.624     albertel 6254: 
                   6255: 	    my $userreply=&resdata($uname,$udom,'user',
                   6256: 				       ($courselevelr,$courselevelm,
                   6257: 					$courselevel));
                   6258: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6259: 
1.594     albertel 6260: # ------------------------------------------------ second, check some of course
1.684     raeburn  6261:             my $coursereply;
1.691     raeburn  6262:             if (@groups > 0) {
                   6263:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6264:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6265:                 if (defined($coursereply)) { return $coursereply; }
                   6266:             }
1.96      www      6267: 
1.684     raeburn  6268: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6269: 				     $env{'course.'.$courseid.'.domain'},
                   6270: 				     'course',
                   6271: 				     ($seclevelr,$seclevelm,$seclevel,
                   6272: 				      $courselevelr));
1.287     albertel 6273: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6274: 
1.60      www      6275: # ------------------------------------------------------ third, check map parms
1.218     albertel 6276: 	    my %parmhash=();
                   6277: 	    my $thisparm='';
                   6278: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6279: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6280: 		    &GDBM_READER(),0640)) {
1.218     albertel 6281: 		$thisparm=$parmhash{$symbparm};
                   6282: 		untie(%parmhash);
                   6283: 	    }
                   6284: 	    if ($thisparm) { return $thisparm; }
                   6285: 	}
1.594     albertel 6286: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6287: 
1.218     albertel 6288: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6289: 	my $filename;
                   6290: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6291: 	if ($symbparm) {
1.409     www      6292: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6293: 	} else {
1.620     albertel 6294: 	    $filename=$env{'request.filename'};
1.282     albertel 6295: 	}
                   6296: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6297: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6298: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6299: 	if (defined($metadata)) { return $metadata; }
1.142     www      6300: 
1.594     albertel 6301: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6302: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6303: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6304: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6305: 				     $env{'course.'.$courseid.'.domain'},
                   6306: 				     'course',
                   6307: 				     ($courselevelm,$courselevel));
1.593     albertel 6308: 	    if (defined($coursereply)) { return $coursereply; }
                   6309: 	}
1.145     www      6310: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6311: 	unless ($space eq '0') {
1.336     albertel 6312: 	    my @parts=split(/_/,$space);
                   6313: 	    my $id=pop(@parts);
                   6314: 	    my $part=join('_',@parts);
                   6315: 	    if ($part eq '') { $part='0'; }
                   6316: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6317: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6318: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6319: 	}
1.395     albertel 6320: 	if ($recurse) { return undef; }
                   6321: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6322: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6323: 
1.48      www      6324: # ---------------------------------------------------- Any other user namespace
                   6325:     } elsif ($realm eq 'environment') {
                   6326: # ----------------------------------------------------------------- environment
1.620     albertel 6327: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6328: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6329: 	} else {
1.770     albertel 6330: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6331: 		return '';
                   6332: 	    }
1.219     albertel 6333: 	    my %returnhash=&userenvironment($udom,$uname,
                   6334: 					    $spacequalifierrest);
                   6335: 	    return $returnhash{$spacequalifierrest};
                   6336: 	}
1.28      www      6337:     } elsif ($realm eq 'system') {
1.48      www      6338: # ----------------------------------------------------------------- system.time
                   6339: 	if ($space eq 'time') {
                   6340: 	    return time;
                   6341:         }
1.696     albertel 6342:     } elsif ($realm eq 'server') {
                   6343: # ----------------------------------------------------------------- system.time
                   6344: 	if ($space eq 'name') {
                   6345: 	    return $ENV{'SERVER_NAME'};
                   6346:         }
1.28      www      6347:     }
1.48      www      6348:     return '';
1.61      www      6349: }
                   6350: 
1.691     raeburn  6351: sub check_group_parms {
                   6352:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6353:     my @groupitems = ();
                   6354:     my $resultitem;
                   6355:     my @levels = ($symbparm,$mapparm,$what);
                   6356:     foreach my $group (@{$groups}) {
                   6357:         foreach my $level (@levels) {
                   6358:              my $item = $courseid.'.['.$group.'].'.$level;
                   6359:              push(@groupitems,$item);
                   6360:         }
                   6361:     }
                   6362:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6363:                             $env{'course.'.$courseid.'.domain'},
                   6364:                                      'course',@groupitems);
                   6365:     return $coursereply;
                   6366: }
                   6367: 
                   6368: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6369:     my ($courseid,@groups) = @_;
                   6370:     @groups = sort(@groups);
1.691     raeburn  6371:     return @groups;
                   6372: }
                   6373: 
1.395     albertel 6374: sub packages_tab_default {
                   6375:     my ($uri,$varname)=@_;
                   6376:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6377: 
                   6378:     my (@extension,@specifics,$do_default);
                   6379:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6380: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6381: 	if ($pack_type eq 'default') {
                   6382: 	    $do_default=1;
                   6383: 	} elsif ($pack_type eq 'extension') {
                   6384: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6385: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6386: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6387: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6388: 	}
                   6389:     }
                   6390:     # first look for a package that matches the requested part id
                   6391:     foreach my $package (@specifics) {
                   6392: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6393: 	next if ($pack_part ne $part);
                   6394: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6395: 	    return $packagetab{"$pack_type&$name&default"};
                   6396: 	}
                   6397:     }
                   6398:     # look for any possible matching non extension_ package
                   6399:     foreach my $package (@specifics) {
                   6400: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6401: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6402: 	    return $packagetab{"$pack_type&$name&default"};
                   6403: 	}
1.585     albertel 6404: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6405: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6406: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6407: 	}
                   6408:     }
1.738     albertel 6409:     # look for any posible extension_ match
                   6410:     foreach my $package (@extension) {
                   6411: 	my ($package,$pack_type)=@{$package};
                   6412: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6413: 	    return $packagetab{"$pack_type&$name&default"};
                   6414: 	}
                   6415: 	if (defined($packagetab{$package."&$name&default"})) {
                   6416: 	    return $packagetab{$package."&$name&default"};
                   6417: 	}
                   6418:     }
                   6419:     # look for a global default setting
                   6420:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6421: 	return $packagetab{"default&$name&default"};
                   6422:     }
1.395     albertel 6423:     return undef;
                   6424: }
                   6425: 
1.334     albertel 6426: sub add_prefix_and_part {
                   6427:     my ($prefix,$part)=@_;
                   6428:     my $keyroot;
                   6429:     if (defined($prefix) && $prefix !~ /^__/) {
                   6430: 	# prefix that has a part already
                   6431: 	$keyroot=$prefix;
                   6432:     } elsif (defined($prefix)) {
                   6433: 	# prefix that is missing a part
                   6434: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6435:     } else {
                   6436: 	# no prefix at all
                   6437: 	if (defined($part)) { $keyroot='_'.$part; }
                   6438:     }
                   6439:     return $keyroot;
                   6440: }
                   6441: 
1.71      www      6442: # ---------------------------------------------------------------- Get metadata
                   6443: 
1.599     albertel 6444: my %metaentry;
1.71      www      6445: sub metadata {
1.176     www      6446:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6447:     $uri=&declutter($uri);
1.288     albertel 6448:     # if it is a non metadata possible uri return quickly
1.529     albertel 6449:     if (($uri eq '') || 
                   6450: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6451: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6452:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6453: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6454: 	return undef;
1.288     albertel 6455:     }
1.73      www      6456:     my $filename=$uri;
                   6457:     $uri=~s/\.meta$//;
1.172     www      6458: #
                   6459: # Is the metadata already cached?
1.177     www      6460: # Look at timestamp of caching
1.172     www      6461: # Everything is cached by the main uri, libraries are never directly cached
                   6462: #
1.428     albertel 6463:     if (!defined($liburi)) {
1.599     albertel 6464: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6465: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6466:     }
                   6467:     {
1.172     www      6468: #
                   6469: # Is this a recursive call for a library?
                   6470: #
1.599     albertel 6471: #	if (! exists($metacache{$uri})) {
                   6472: #	    $metacache{$uri}={};
                   6473: #	}
1.171     www      6474:         if ($liburi) {
                   6475: 	    $liburi=&declutter($liburi);
                   6476:             $filename=$liburi;
1.401     bowersj2 6477:         } else {
1.599     albertel 6478: 	    &devalidate_cache_new('meta',$uri);
                   6479: 	    undef(%metaentry);
1.401     bowersj2 6480: 	}
1.140     www      6481:         my %metathesekeys=();
1.73      www      6482:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6483: 	my $metastring;
1.768     albertel 6484: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6485: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6486: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6487: 	    $metastring=&getfile($file);
1.489     albertel 6488: 	}
1.208     albertel 6489:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6490:         my $token;
1.140     www      6491:         undef %metathesekeys;
1.71      www      6492:         while ($token=$parser->get_token) {
1.339     albertel 6493: 	    if ($token->[0] eq 'S') {
                   6494: 		if (defined($token->[2]->{'package'})) {
1.172     www      6495: #
                   6496: # This is a package - get package info
                   6497: #
1.339     albertel 6498: 		    my $package=$token->[2]->{'package'};
                   6499: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6500: 		    if (defined($token->[2]->{'id'})) { 
                   6501: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6502: 		    }
1.599     albertel 6503: 		    if ($metaentry{':packages'}) {
                   6504: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6505: 		    } else {
1.599     albertel 6506: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6507: 		    }
1.736     albertel 6508: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6509: 			my $part=$keyroot;
                   6510: 			$part=~s/^\_//;
1.736     albertel 6511: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6512: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6513: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6514: 			    # ignore package.tab specified default values
                   6515:                             # here &package_tab_default() will fetch those
                   6516: 			    if ($subp eq 'default') { next; }
1.736     albertel 6517: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6518: 			    my $unikey;
                   6519: 			    if ($pack =~ /_0$/) {
                   6520: 				$unikey='parameter_0_'.$name;
                   6521: 				$part=0;
                   6522: 			    } else {
                   6523: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6524: 			    }
1.339     albertel 6525: 			    if ($subp eq 'display') {
                   6526: 				$value.=' [Part: '.$part.']';
                   6527: 			    }
1.599     albertel 6528: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6529: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6530: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6531: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6532: 			    }
1.599     albertel 6533: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6534: 				$metaentry{':'.$unikey}=
                   6535: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6536: 			    }
1.339     albertel 6537: 			}
                   6538: 		    }
                   6539: 		} else {
1.172     www      6540: #
                   6541: # This is not a package - some other kind of start tag
1.339     albertel 6542: #
                   6543: 		    my $entry=$token->[1];
                   6544: 		    my $unikey;
                   6545: 		    if ($entry eq 'import') {
                   6546: 			$unikey='';
                   6547: 		    } else {
                   6548: 			$unikey=$entry;
                   6549: 		    }
                   6550: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6551: 
                   6552: 		    if (defined($token->[2]->{'id'})) { 
                   6553: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6554: 		    }
1.175     www      6555: 
1.339     albertel 6556: 		    if ($entry eq 'import') {
1.175     www      6557: #
                   6558: # Importing a library here
1.339     albertel 6559: #
                   6560: 			if ($depthcount<20) {
                   6561: 			    my $location=$parser->get_text('/import');
                   6562: 			    my $dir=$filename;
                   6563: 			    $dir=~s|[^/]*$||;
                   6564: 			    $location=&filelocation($dir,$location);
1.736     albertel 6565: 			    my $metadata = 
                   6566: 				&metadata($uri,'keys', $location,$unikey,
                   6567: 					  $depthcount+1);
                   6568: 			    foreach my $meta (split(',',$metadata)) {
                   6569: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6570: 				$metathesekeys{$meta}=1;
1.339     albertel 6571: 			    }
                   6572: 			}
                   6573: 		    } else { 
                   6574: 			
                   6575: 			if (defined($token->[2]->{'name'})) { 
                   6576: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6577: 			}
                   6578: 			$metathesekeys{$unikey}=1;
1.736     albertel 6579: 			foreach my $param (@{$token->[3]}) {
                   6580: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6581: 				$token->[2]->{$param};
1.339     albertel 6582: 			}
                   6583: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6584: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6585: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6586: 		 # only ws inside the tag, and not in default, so use default
                   6587: 		 # as value
1.599     albertel 6588: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6589: 			} else {
1.321     albertel 6590: 		  # either something interesting inside the tag or default
                   6591:                   # uninteresting
1.599     albertel 6592: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6593: 			}
1.172     www      6594: # end of not-a-package not-a-library import
1.339     albertel 6595: 		    }
1.172     www      6596: # end of not-a-package start tag
1.339     albertel 6597: 		}
1.172     www      6598: # the next is the end of "start tag"
1.339     albertel 6599: 	    }
                   6600: 	}
1.483     albertel 6601: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6602: 	$extension = lc($extension);
                   6603: 	if ($extension eq 'htm') { $extension='html'; }
                   6604: 
1.737     albertel 6605: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6606: 	    #no specific packages #how's our extension
                   6607: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6608: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6609: 					 \%metathesekeys);
                   6610: 	}
1.883     albertel 6611: 
                   6612: 	if (!exists($metaentry{':packages'})
                   6613: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6614: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6615: 		#no specific packages well let's get default then
                   6616: 		if ($key!~/^default&/) { next; }
1.488     albertel 6617: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6618: 					     \%metathesekeys);
                   6619: 	    }
                   6620: 	}
1.338     www      6621: # are there custom rights to evaluate
1.599     albertel 6622: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6623: 
1.338     www      6624:     #
                   6625:     # Importing a rights file here
1.339     albertel 6626:     #
                   6627: 	    unless ($depthcount) {
1.599     albertel 6628: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6629: 		my $dir=$filename;
                   6630: 		$dir=~s|[^/]*$||;
                   6631: 		$location=&filelocation($dir,$location);
1.736     albertel 6632: 		my $rights_metadata =
                   6633: 		    &metadata($uri,'keys',$location,'_rights',
                   6634: 			      $depthcount+1);
                   6635: 		foreach my $rights (split(',',$rights_metadata)) {
                   6636: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6637: 		    $metathesekeys{$rights}=1;
1.339     albertel 6638: 		}
                   6639: 	    }
                   6640: 	}
1.737     albertel 6641: 	# uniqifiy package listing
                   6642: 	my %seen;
                   6643: 	my @uniq_packages =
                   6644: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6645: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6646: 
                   6647: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6648: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6649: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6650: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6651: # this is the end of "was not already recently cached
1.71      www      6652:     }
1.599     albertel 6653:     return $metaentry{':'.$what};
1.261     albertel 6654: }
                   6655: 
1.488     albertel 6656: sub metadata_create_package_def {
1.483     albertel 6657:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6658:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6659:     if ($subp eq 'default') { next; }
                   6660:     
1.599     albertel 6661:     if (defined($metaentry{':packages'})) {
                   6662: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6663:     } else {
1.599     albertel 6664: 	$metaentry{':packages'}=$package;
1.483     albertel 6665:     }
                   6666:     my $value=$packagetab{$key};
                   6667:     my $unikey;
                   6668:     $unikey='parameter_0_'.$name;
1.599     albertel 6669:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6670:     $$metathesekeys{$unikey}=1;
1.599     albertel 6671:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6672: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6673:     }
1.599     albertel 6674:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6675: 	$metaentry{':'.$unikey}=
                   6676: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6677:     }
                   6678: }
                   6679: 
1.261     albertel 6680: sub metadata_generate_part0 {
                   6681:     my ($metadata,$metacache,$uri) = @_;
                   6682:     my %allnames;
1.737     albertel 6683:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6684: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6685: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6686: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6687: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6688: 	    $allnames{$name}=$part;
                   6689: 	  }
                   6690: 	}
                   6691:     }
                   6692:     foreach my $name (keys(%allnames)) {
                   6693:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6694:       my $key=":parameter_0_$name";
1.261     albertel 6695:       $$metacache{"$key.part"}='0';
                   6696:       $$metacache{"$key.name"}=$name;
1.428     albertel 6697:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6698: 					   $allnames{$name}.'_'.$name.
                   6699: 					   '.type'};
1.428     albertel 6700:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6701: 			     '.display'};
1.644     www      6702:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6703:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6704:       $$metacache{"$key.display"}=$olddis;
                   6705:     }
1.71      www      6706: }
                   6707: 
1.764     albertel 6708: # ------------------------------------------------------ Devalidate title cache
                   6709: 
                   6710: sub devalidate_title_cache {
                   6711:     my ($url)=@_;
                   6712:     if (!$env{'request.course.id'}) { return; }
                   6713:     my $symb=&symbread($url);
                   6714:     if (!$symb) { return; }
                   6715:     my $key=$env{'request.course.id'}."\0".$symb;
                   6716:     &devalidate_cache_new('title',$key);
                   6717: }
                   6718: 
1.301     www      6719: # ------------------------------------------------- Get the title of a resource
                   6720: 
                   6721: sub gettitle {
                   6722:     my $urlsymb=shift;
                   6723:     my $symb=&symbread($urlsymb);
1.534     albertel 6724:     if ($symb) {
1.620     albertel 6725: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6726: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6727: 	if (defined($cached)) { 
                   6728: 	    return $result;
                   6729: 	}
1.534     albertel 6730: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6731: 	my $title='';
                   6732: 	my %bighash;
1.620     albertel 6733: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6734: 		&GDBM_READER(),0640)) {
                   6735: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6736: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6737: 	    untie %bighash;
                   6738: 	}
                   6739: 	$title=~s/\&colon\;/\:/gs;
                   6740: 	if ($title) {
1.599     albertel 6741: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6742: 	}
                   6743: 	$urlsymb=$url;
                   6744:     }
                   6745:     my $title=&metadata($urlsymb,'title');
                   6746:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6747:     return $title;
1.301     www      6748: }
1.613     albertel 6749: 
1.614     albertel 6750: sub get_slot {
                   6751:     my ($which,$cnum,$cdom)=@_;
                   6752:     if (!$cnum || !$cdom) {
1.790     albertel 6753: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6754: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6755: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6756:     }
1.703     albertel 6757:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6758:     my %slotinfo;
                   6759:     if (exists($remembered{$key})) {
                   6760: 	$slotinfo{$which} = $remembered{$key};
                   6761:     } else {
                   6762: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6763: 	&Apache::lonhomework::showhash(%slotinfo);
                   6764: 	my ($tmp)=keys(%slotinfo);
                   6765: 	if ($tmp=~/^error:/) { return (); }
                   6766: 	$remembered{$key} = $slotinfo{$which};
                   6767:     }
1.616     albertel 6768:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6769: 	return %{$slotinfo{$which}};
                   6770:     }
                   6771:     return $slotinfo{$which};
1.614     albertel 6772: }
1.31      www      6773: # ------------------------------------------------- Update symbolic store links
                   6774: 
                   6775: sub symblist {
                   6776:     my ($mapname,%newhash)=@_;
1.438     www      6777:     $mapname=&deversion(&declutter($mapname));
1.31      www      6778:     my %hash;
1.620     albertel 6779:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6780:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6781:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6782: 	    foreach my $url (keys %newhash) {
                   6783: 		next if ($url eq 'last_known'
                   6784: 			 && $env{'form.no_update_last_known'});
                   6785: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6786: 						    $newhash{$url}->[1],
                   6787: 						    $newhash{$url}->[0]);
1.191     harris41 6788:             }
1.31      www      6789:             if (untie(%hash)) {
                   6790: 		return 'ok';
                   6791:             }
                   6792:         }
                   6793:     }
                   6794:     return 'error';
1.212     www      6795: }
                   6796: 
                   6797: # --------------------------------------------------------------- Verify a symb
                   6798: 
                   6799: sub symbverify {
1.510     www      6800:     my ($symb,$thisurl)=@_;
                   6801:     my $thisfn=$thisurl;
1.439     www      6802:     $thisfn=&declutter($thisfn);
1.215     www      6803: # direct jump to resource in page or to a sequence - will construct own symbs
                   6804:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6805: # check URL part
1.409     www      6806:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6807: 
1.431     www      6808:     unless ($url eq $thisfn) { return 0; }
1.213     www      6809: 
1.216     www      6810:     $symb=&symbclean($symb);
1.510     www      6811:     $thisurl=&deversion($thisurl);
1.439     www      6812:     $thisfn=&deversion($thisfn);
1.213     www      6813: 
                   6814:     my %bighash;
                   6815:     my $okay=0;
1.431     www      6816: 
1.620     albertel 6817:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6818:                             &GDBM_READER(),0640)) {
1.510     www      6819:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6820:         unless ($ids) { 
1.510     www      6821:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6822:         }
                   6823:         if ($ids) {
                   6824: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6825: 	    foreach my $id (split(/\,/,$ids)) {
                   6826: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6827:                if (
                   6828:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6829:    eq $symb) { 
1.620     albertel 6830: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6831: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6832: 		       $okay=1; 
                   6833: 		   }
                   6834: 	       }
1.216     www      6835: 	   }
                   6836:         }
1.213     www      6837: 	untie(%bighash);
                   6838:     }
                   6839:     return $okay;
1.31      www      6840: }
                   6841: 
1.210     www      6842: # --------------------------------------------------------------- Clean-up symb
                   6843: 
                   6844: sub symbclean {
                   6845:     my $symb=shift;
1.568     albertel 6846:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6847: # remove version from map
                   6848:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6849: 
1.210     www      6850: # remove version from URL
                   6851:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6852: 
1.507     www      6853: # remove wrapper
                   6854: 
1.510     www      6855:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6856:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6857:     return $symb;
1.409     www      6858: }
                   6859: 
                   6860: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6861: 
                   6862: sub encode_symb {
                   6863:     my ($map,$resid,$url)=@_;
                   6864:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6865: }
1.409     www      6866: 
                   6867: sub decode_symb {
1.568     albertel 6868:     my $symb=shift;
                   6869:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6870:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6871:     return (&fixversion($map),$resid,&fixversion($url));
                   6872: }
                   6873: 
                   6874: sub fixversion {
                   6875:     my $fn=shift;
1.609     banghart 6876:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6877:     my %bighash;
                   6878:     my $uri=&clutter($fn);
1.620     albertel 6879:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6880: # is this cached?
1.599     albertel 6881:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6882:     if (defined($cached)) { return $result; }
                   6883: # unfortunately not cached, or expired
1.620     albertel 6884:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6885: 	    &GDBM_READER(),0640)) {
                   6886:  	if ($bighash{'version_'.$uri}) {
                   6887:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6888:  	    unless (($version eq 'mostrecent') || 
                   6889: 		    ($version==&getversion($uri))) {
1.440     www      6890:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6891:  	    }
                   6892:  	}
                   6893:  	untie %bighash;
1.413     www      6894:     }
1.599     albertel 6895:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6896: }
                   6897: 
                   6898: sub deversion {
                   6899:     my $url=shift;
                   6900:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6901:     return $url;
1.210     www      6902: }
                   6903: 
1.31      www      6904: # ------------------------------------------------------ Return symb list entry
                   6905: 
                   6906: sub symbread {
1.249     www      6907:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6908:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6909:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6910: # no filename provided? try from environment
1.44      www      6911:     unless ($thisfn) {
1.620     albertel 6912:         if ($env{'request.symb'}) {
                   6913: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6914: 	}
1.620     albertel 6915: 	$thisfn=$env{'request.filename'};
1.44      www      6916:     }
1.569     albertel 6917:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6918: # is that filename actually a symb? Verify, clean, and return
                   6919:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6920: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6921: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6922: 	}
1.242     www      6923:     }
1.44      www      6924:     $thisfn=declutter($thisfn);
1.31      www      6925:     my %hash;
1.37      www      6926:     my %bighash;
                   6927:     my $syval='';
1.620     albertel 6928:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6929:         my $targetfn = $thisfn;
1.609     banghart 6930:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6931:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6932:         }
1.687     albertel 6933: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6934: 	    $targetfn=$1;
                   6935: 	}
1.620     albertel 6936:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6937:                       &GDBM_READER(),0640)) {
1.481     raeburn  6938: 	    $syval=$hash{$targetfn};
1.37      www      6939:             untie(%hash);
                   6940:         }
                   6941: # ---------------------------------------------------------- There was an entry
                   6942:         if ($syval) {
1.601     albertel 6943: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6944: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6945: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6946: 		    #return $env{$cache_str}='';
1.601     albertel 6947: 		#}    
                   6948: 		#$syval.=$1;
                   6949: 	    #}
1.37      www      6950:         } else {
                   6951: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6952:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6953:                             &GDBM_READER(),0640)) {
1.37      www      6954: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6955:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6956:               unless ($ids) { 
                   6957:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6958:               }
                   6959:               unless ($ids) {
                   6960: # alias?
                   6961: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6962:               }
1.37      www      6963:               if ($ids) {
                   6964: # ------------------------------------------------------------------- Has ID(s)
                   6965:                  my @possibilities=split(/\,/,$ids);
1.39      www      6966:                  if ($#possibilities==0) {
                   6967: # ----------------------------------------------- There is only one possibility
1.37      www      6968: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6969: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6970: 						    $resid,$thisfn);
1.249     www      6971:                  } elsif (!$donotrecurse) {
1.39      www      6972: # ------------------------------------------ There is more than one possibility
                   6973:                      my $realpossible=0;
1.800     albertel 6974:                      foreach my $id (@possibilities) {
                   6975: 			 my $file=$bighash{'src_'.$id};
1.39      www      6976:                          if (&allowed('bre',$file)) {
1.800     albertel 6977:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6978:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6979: 				$realpossible++;
1.626     albertel 6980:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6981: 						    $resid,$thisfn);
1.39      www      6982:                             }
                   6983: 			 }
1.191     harris41 6984:                      }
1.39      www      6985: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6986:                  } else {
                   6987:                      $syval='';
1.37      www      6988:                  }
                   6989: 	      }
                   6990:               untie(%bighash)
1.481     raeburn  6991:            }
1.31      www      6992:         }
1.62      www      6993:         if ($syval) {
1.620     albertel 6994: 	    return $env{$cache_str}=$syval;
1.62      www      6995:         }
1.31      www      6996:     }
1.44      www      6997:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6998:     return $env{$cache_str}='';
1.31      www      6999: }
                   7000: 
                   7001: # ---------------------------------------------------------- Return random seed
                   7002: 
1.32      www      7003: sub numval {
                   7004:     my $txt=shift;
                   7005:     $txt=~tr/A-J/0-9/;
                   7006:     $txt=~tr/a-j/0-9/;
                   7007:     $txt=~tr/K-T/0-9/;
                   7008:     $txt=~tr/k-t/0-9/;
                   7009:     $txt=~tr/U-Z/0-5/;
                   7010:     $txt=~tr/u-z/0-5/;
                   7011:     $txt=~s/\D//g;
1.564     albertel 7012:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7013:     return int($txt);
1.368     albertel 7014: }
                   7015: 
1.484     albertel 7016: sub numval2 {
                   7017:     my $txt=shift;
                   7018:     $txt=~tr/A-J/0-9/;
                   7019:     $txt=~tr/a-j/0-9/;
                   7020:     $txt=~tr/K-T/0-9/;
                   7021:     $txt=~tr/k-t/0-9/;
                   7022:     $txt=~tr/U-Z/0-5/;
                   7023:     $txt=~tr/u-z/0-5/;
                   7024:     $txt=~s/\D//g;
                   7025:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7026:     my $total;
                   7027:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7028:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7029:     return int($total);
                   7030: }
                   7031: 
1.575     albertel 7032: sub numval3 {
                   7033:     use integer;
                   7034:     my $txt=shift;
                   7035:     $txt=~tr/A-J/0-9/;
                   7036:     $txt=~tr/a-j/0-9/;
                   7037:     $txt=~tr/K-T/0-9/;
                   7038:     $txt=~tr/k-t/0-9/;
                   7039:     $txt=~tr/U-Z/0-5/;
                   7040:     $txt=~tr/u-z/0-5/;
                   7041:     $txt=~s/\D//g;
                   7042:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7043:     my $total;
                   7044:     foreach my $val (@txts) { $total+=$val; }
                   7045:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7046:     return $total;
                   7047: }
                   7048: 
1.675     albertel 7049: sub digest {
                   7050:     my ($data)=@_;
                   7051:     my $digest=&Digest::MD5::md5($data);
                   7052:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7053:     my ($e,$f);
                   7054:     {
                   7055:         use integer;
                   7056:         $e=($a+$b);
                   7057:         $f=($c+$d);
                   7058:         if ($_64bit) {
                   7059:             $e=(($e<<32)>>32);
                   7060:             $f=(($f<<32)>>32);
                   7061:         }
                   7062:     }
                   7063:     if (wantarray) {
                   7064: 	return ($e,$f);
                   7065:     } else {
                   7066: 	my $g;
                   7067: 	{
                   7068: 	    use integer;
                   7069: 	    $g=($e+$f);
                   7070: 	    if ($_64bit) {
                   7071: 		$g=(($g<<32)>>32);
                   7072: 	    }
                   7073: 	}
                   7074: 	return $g;
                   7075:     }
                   7076: }
                   7077: 
1.368     albertel 7078: sub latest_rnd_algorithm_id {
1.675     albertel 7079:     return '64bit5';
1.366     albertel 7080: }
1.32      www      7081: 
1.503     albertel 7082: sub get_rand_alg {
                   7083:     my ($courseid)=@_;
1.790     albertel 7084:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7085:     if ($courseid) {
1.620     albertel 7086: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7087:     }
                   7088:     return &latest_rnd_algorithm_id();
                   7089: }
                   7090: 
1.562     albertel 7091: sub validCODE {
                   7092:     my ($CODE)=@_;
                   7093:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7094:     return 0;
                   7095: }
                   7096: 
1.491     albertel 7097: sub getCODE {
1.620     albertel 7098:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7099:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7100: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7101: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7102: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7103:     }
                   7104:     return undef;
                   7105: }
                   7106: 
1.31      www      7107: sub rndseed {
1.155     albertel 7108:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7109:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7110:     if (!defined($symb)) {
1.366     albertel 7111: 	unless ($symb=$wsymb) { return time; }
                   7112:     }
                   7113:     if (!$courseid) { $courseid=$wcourseid; }
                   7114:     if (!$domain) { $domain=$wdomain; }
                   7115:     if (!$username) { $username=$wusername }
1.503     albertel 7116:     my $which=&get_rand_alg();
1.803     albertel 7117: 
1.491     albertel 7118:     if (defined(&getCODE())) {
1.675     albertel 7119: 	if ($which eq '64bit5') {
                   7120: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7121: 	} elsif ($which eq '64bit4') {
1.575     albertel 7122: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7123: 	} else {
                   7124: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7125: 	}
1.675     albertel 7126:     } elsif ($which eq '64bit5') {
                   7127: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7128:     } elsif ($which eq '64bit4') {
                   7129: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7130:     } elsif ($which eq '64bit3') {
                   7131: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7132:     } elsif ($which eq '64bit2') {
                   7133: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7134:     } elsif ($which eq '64bit') {
                   7135: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7136:     }
                   7137:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7138: }
                   7139: 
                   7140: sub rndseed_32bit {
                   7141:     my ($symb,$courseid,$domain,$username)=@_;
                   7142:     {
                   7143: 	use integer;
                   7144: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7145: 	my $symbseed=numval($symb) << 22;
                   7146: 	my $namechck=unpack("%32C*",$username) << 17;
                   7147: 	my $nameseed=numval($username) << 12;
                   7148: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7149: 	my $courseseed=unpack("%32C*",$courseid);
                   7150: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7151: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7152: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7153: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7154: 	return $num;
                   7155:     }
                   7156: }
                   7157: 
                   7158: sub rndseed_64bit {
                   7159:     my ($symb,$courseid,$domain,$username)=@_;
                   7160:     {
                   7161: 	use integer;
                   7162: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7163: 	my $symbseed=numval($symb) << 10;
                   7164: 	my $namechck=unpack("%32S*",$username);
                   7165: 	
                   7166: 	my $nameseed=numval($username) << 21;
                   7167: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7168: 	my $courseseed=unpack("%32S*",$courseid);
                   7169: 	
                   7170: 	my $num1=$symbchck+$symbseed+$namechck;
                   7171: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7172: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7173: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7174: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7175: 	return "$num1,$num2";
1.155     albertel 7176:     }
1.366     albertel 7177: }
                   7178: 
1.443     albertel 7179: sub rndseed_64bit2 {
                   7180:     my ($symb,$courseid,$domain,$username)=@_;
                   7181:     {
                   7182: 	use integer;
                   7183: 	# strings need to be an even # of cahracters long, it it is odd the
                   7184:         # last characters gets thrown away
                   7185: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7186: 	my $symbseed=numval($symb) << 10;
                   7187: 	my $namechck=unpack("%32S*",$username.' ');
                   7188: 	
                   7189: 	my $nameseed=numval($username) << 21;
1.501     albertel 7190: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7191: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7192: 	
                   7193: 	my $num1=$symbchck+$symbseed+$namechck;
                   7194: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7195: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7196: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7197: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7198: 	return "$num1,$num2";
                   7199:     }
                   7200: }
                   7201: 
                   7202: sub rndseed_64bit3 {
                   7203:     my ($symb,$courseid,$domain,$username)=@_;
                   7204:     {
                   7205: 	use integer;
                   7206: 	# strings need to be an even # of cahracters long, it it is odd the
                   7207:         # last characters gets thrown away
                   7208: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7209: 	my $symbseed=numval2($symb) << 10;
                   7210: 	my $namechck=unpack("%32S*",$username.' ');
                   7211: 	
                   7212: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7213: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7214: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7215: 	
                   7216: 	my $num1=$symbchck+$symbseed+$namechck;
                   7217: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7218: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7219: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7220: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7221: 	
1.503     albertel 7222: 	return "$num1:$num2";
1.443     albertel 7223:     }
                   7224: }
                   7225: 
1.575     albertel 7226: sub rndseed_64bit4 {
                   7227:     my ($symb,$courseid,$domain,$username)=@_;
                   7228:     {
                   7229: 	use integer;
                   7230: 	# strings need to be an even # of cahracters long, it it is odd the
                   7231:         # last characters gets thrown away
                   7232: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7233: 	my $symbseed=numval3($symb) << 10;
                   7234: 	my $namechck=unpack("%32S*",$username.' ');
                   7235: 	
                   7236: 	my $nameseed=numval3($username) << 21;
                   7237: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7238: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7239: 	
                   7240: 	my $num1=$symbchck+$symbseed+$namechck;
                   7241: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7242: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7243: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7244: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7245: 	
                   7246: 	return "$num1:$num2";
                   7247:     }
                   7248: }
                   7249: 
1.675     albertel 7250: sub rndseed_64bit5 {
                   7251:     my ($symb,$courseid,$domain,$username)=@_;
                   7252:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7253:     return "$num1:$num2";
                   7254: }
                   7255: 
1.366     albertel 7256: sub rndseed_CODE_64bit {
                   7257:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7258:     {
1.366     albertel 7259: 	use integer;
1.443     albertel 7260: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7261: 	my $symbseed=numval2($symb);
1.491     albertel 7262: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7263: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7264: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7265: 	my $num1=$symbseed+$CODEchck;
                   7266: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7267: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7268: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7269: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7270: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7271: 	return "$num1:$num2";
1.366     albertel 7272:     }
                   7273: }
                   7274: 
1.575     albertel 7275: sub rndseed_CODE_64bit4 {
                   7276:     my ($symb,$courseid,$domain,$username)=@_;
                   7277:     {
                   7278: 	use integer;
                   7279: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7280: 	my $symbseed=numval3($symb);
                   7281: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7282: 	my $CODEseed=numval3(&getCODE());
                   7283: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7284: 	my $num1=$symbseed+$CODEchck;
                   7285: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7286: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7287: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7288: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7289: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7290: 	return "$num1:$num2";
                   7291:     }
                   7292: }
                   7293: 
1.675     albertel 7294: sub rndseed_CODE_64bit5 {
                   7295:     my ($symb,$courseid,$domain,$username)=@_;
                   7296:     my $code = &getCODE();
                   7297:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7298:     return "$num1:$num2";
                   7299: }
                   7300: 
1.366     albertel 7301: sub setup_random_from_rndseed {
                   7302:     my ($rndseed)=@_;
1.503     albertel 7303:     if ($rndseed =~/([,:])/) {
                   7304: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7305: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7306:     } else {
                   7307: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7308:     }
1.36      albertel 7309: }
                   7310: 
1.474     albertel 7311: sub latest_receipt_algorithm_id {
1.835     albertel 7312:     return 'receipt3';
1.474     albertel 7313: }
                   7314: 
1.480     www      7315: sub recunique {
                   7316:     my $fucourseid=shift;
                   7317:     my $unique;
1.835     albertel 7318:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7319: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7320: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7321:     } else {
                   7322: 	$unique=$perlvar{'lonReceipt'};
                   7323:     }
                   7324:     return unpack("%32C*",$unique);
                   7325: }
                   7326: 
                   7327: sub recprefix {
                   7328:     my $fucourseid=shift;
                   7329:     my $prefix;
1.835     albertel 7330:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7331: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7332: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7333:     } else {
                   7334: 	$prefix=$perlvar{'lonHostID'};
                   7335:     }
                   7336:     return unpack("%32C*",$prefix);
                   7337: }
                   7338: 
1.76      www      7339: sub ireceipt {
1.474     albertel 7340:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7341: 
                   7342:     my $return =&recprefix($fucourseid).'-';
                   7343: 
                   7344:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7345: 	$env{'request.state'} eq 'construct') {
                   7346: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7347: 	return $return;
                   7348:     }
                   7349: 
1.76      www      7350:     my $cuname=unpack("%32C*",$funame);
                   7351:     my $cudom=unpack("%32C*",$fudom);
                   7352:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7353:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7354:     my $cunique=&recunique($fucourseid);
1.474     albertel 7355:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7356:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7357: 
1.790     albertel 7358: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7359: 			       
                   7360: 	$return.= ($cunique%$cuname+
                   7361: 		   $cunique%$cudom+
                   7362: 		   $cusymb%$cuname+
                   7363: 		   $cusymb%$cudom+
                   7364: 		   $cucourseid%$cuname+
                   7365: 		   $cucourseid%$cudom+
                   7366: 		   $cpart%$cuname+
                   7367: 		   $cpart%$cudom);
                   7368:     } else {
                   7369: 	$return.= ($cunique%$cuname+
                   7370: 		   $cunique%$cudom+
                   7371: 		   $cusymb%$cuname+
                   7372: 		   $cusymb%$cudom+
                   7373: 		   $cucourseid%$cuname+
                   7374: 		   $cucourseid%$cudom);
                   7375:     }
                   7376:     return $return;
1.76      www      7377: }
                   7378: 
                   7379: sub receipt {
1.474     albertel 7380:     my ($part)=@_;
1.790     albertel 7381:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7382:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7383: }
1.260     ng       7384: 
1.790     albertel 7385: sub whichuser {
                   7386:     my ($passedsymb)=@_;
                   7387:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7388:     if (defined($env{'form.grade_symb'})) {
                   7389: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7390: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7391: 	if (!$allowed &&
                   7392: 	    exists($env{'request.course.sec'}) &&
                   7393: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7394: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7395: 			      '/'.$env{'request.course.sec'});
                   7396: 	}
                   7397: 	if ($allowed) {
                   7398: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7399: 	    $courseid=$tmp_courseid;
                   7400: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7401: 	    ($name)=&get_env_multiple('form.grade_username');
                   7402: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7403: 	}
                   7404:     }
                   7405:     if (!$passedsymb) {
                   7406: 	$symb=&symbread();
                   7407:     } else {
                   7408: 	$symb=$passedsymb;
                   7409:     }
                   7410:     $courseid=$env{'request.course.id'};
                   7411:     $domain=$env{'user.domain'};
                   7412:     $name=$env{'user.name'};
                   7413:     if ($name eq 'public' && $domain eq 'public') {
                   7414: 	if (!defined($env{'form.username'})) {
                   7415: 	    $env{'form.username'}.=time.rand(10000000);
                   7416: 	}
                   7417: 	$name.=$env{'form.username'};
                   7418:     }
                   7419:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7420: 
                   7421: }
                   7422: 
1.36      albertel 7423: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7424: # returns either the contents of the file or 
                   7425: # -1 if the file doesn't exist
1.481     raeburn  7426: #
                   7427: # if the target is a file that was uploaded via DOCS, 
                   7428: # a check will be made to see if a current copy exists on the local server,
                   7429: # if it does this will be served, otherwise a copy will be retrieved from
                   7430: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7431: # the local server.   
1.472     albertel 7432: 
1.36      albertel 7433: sub getfile {
1.538     albertel 7434:     my ($file) = @_;
1.609     banghart 7435:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7436:     &repcopy($file);
                   7437:     return &readfile($file);
                   7438: }
                   7439: 
                   7440: sub repcopy_userfile {
                   7441:     my ($file)=@_;
1.609     banghart 7442:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7443:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7444:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7445: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7446:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7447:     if (-e "$file") {
1.828     www      7448: # we already have a local copy, check it out
1.538     albertel 7449: 	my @fileinfo = stat($file);
1.828     www      7450: 	my $rtncode;
                   7451: 	my $info;
1.538     albertel 7452: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7453: 	if ($lwpresp ne 'ok') {
1.828     www      7454: # there is no such file anymore, even though we had a local copy
1.482     albertel 7455: 	    if ($rtncode eq '404') {
1.538     albertel 7456: 		unlink($file);
1.482     albertel 7457: 	    }
                   7458: 	    return -1;
                   7459: 	}
                   7460: 	if ($info < $fileinfo[9]) {
1.828     www      7461: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7462: 	    return 'ok';
1.828     www      7463: 	} else {
                   7464: # the file is outdated, get rid of it
                   7465: 	    unlink($file);
1.482     albertel 7466: 	}
1.828     www      7467:     }
                   7468: # one way or the other, at this point, we don't have the file
                   7469: # construct the correct path for the file
                   7470:     my @parts = ($cdom,$cnum); 
                   7471:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7472: 	push @parts, split(/\//,$1);
                   7473:     }
                   7474:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7475:     foreach my $part (@parts) {
                   7476: 	$path .= '/'.$part;
                   7477: 	if (!-e $path) {
                   7478: 	    mkdir($path,0770);
1.482     albertel 7479: 	}
                   7480:     }
1.828     www      7481: # now the path exists for sure
                   7482: # get a user agent
                   7483:     my $ua=new LWP::UserAgent;
                   7484:     my $transferfile=$file.'.in.transfer';
                   7485: # FIXME: this should flock
                   7486:     if (-e $transferfile) { return 'ok'; }
                   7487:     my $request;
                   7488:     $uri=~s/^\///;
1.838     albertel 7489:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7490:     my $response=$ua->request($request,$transferfile);
                   7491: # did it work?
                   7492:     if ($response->is_error()) {
                   7493: 	unlink($transferfile);
                   7494: 	&logthis("Userfile repcopy failed for $uri");
                   7495: 	return -1;
                   7496:     }
                   7497: # worked, rename the transfer file
                   7498:     rename($transferfile,$file);
1.607     raeburn  7499:     return 'ok';
1.481     raeburn  7500: }
                   7501: 
1.517     albertel 7502: sub tokenwrapper {
                   7503:     my $uri=shift;
1.552     albertel 7504:     $uri=~s|^http\://([^/]+)||;
                   7505:     $uri=~s|^/||;
1.620     albertel 7506:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7507:     my $token=$1;
1.552     albertel 7508:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7509:     if ($udom && $uname && $file) {
                   7510: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7511:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7512:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7513:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7514:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7515:     } else {
                   7516:         return '/adm/notfound.html';
                   7517:     }
                   7518: }
                   7519: 
1.828     www      7520: # call with reqtype HEAD: get last modification time
                   7521: # call with reqtype GET: get the file contents
                   7522: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7523: #
1.481     raeburn  7524: sub getuploaded {
                   7525:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7526:     $uri=~s/^\///;
1.838     albertel 7527:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7528:     my $ua=new LWP::UserAgent;
                   7529:     my $request=new HTTP::Request($reqtype,$uri);
                   7530:     my $response=$ua->request($request);
                   7531:     $$rtncode = $response->code;
1.482     albertel 7532:     if (! $response->is_success()) {
                   7533: 	return 'failed';
                   7534:     }      
                   7535:     if ($reqtype eq 'HEAD') {
1.486     www      7536: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7537:     } elsif ($reqtype eq 'GET') {
                   7538: 	$$info = $response->content;
1.472     albertel 7539:     }
1.482     albertel 7540:     return 'ok';
1.36      albertel 7541: }
                   7542: 
1.481     raeburn  7543: sub readfile {
                   7544:     my $file = shift;
                   7545:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7546:     my $fh;
                   7547:     open($fh,"<$file");
                   7548:     my $a='';
1.800     albertel 7549:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7550:     return $a;
                   7551: }
                   7552: 
1.36      albertel 7553: sub filelocation {
1.590     banghart 7554:     my ($dir,$file) = @_;
                   7555:     my $location;
                   7556:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7557: 
                   7558:     if ($file =~ m-^/adm/-) {
                   7559: 	$file=~s-^/adm/wrapper/-/-;
                   7560: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7561:     }
1.882     albertel 7562: 
1.590     banghart 7563:     if ($file=~m:^/~:) { # is a contruction space reference
                   7564:         $location = $file;
                   7565:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7566:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7567: 	# is a correct contruction space reference
                   7568:         $location = $file;
1.609     banghart 7569:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7570:         my ($udom,$uname,$filename)=
1.811     albertel 7571:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7572:         my $home=&homeserver($uname,$udom);
                   7573:         my $is_me=0;
                   7574:         my @ids=&current_machine_ids();
                   7575:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7576:         if ($is_me) {
1.740     www      7577:   	    $location=&propath($udom,$uname).
1.590     banghart 7578:   	      '/userfiles/'.$filename;
                   7579:         } else {
                   7580:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7581:   	      $udom.'/'.$uname.'/'.$filename;
                   7582:         }
1.882     albertel 7583:     } elsif ($file =~ m-^/adm/-) {
                   7584: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7585:     } else {
                   7586:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7587:         $file=~s:^/res/:/:;
                   7588:         if ( !( $file =~ m:^/:) ) {
                   7589:             $location = $dir. '/'.$file;
                   7590:         } else {
                   7591:             $location = '/home/httpd/html/res'.$file;
                   7592:         }
1.59      albertel 7593:     }
1.590     banghart 7594:     $location=~s://+:/:g; # remove duplicate /
                   7595:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7596:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7597:     return $location;
1.46      www      7598: }
1.36      albertel 7599: 
1.46      www      7600: sub hreflocation {
                   7601:     my ($dir,$file)=@_;
1.460     albertel 7602:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7603: 	$file=filelocation($dir,$file);
1.700     albertel 7604:     } elsif ($file=~m-^/adm/-) {
                   7605: 	$file=~s-^/adm/wrapper/-/-;
                   7606: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7607:     }
                   7608:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7609: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7610:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7611: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7612:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7613: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7614: 	    -/uploaded/$1/$2/-x;
1.46      www      7615:     }
1.462     albertel 7616:     return $file;
1.465     albertel 7617: }
                   7618: 
                   7619: sub current_machine_domains {
1.853     albertel 7620:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7621: }
                   7622: 
                   7623: sub machine_domains {
                   7624:     my ($hostname) = @_;
1.465     albertel 7625:     my @domains;
1.838     albertel 7626:     my %hostname = &all_hostnames();
1.465     albertel 7627:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7628: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7629: 	if ($hostname eq $name) {
1.844     albertel 7630: 	    push(@domains,&host_domain($id));
1.465     albertel 7631: 	}
                   7632:     }
                   7633:     return @domains;
                   7634: }
                   7635: 
                   7636: sub current_machine_ids {
1.853     albertel 7637:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7638: }
                   7639: 
                   7640: sub machine_ids {
                   7641:     my ($hostname) = @_;
                   7642:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7643:     my @ids;
1.888     albertel 7644:     my %name_to_host = &all_names();
1.889     albertel 7645:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7646: 	return @{ $name_to_host{$hostname} };
                   7647:     }
                   7648:     return;
1.31      www      7649: }
                   7650: 
1.824     raeburn  7651: sub additional_machine_domains {
                   7652:     my @domains;
                   7653:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7654:     while( my $line = <$fh>) {
                   7655:         $line =~ s/\s//g;
                   7656:         push(@domains,$line);
                   7657:     }
                   7658:     return @domains;
                   7659: }
                   7660: 
                   7661: sub default_login_domain {
                   7662:     my $domain = $perlvar{'lonDefDomain'};
                   7663:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7664:     foreach my $posdom (&current_machine_domains(),
                   7665:                         &additional_machine_domains()) {
                   7666:         if (lc($posdom) eq lc($testdomain)) {
                   7667:             $domain=$posdom;
                   7668:             last;
                   7669:         }
                   7670:     }
                   7671:     return $domain;
                   7672: }
                   7673: 
1.31      www      7674: # ------------------------------------------------------------- Declutters URLs
                   7675: 
                   7676: sub declutter {
                   7677:     my $thisfn=shift;
1.569     albertel 7678:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7679:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7680:     $thisfn=~s/^\///;
1.697     albertel 7681:     $thisfn=~s|^adm/wrapper/||;
                   7682:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7683:     $thisfn=~s/^res\///;
1.235     www      7684:     $thisfn=~s/\?.+$//;
1.268     www      7685:     return $thisfn;
                   7686: }
                   7687: 
                   7688: # ------------------------------------------------------------- Clutter up URLs
                   7689: 
                   7690: sub clutter {
                   7691:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7692:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7693: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7694:        $thisfn='/res'.$thisfn; 
                   7695:     }
1.694     albertel 7696:     if ($thisfn !~m|/adm|) {
1.695     albertel 7697: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7698: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7699: 	} else {
                   7700: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7701: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7702: 	    if ($embstyle eq 'ssi'
                   7703: 		|| ($embstyle eq 'hdn')
                   7704: 		|| ($embstyle eq 'rat')
                   7705: 		|| ($embstyle eq 'prv')
                   7706: 		|| ($embstyle eq 'ign')) {
                   7707: 		#do nothing with these
                   7708: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7709: 		|| ($embstyle eq 'emb')
                   7710: 		|| ($embstyle eq 'wrp')) {
                   7711: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7712: 	    } elsif ($embstyle eq 'unk'
                   7713: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7714: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7715: 	    } else {
1.718     www      7716: #		&logthis("Got a blank emb style");
1.695     albertel 7717: 	    }
1.694     albertel 7718: 	}
                   7719:     }
1.31      www      7720:     return $thisfn;
1.12      www      7721: }
                   7722: 
1.787     albertel 7723: sub clutter_with_no_wrapper {
                   7724:     my $uri = &clutter(shift);
                   7725:     if ($uri =~ m-^/adm/-) {
                   7726: 	$uri =~ s-^/adm/wrapper/-/-;
                   7727: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7728:     }
                   7729:     return $uri;
                   7730: }
                   7731: 
1.557     albertel 7732: sub freeze_escape {
                   7733:     my ($value)=@_;
                   7734:     if (ref($value)) {
                   7735: 	$value=&nfreeze($value);
                   7736: 	return '__FROZEN__'.&escape($value);
                   7737:     }
                   7738:     return &escape($value);
                   7739: }
                   7740: 
1.11      www      7741: 
1.557     albertel 7742: sub thaw_unescape {
                   7743:     my ($value)=@_;
                   7744:     if ($value =~ /^__FROZEN__/) {
                   7745: 	substr($value,0,10,undef);
                   7746: 	$value=&unescape($value);
                   7747: 	return &thaw($value);
                   7748:     }
                   7749:     return &unescape($value);
                   7750: }
                   7751: 
1.436     albertel 7752: sub correct_line_ends {
                   7753:     my ($result)=@_;
                   7754:     $$result =~s/\r\n/\n/mg;
                   7755:     $$result =~s/\r/\n/mg;
1.415     albertel 7756: }
1.1       albertel 7757: # ================================================================ Main Program
                   7758: 
1.184     www      7759: sub goodbye {
1.204     albertel 7760:    &logthis("Starting Shut down");
1.443     albertel 7761: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7762:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7763: #converted
1.599     albertel 7764: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7765:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7766: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7767: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7768: #1.1 only
1.870     albertel 7769: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7770: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7771: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7772: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7773:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7774:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7775:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7776:    &flushcourselogs();
                   7777:    &logthis("Shutting down");
                   7778: }
                   7779: 
1.852     albertel 7780: sub get_dns {
1.869     albertel 7781:     my ($url,$func,$ignore_cache) = @_;
                   7782:     if (!$ignore_cache) {
                   7783: 	my ($content,$cached)=
                   7784: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7785: 	if ($cached) {
                   7786: 	    &$func($content);
                   7787: 	    return;
                   7788: 	}
                   7789:     }
                   7790: 
                   7791:     my %alldns;
1.852     albertel 7792:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7793:     foreach my $dns (<$config>) {
                   7794: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7795: 	$alldns{$1} = 1;
                   7796:     }
                   7797:     while (%alldns) {
                   7798: 	my ($dns) = keys(%alldns);
                   7799: 	delete($alldns{$dns});
1.852     albertel 7800: 	my $ua=new LWP::UserAgent;
                   7801: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7802: 	my $response=$ua->request($request);
                   7803: 	next if ($response->is_error());
                   7804: 	my @content = split("\n",$response->content);
1.869     albertel 7805: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7806: 	&$func(\@content);
1.869     albertel 7807: 	return;
1.852     albertel 7808:     }
                   7809:     close($config);
1.871     albertel 7810:     my $which = (split('/',$url))[3];
                   7811:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7812:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7813:     my @content = <$config>;
                   7814:     &$func(\@content);
                   7815:     return;
1.852     albertel 7816: }
1.327     albertel 7817: # ------------------------------------------------------------ Read domain file
                   7818: {
1.852     albertel 7819:     my $loaded;
1.846     albertel 7820:     my %domain;
                   7821: 
1.852     albertel 7822:     sub parse_domain_tab {
                   7823: 	my ($lines) = @_;
                   7824: 	foreach my $line (@$lines) {
                   7825: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7826: 
1.846     albertel 7827: 	    chomp($line);
1.852     albertel 7828: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7829: 	    my %this_domain;
                   7830: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7831: 			       'lang_def', 'city', 'longi', 'lati',
                   7832: 			       'primary') {
                   7833: 		$this_domain{$field} = shift(@elements);
                   7834: 	    }
                   7835: 	    $domain{$name} = \%this_domain;
1.852     albertel 7836: 	}
                   7837:     }
1.864     albertel 7838: 
                   7839:     sub reset_domain_info {
                   7840: 	undef($loaded);
                   7841: 	undef(%domain);
                   7842:     }
                   7843: 
1.852     albertel 7844:     sub load_domain_tab {
1.869     albertel 7845: 	my ($ignore_cache) = @_;
                   7846: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7847: 	my $fh;
                   7848: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7849: 	    my @lines = <$fh>;
                   7850: 	    &parse_domain_tab(\@lines);
1.448     albertel 7851: 	}
1.852     albertel 7852: 	close($fh);
                   7853: 	$loaded = 1;
1.327     albertel 7854:     }
1.846     albertel 7855: 
                   7856:     sub domain {
1.852     albertel 7857: 	&load_domain_tab() if (!$loaded);
                   7858: 
1.846     albertel 7859: 	my ($name,$what) = @_;
                   7860: 	return if ( !exists($domain{$name}) );
                   7861: 
                   7862: 	if (!$what) {
                   7863: 	    return $domain{$name}{'description'};
                   7864: 	}
                   7865: 	return $domain{$name}{$what};
                   7866:     }
1.327     albertel 7867: }
                   7868: 
                   7869: 
1.1       albertel 7870: # ------------------------------------------------------------- Read hosts file
                   7871: {
1.838     albertel 7872:     my %hostname;
1.844     albertel 7873:     my %hostdom;
1.845     albertel 7874:     my %libserv;
1.852     albertel 7875:     my $loaded;
1.888     albertel 7876:     my %name_to_host;
1.852     albertel 7877: 
                   7878:     sub parse_hosts_tab {
                   7879: 	my ($file) = @_;
                   7880: 	foreach my $configline (@$file) {
                   7881: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7882: 	    next if ($configline =~ /^\^/);
                   7883: 	    chomp($configline);
                   7884: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7885: 	    $name=~s/\s//g;
                   7886: 	    if ($id && $domain && $role && $name) {
                   7887: 		$hostname{$id}=$name;
1.888     albertel 7888: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 7889: 		$hostdom{$id}=$domain;
                   7890: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   7891: 	    }
                   7892: 	}
                   7893:     }
1.864     albertel 7894:     
                   7895:     sub reset_hosts_info {
1.897     albertel 7896: 	&purge_remembered();
1.864     albertel 7897: 	&reset_domain_info();
                   7898: 	&reset_hosts_ip_info();
1.892     albertel 7899: 	undef(%name_to_host);
1.864     albertel 7900: 	undef(%hostname);
                   7901: 	undef(%hostdom);
                   7902: 	undef(%libserv);
                   7903: 	undef($loaded);
                   7904:     }
1.1       albertel 7905: 
1.852     albertel 7906:     sub load_hosts_tab {
1.869     albertel 7907: 	my ($ignore_cache) = @_;
                   7908: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 7909: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7910: 	my @config = <$config>;
                   7911: 	&parse_hosts_tab(\@config);
                   7912: 	close($config);
                   7913: 	$loaded=1;
1.1       albertel 7914:     }
1.852     albertel 7915: 
1.838     albertel 7916:     sub hostname {
1.852     albertel 7917: 	&load_hosts_tab() if (!$loaded);
                   7918: 
1.838     albertel 7919: 	my ($lonid) = @_;
                   7920: 	return $hostname{$lonid};
                   7921:     }
1.845     albertel 7922: 
1.838     albertel 7923:     sub all_hostnames {
1.852     albertel 7924: 	&load_hosts_tab() if (!$loaded);
                   7925: 
1.838     albertel 7926: 	return %hostname;
                   7927:     }
1.845     albertel 7928: 
1.888     albertel 7929:     sub all_names {
                   7930: 	&load_hosts_tab() if (!$loaded);
                   7931: 
                   7932: 	return %name_to_host;
                   7933:     }
                   7934: 
1.845     albertel 7935:     sub is_library {
1.852     albertel 7936: 	&load_hosts_tab() if (!$loaded);
                   7937: 
1.845     albertel 7938: 	return exists($libserv{$_[0]});
                   7939:     }
                   7940: 
                   7941:     sub all_library {
1.852     albertel 7942: 	&load_hosts_tab() if (!$loaded);
                   7943: 
1.845     albertel 7944: 	return %libserv;
                   7945:     }
                   7946: 
1.841     albertel 7947:     sub get_servers {
1.852     albertel 7948: 	&load_hosts_tab() if (!$loaded);
                   7949: 
1.841     albertel 7950: 	my ($domain,$type) = @_;
                   7951: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7952: 	                                          : %hostname;
                   7953: 	my %result;
1.842     albertel 7954: 	if (ref($domain) eq 'ARRAY') {
                   7955: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7956: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7957: 		    $result{$host} = $hostname;
                   7958: 		}
                   7959: 	    }
                   7960: 	} else {
                   7961: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7962: 		if ($hostdom{$host} eq $domain) {
                   7963: 		    $result{$host} = $hostname;
                   7964: 		}
1.841     albertel 7965: 	    }
                   7966: 	}
                   7967: 	return %result;
                   7968:     }
1.845     albertel 7969: 
1.844     albertel 7970:     sub host_domain {
1.852     albertel 7971: 	&load_hosts_tab() if (!$loaded);
                   7972: 
1.844     albertel 7973: 	my ($lonid) = @_;
                   7974: 	return $hostdom{$lonid};
                   7975:     }
                   7976: 
1.841     albertel 7977:     sub all_domains {
1.852     albertel 7978: 	&load_hosts_tab() if (!$loaded);
                   7979: 
1.841     albertel 7980: 	my %seen;
                   7981: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7982: 	return @uniq;
                   7983:     }
1.1       albertel 7984: }
                   7985: 
1.847     albertel 7986: { 
                   7987:     my %iphost;
1.856     albertel 7988:     my %name_to_ip;
                   7989:     my %lonid_to_ip;
1.869     albertel 7990: 
1.847     albertel 7991:     sub get_hosts_from_ip {
                   7992: 	my ($ip) = @_;
                   7993: 	my %iphosts = &get_iphost();
                   7994: 	if (ref($iphosts{$ip})) {
                   7995: 	    return @{$iphosts{$ip}};
                   7996: 	}
                   7997: 	return;
1.839     albertel 7998:     }
1.864     albertel 7999:     
                   8000:     sub reset_hosts_ip_info {
                   8001: 	undef(%iphost);
                   8002: 	undef(%name_to_ip);
                   8003: 	undef(%lonid_to_ip);
                   8004:     }
1.856     albertel 8005: 
                   8006:     sub get_host_ip {
                   8007: 	my ($lonid) = @_;
                   8008: 	if (exists($lonid_to_ip{$lonid})) {
                   8009: 	    return $lonid_to_ip{$lonid};
                   8010: 	}
                   8011: 	my $name=&hostname($lonid);
                   8012:    	my $ip = gethostbyname($name);
                   8013: 	return if (!$ip || length($ip) ne 4);
                   8014: 	$ip=inet_ntoa($ip);
                   8015: 	$name_to_ip{$name}   = $ip;
                   8016: 	$lonid_to_ip{$lonid} = $ip;
                   8017: 	return $ip;
                   8018:     }
1.847     albertel 8019:     
                   8020:     sub get_iphost {
1.869     albertel 8021: 	my ($ignore_cache) = @_;
1.894     albertel 8022: 
1.869     albertel 8023: 	if (!$ignore_cache) {
                   8024: 	    if (%iphost) {
                   8025: 		return %iphost;
                   8026: 	    }
                   8027: 	    my ($ip_info,$cached)=
                   8028: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8029: 	    if ($cached) {
                   8030: 		%iphost      = %{$ip_info->[0]};
                   8031: 		%name_to_ip  = %{$ip_info->[1]};
                   8032: 		%lonid_to_ip = %{$ip_info->[2]};
                   8033: 		return %iphost;
                   8034: 	    }
                   8035: 	}
1.894     albertel 8036: 
                   8037: 	# get yesterday's info for fallback
                   8038: 	my %old_name_to_ip;
                   8039: 	my ($ip_info,$cached)=
                   8040: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8041: 	if ($cached) {
                   8042: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8043: 	}
                   8044: 
1.888     albertel 8045: 	my %name_to_host = &all_names();
                   8046: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8047: 	    my $ip;
                   8048: 	    if (!exists($name_to_ip{$name})) {
                   8049: 		$ip = gethostbyname($name);
                   8050: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8051: 		    if (defined($old_name_to_ip{$name})) {
                   8052: 			$ip = $old_name_to_ip{$name};
                   8053: 			&logthis("Can't find $name defaulting to old $ip");
                   8054: 		    } else {
                   8055: 			&logthis("Name $name no IP found");
                   8056: 			next;
                   8057: 		    }
                   8058: 		} else {
                   8059: 		    $ip=inet_ntoa($ip);
1.847     albertel 8060: 		}
                   8061: 		$name_to_ip{$name} = $ip;
                   8062: 	    } else {
                   8063: 		$ip = $name_to_ip{$name};
1.653     albertel 8064: 	    }
1.888     albertel 8065: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8066: 		$lonid_to_ip{$id} = $ip;
                   8067: 	    }
                   8068: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8069: 	}
1.869     albertel 8070: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8071: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8072: 				      48*60*60);
1.869     albertel 8073: 
1.847     albertel 8074: 	return %iphost;
1.598     albertel 8075:     }
                   8076: }
                   8077: 
1.862     albertel 8078: BEGIN {
                   8079: 
                   8080: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8081:     unless ($readit) {
                   8082: {
                   8083:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8084:     %perlvar = (%perlvar,%{$configvars});
                   8085: }
                   8086: 
                   8087: 
1.1       albertel 8088: # ------------------------------------------------------ Read spare server file
                   8089: {
1.448     albertel 8090:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8091: 
                   8092:     while (my $configline=<$config>) {
                   8093:        chomp($configline);
1.284     matthew  8094:        if ($configline) {
1.784     albertel 8095: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8096: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8097: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8098:        }
                   8099:     }
1.448     albertel 8100:     close($config);
1.1       albertel 8101: }
1.11      www      8102: # ------------------------------------------------------------ Read permissions
                   8103: {
1.448     albertel 8104:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8105: 
                   8106:     while (my $configline=<$config>) {
1.448     albertel 8107: 	chomp($configline);
                   8108: 	if ($configline) {
                   8109: 	    my ($role,$perm)=split(/ /,$configline);
                   8110: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8111: 	}
1.11      www      8112:     }
1.448     albertel 8113:     close($config);
1.11      www      8114: }
                   8115: 
                   8116: # -------------------------------------------- Read plain texts for permissions
                   8117: {
1.448     albertel 8118:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8119: 
                   8120:     while (my $configline=<$config>) {
1.448     albertel 8121: 	chomp($configline);
                   8122: 	if ($configline) {
1.742     raeburn  8123: 	    my ($short,@plain)=split(/:/,$configline);
                   8124:             %{$prp{$short}} = ();
                   8125: 	    if (@plain > 0) {
                   8126:                 $prp{$short}{'std'} = $plain[0];
                   8127:                 for (my $i=1; $i<@plain; $i++) {
                   8128:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8129:                 }
                   8130:             }
1.448     albertel 8131: 	}
1.135     www      8132:     }
1.448     albertel 8133:     close($config);
1.135     www      8134: }
                   8135: 
                   8136: # ---------------------------------------------------------- Read package table
                   8137: {
1.448     albertel 8138:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8139: 
                   8140:     while (my $configline=<$config>) {
1.483     albertel 8141: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8142: 	chomp($configline);
                   8143: 	my ($short,$plain)=split(/:/,$configline);
                   8144: 	my ($pack,$name)=split(/\&/,$short);
                   8145: 	if ($plain ne '') {
                   8146: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8147: 	    $packagetab{$short}=$plain; 
                   8148: 	}
1.11      www      8149:     }
1.448     albertel 8150:     close($config);
1.329     matthew  8151: }
                   8152: 
                   8153: # ------------- set up temporary directory
                   8154: {
                   8155:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8156: 
1.11      www      8157: }
                   8158: 
1.794     albertel 8159: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8160: 				'compress_threshold'=> 20_000,
                   8161:  			        });
1.185     www      8162: 
1.281     www      8163: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8164: $dumpcount=0;
1.22      www      8165: 
1.163     harris41 8166: &logtouch();
1.672     albertel 8167: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8168: $readit=1;
1.564     albertel 8169:     {
                   8170: 	use integer;
                   8171: 	my $test=(2**32)+1;
1.568     albertel 8172: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8173: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8174:     }
1.195     www      8175: }
1.1       albertel 8176: }
1.179     www      8177: 
1.1       albertel 8178: 1;
1.191     harris41 8179: __END__
                   8180: 
1.243     albertel 8181: =pod
                   8182: 
1.191     harris41 8183: =head1 NAME
                   8184: 
1.243     albertel 8185: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8186: 
                   8187: =head1 SYNOPSIS
                   8188: 
1.243     albertel 8189: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8190: 
                   8191:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8192: 
1.243     albertel 8193: Common parameters:
                   8194: 
                   8195: =over 4
                   8196: 
                   8197: =item *
                   8198: 
                   8199: $uname : an internal username (if $cname expecting a course Id specifically)
                   8200: 
                   8201: =item *
                   8202: 
                   8203: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8204: 
                   8205: =item *
                   8206: 
                   8207: $symb : a resource instance identifier
                   8208: 
                   8209: =item *
                   8210: 
                   8211: $namespace : the name of a .db file that contains the data needed or
                   8212: being set.
                   8213: 
                   8214: =back
                   8215: 
1.394     bowersj2 8216: =head1 OVERVIEW
1.191     harris41 8217: 
1.394     bowersj2 8218: lonnet provides subroutines which interact with the
                   8219: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8220: about classes, users, and resources.
1.243     albertel 8221: 
                   8222: For many of these objects you can also use this to store data about
                   8223: them or modify them in various ways.
1.191     harris41 8224: 
1.394     bowersj2 8225: =head2 Symbs
1.191     harris41 8226: 
1.394     bowersj2 8227: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8228: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8229: map, the resource number of the resource in the map, and the URL of
                   8230: the resource itself. The latter is somewhat redundant, but might help
                   8231: if maps change.
                   8232: 
                   8233: An example is
                   8234: 
                   8235:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8236: 
                   8237: The respective map entry is
                   8238: 
                   8239:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8240:   title="Problem 2">
                   8241:  </resource>
                   8242: 
                   8243: Symbs are used by the random number generator, as well as to store and
                   8244: restore data specific to a certain instance of for example a problem.
                   8245: 
                   8246: =head2 Storing And Retrieving Data
                   8247: 
                   8248: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8249: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8250: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8251: is is the non-critical message twin of cstore. These functions are for
                   8252: handlers to store a perl hash to a user's permanent data space in an
                   8253: easy manner, and to retrieve it again on another call. It is expected
                   8254: that a handler would use this once at the beginning to retrieve data,
                   8255: and then again once at the end to send only the new data back.
                   8256: 
                   8257: The data is stored in the user's data directory on the user's
                   8258: homeserver under the ID of the course.
                   8259: 
                   8260: The hash that is returned by restore will have all of the previous
                   8261: value for all of the elements of the hash.
                   8262: 
                   8263: Example:
                   8264: 
                   8265:  #creating a hash
                   8266:  my %hash;
                   8267:  $hash{'foo'}='bar';
                   8268: 
                   8269:  #storing it
                   8270:  &Apache::lonnet::cstore(\%hash);
                   8271: 
                   8272:  #changing a value
                   8273:  $hash{'foo'}='notbar';
                   8274: 
                   8275:  #adding a new value
                   8276:  $hash{'bar'}='foo';
                   8277:  &Apache::lonnet::cstore(\%hash);
                   8278: 
                   8279:  #retrieving the hash
                   8280:  my %history=&Apache::lonnet::restore();
                   8281: 
                   8282:  #print the hash
                   8283:  foreach my $key (sort(keys(%history))) {
                   8284:    print("\%history{$key} = $history{$key}");
                   8285:  }
                   8286: 
                   8287: Will print out:
1.191     harris41 8288: 
1.394     bowersj2 8289:  %history{1:foo} = bar
                   8290:  %history{1:keys} = foo:timestamp
                   8291:  %history{1:timestamp} = 990455579
                   8292:  %history{2:bar} = foo
                   8293:  %history{2:foo} = notbar
                   8294:  %history{2:keys} = foo:bar:timestamp
                   8295:  %history{2:timestamp} = 990455580
                   8296:  %history{bar} = foo
                   8297:  %history{foo} = notbar
                   8298:  %history{timestamp} = 990455580
                   8299:  %history{version} = 2
                   8300: 
                   8301: Note that the special hash entries C<keys>, C<version> and
                   8302: C<timestamp> were added to the hash. C<version> will be equal to the
                   8303: total number of versions of the data that have been stored. The
                   8304: C<timestamp> attribute will be the UNIX time the hash was
                   8305: stored. C<keys> is available in every historical section to list which
                   8306: keys were added or changed at a specific historical revision of a
                   8307: hash.
                   8308: 
                   8309: B<Warning>: do not store the hash that restore returns directly. This
                   8310: will cause a mess since it will restore the historical keys as if the
                   8311: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8312: 
1.394     bowersj2 8313: Calling convention:
1.191     harris41 8314: 
1.394     bowersj2 8315:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8316:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8317: 
1.394     bowersj2 8318: For more detailed information, see lonnet specific documentation.
1.191     harris41 8319: 
1.394     bowersj2 8320: =head1 RETURN MESSAGES
1.191     harris41 8321: 
1.394     bowersj2 8322: =over 4
1.191     harris41 8323: 
1.394     bowersj2 8324: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8325: 
1.394     bowersj2 8326: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8327: when the connection is brought back up
1.191     harris41 8328: 
1.394     bowersj2 8329: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8330: for later delivery
1.191     harris41 8331: 
1.394     bowersj2 8332: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8333: 
1.394     bowersj2 8334: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8335: that was requested
1.191     harris41 8336: 
1.243     albertel 8337: =back
1.191     harris41 8338: 
1.243     albertel 8339: =head1 PUBLIC SUBROUTINES
1.191     harris41 8340: 
1.243     albertel 8341: =head2 Session Environment Functions
1.191     harris41 8342: 
1.243     albertel 8343: =over 4
1.191     harris41 8344: 
1.394     bowersj2 8345: =item * 
                   8346: X<appenv()>
                   8347: B<appenv(%hash)>: the value of %hash is written to
                   8348: the user envirnoment file, and will be restored for each access this
1.620     albertel 8349: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8350: process
1.191     harris41 8351: 
                   8352: =item *
1.394     bowersj2 8353: X<delenv()>
                   8354: B<delenv($regexp)>: removes all items from the session
                   8355: environment file that matches the regular expression in $regexp. The
1.620     albertel 8356: values are also delted from the current processes %env.
1.191     harris41 8357: 
1.795     albertel 8358: =item * get_env_multiple($name) 
                   8359: 
                   8360: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8361: values may be defined and end up as an array ref.
                   8362: 
                   8363: returns an array of values
                   8364: 
1.243     albertel 8365: =back
                   8366: 
                   8367: =head2 User Information
1.191     harris41 8368: 
1.243     albertel 8369: =over 4
1.191     harris41 8370: 
                   8371: =item *
1.394     bowersj2 8372: X<queryauthenticate()>
                   8373: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8374: authentication scheme
                   8375: 
                   8376: =item *
1.394     bowersj2 8377: X<authenticate()>
                   8378: B<authenticate($uname,$upass,$udom)>: try to
                   8379: authenticate user from domain's lib servers (first use the current
                   8380: one). C<$upass> should be the users password.
1.191     harris41 8381: 
                   8382: =item *
1.394     bowersj2 8383: X<homeserver()>
                   8384: B<homeserver($uname,$udom)>: find the server which has
                   8385: the user's directory and files (there must be only one), this caches
                   8386: the answer, and also caches if there is a borken connection.
1.191     harris41 8387: 
                   8388: =item *
1.394     bowersj2 8389: X<idget()>
                   8390: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8391: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8392: username, and only 1 username per ID in a specific domain) (returns
                   8393: hash: id=>name,id=>name)
1.191     harris41 8394: 
                   8395: =item *
1.394     bowersj2 8396: X<idrget()>
                   8397: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8398: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8399: 
                   8400: =item *
1.394     bowersj2 8401: X<idput()>
                   8402: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8403: 
                   8404: =item *
1.394     bowersj2 8405: X<rolesinit()>
                   8406: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8407: 
                   8408: =item *
1.551     albertel 8409: X<getsection()>
                   8410: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8411: course $cname, return section name/number or '' for "not in course"
                   8412: and '-1' for "no section"
                   8413: 
                   8414: =item *
1.394     bowersj2 8415: X<userenvironment()>
                   8416: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8417: passed in @what from the requested user's environment, returns a hash
                   8418: 
1.858     raeburn  8419: =item * 
                   8420: X<userlog_query()>
1.859     albertel 8421: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8422: activity.log file. %filters defines filters applied when parsing the
                   8423: log file. These can be start or end timestamps, or the type of action
                   8424: - log to look for Login or Logout events, check for Checkin or
                   8425: Checkout, role for role selection. The response is in the form
                   8426: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8427: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8428: 
1.243     albertel 8429: =back
                   8430: 
                   8431: =head2 User Roles
                   8432: 
                   8433: =over 4
                   8434: 
                   8435: =item *
                   8436: 
1.810     raeburn  8437: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8438:  F: full access
                   8439:  U,I,K: authentication modes (cxx only)
                   8440:  '': forbidden
                   8441:  1: user needs to choose course
                   8442:  2: browse allowed
1.766     albertel 8443:  A: passphrase authentication needed
1.243     albertel 8444: 
                   8445: =item *
                   8446: 
                   8447: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8448: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8449: and course level
                   8450: 
                   8451: =item *
                   8452: 
                   8453: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8454: explanation of a user role term
                   8455: 
1.832     raeburn  8456: =item *
                   8457: 
1.858     raeburn  8458: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8459: All arguments are optional. Returns a hash of a roles, either for
                   8460: co-author/assistant author roles for a user's Construction Space
                   8461: (default), or if $context is 'user', roles for the user himself,
                   8462: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8463: and value is set to colon-separated start and end times for the role.
                   8464: If no username and domain are specified, will default to current
                   8465: user/domain. Types, roles, and roledoms are references to arrays,
                   8466: of role statuses (active, future or previous), roles 
                   8467: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8468: to restrict the list of roles reported. If no array ref is 
                   8469: provided for types, will default to return only active roles.
1.834     albertel 8470: 
1.243     albertel 8471: =back
                   8472: 
                   8473: =head2 User Modification
                   8474: 
                   8475: =over 4
                   8476: 
                   8477: =item *
                   8478: 
                   8479: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8480: user for the level given by URL.  Optional start and end dates (leave empty
                   8481: string or zero for "no date")
1.191     harris41 8482: 
                   8483: =item *
                   8484: 
1.243     albertel 8485: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8486: change a users, password, possible return values are: ok,
                   8487: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8488: refused
1.191     harris41 8489: 
                   8490: =item *
                   8491: 
1.243     albertel 8492: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8493: 
                   8494: =item *
                   8495: 
1.243     albertel 8496: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8497: modify user
1.191     harris41 8498: 
                   8499: =item *
                   8500: 
1.286     matthew  8501: modifystudent
                   8502: 
                   8503: modify a students enrollment and identification information.
                   8504: The course id is resolved based on the current users environment.  
                   8505: This means the envoking user must be a course coordinator or otherwise
                   8506: associated with a course.
                   8507: 
1.297     matthew  8508: This call is essentially a wrapper for lonnet::modifyuser and
                   8509: lonnet::modify_student_enrollment
1.286     matthew  8510: 
                   8511: Inputs: 
                   8512: 
                   8513: =over 4
                   8514: 
                   8515: =item B<$udom> Students loncapa domain
                   8516: 
                   8517: =item B<$uname> Students loncapa login name
                   8518: 
                   8519: =item B<$uid> Students id/student number
                   8520: 
                   8521: =item B<$umode> Students authentication mode
                   8522: 
                   8523: =item B<$upass> Students password
                   8524: 
                   8525: =item B<$first> Students first name
                   8526: 
                   8527: =item B<$middle> Students middle name
                   8528: 
                   8529: =item B<$last> Students last name
                   8530: 
                   8531: =item B<$gene> Students generation
                   8532: 
                   8533: =item B<$usec> Students section in course
                   8534: 
                   8535: =item B<$end> Unix time of the roles expiration
                   8536: 
                   8537: =item B<$start> Unix time of the roles start date
                   8538: 
                   8539: =item B<$forceid> If defined, allow $uid to be changed
                   8540: 
                   8541: =item B<$desiredhome> server to use as home server for student
                   8542: 
                   8543: =back
1.297     matthew  8544: 
                   8545: =item *
                   8546: 
                   8547: modify_student_enrollment
                   8548: 
                   8549: Change a students enrollment status in a class.  The environment variable
                   8550: 'role.request.course' must be defined for this function to proceed.
                   8551: 
                   8552: Inputs:
                   8553: 
                   8554: =over 4
                   8555: 
                   8556: =item $udom, students domain
                   8557: 
                   8558: =item $uname, students name
                   8559: 
                   8560: =item $uid, students user id
                   8561: 
                   8562: =item $first, students first name
                   8563: 
                   8564: =item $middle
                   8565: 
                   8566: =item $last
                   8567: 
                   8568: =item $gene
                   8569: 
                   8570: =item $usec
                   8571: 
                   8572: =item $end
                   8573: 
                   8574: =item $start
                   8575: 
                   8576: =back
                   8577: 
1.191     harris41 8578: 
                   8579: =item *
                   8580: 
1.243     albertel 8581: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8582: custom role; give a custom role to a user for the level given by URL.  Specify
                   8583: name and domain of role author, and role name
1.191     harris41 8584: 
                   8585: =item *
                   8586: 
1.243     albertel 8587: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8588: 
                   8589: =item *
                   8590: 
1.243     albertel 8591: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8592: 
                   8593: =back
                   8594: 
                   8595: =head2 Course Infomation
                   8596: 
                   8597: =over 4
1.191     harris41 8598: 
                   8599: =item *
                   8600: 
1.631     albertel 8601: coursedescription($courseid) : returns a hash of information about the
                   8602: specified course id, including all environment settings for the
                   8603: course, the description of the course will be in the hash under the
                   8604: key 'description'
1.191     harris41 8605: 
                   8606: =item *
                   8607: 
1.624     albertel 8608: resdata($name,$domain,$type,@which) : request for current parameter
                   8609: setting for a specific $type, where $type is either 'course' or 'user',
                   8610: @what should be a list of parameters to ask about. This routine caches
                   8611: answers for 5 minutes.
1.243     albertel 8612: 
1.877     foxr     8613: =item *
                   8614: 
                   8615: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8616: data base, returning a hash that is keyed by the resource name and has
                   8617: values that are the resource value.  I believe that the timestamps and
                   8618: versions are also returned.
                   8619: 
                   8620: 
1.243     albertel 8621: =back
                   8622: 
                   8623: =head2 Course Modification
                   8624: 
                   8625: =over 4
1.191     harris41 8626: 
                   8627: =item *
                   8628: 
1.243     albertel 8629: writecoursepref($courseid,%prefs) : write preferences (environment
                   8630: database) for a course
1.191     harris41 8631: 
                   8632: =item *
                   8633: 
1.243     albertel 8634: createcourse($udom,$description,$url) : make/modify course
                   8635: 
                   8636: =back
                   8637: 
                   8638: =head2 Resource Subroutines
                   8639: 
                   8640: =over 4
1.191     harris41 8641: 
                   8642: =item *
                   8643: 
1.243     albertel 8644: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8645: 
                   8646: =item *
                   8647: 
1.243     albertel 8648: repcopy($filename) : subscribes to the requested file, and attempts to
                   8649: replicate from the owning library server, Might return
1.607     raeburn  8650: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8651: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8652: resource. Expects the local filesystem pathname
                   8653: (/home/httpd/html/res/....)
                   8654: 
                   8655: =back
                   8656: 
                   8657: =head2 Resource Information
                   8658: 
                   8659: =over 4
1.191     harris41 8660: 
                   8661: =item *
                   8662: 
1.243     albertel 8663: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8664: a vairety of different possible values, $varname should be a request
                   8665: string, and the other parameters can be used to specify who and what
                   8666: one is asking about.
                   8667: 
                   8668: Possible values for $varname are environment.lastname (or other item
                   8669: from the envirnment hash), user.name (or someother aspect about the
                   8670: user), resource.0.maxtries (or some other part and parameter of a
                   8671: resource)
1.204     albertel 8672: 
                   8673: =item *
                   8674: 
1.243     albertel 8675: directcondval($number) : get current value of a condition; reads from a state
                   8676: string
1.204     albertel 8677: 
                   8678: =item *
                   8679: 
1.243     albertel 8680: condval($condidx) : value of condition index based on state
1.204     albertel 8681: 
                   8682: =item *
                   8683: 
1.243     albertel 8684: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8685: resource's metadata, $what should be either a specific key, or either
                   8686: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8687: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8688: 
                   8689: this function automatically caches all requests
1.191     harris41 8690: 
                   8691: =item *
                   8692: 
1.243     albertel 8693: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8694: network of library servers; returns file handle of where SQL and regex results
                   8695: will be stored for query
1.191     harris41 8696: 
                   8697: =item *
                   8698: 
1.243     albertel 8699: symbread($filename) : return symbolic list entry (filename argument optional);
                   8700: returns the data handle
1.191     harris41 8701: 
                   8702: =item *
                   8703: 
1.243     albertel 8704: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8705: a possible symb for the URL in $thisfn, and if is an encryypted
                   8706: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8707: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8708: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8709: 
1.191     harris41 8710: 
                   8711: =item *
                   8712: 
1.243     albertel 8713: symbclean($symb) : removes versions numbers from a symb, returns the
                   8714: cleaned symb
1.191     harris41 8715: 
                   8716: =item *
                   8717: 
1.243     albertel 8718: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8719: course map, user must be in a course for it to work.
1.191     harris41 8720: 
                   8721: =item *
                   8722: 
1.243     albertel 8723: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8724: 
                   8725: =item *
                   8726: 
1.243     albertel 8727: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8728: a random seed, all arguments are optional, if they aren't sent it uses the
                   8729: environment to derive them. Note: if symb isn't sent and it can't get one
                   8730: from &symbread it will use the current time as its return value
1.191     harris41 8731: 
                   8732: =item *
                   8733: 
1.243     albertel 8734: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8735: unfakeable, receipt
1.191     harris41 8736: 
                   8737: =item *
                   8738: 
1.620     albertel 8739: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8740: 
                   8741: =item *
                   8742: 
1.243     albertel 8743: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8744: 
                   8745: =item *
                   8746: 
1.243     albertel 8747: 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 8748: 
                   8749: =item *
                   8750: 
1.243     albertel 8751: 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 8752: 
                   8753: =item *
                   8754: 
1.243     albertel 8755: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8756: 
                   8757: =item *
                   8758: 
1.243     albertel 8759: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8760: forcing spreadsheet to reevaluate the resource scores next time.
                   8761: 
                   8762: =back
                   8763: 
                   8764: =head2 Storing/Retreiving Data
                   8765: 
                   8766: =over 4
1.191     harris41 8767: 
                   8768: =item *
                   8769: 
1.243     albertel 8770: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8771: for this url; hashref needs to be given and should be a \%hashname; the
                   8772: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8773: be derived from the env
1.191     harris41 8774: 
                   8775: =item *
                   8776: 
1.243     albertel 8777: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8778: uses critical subroutine
1.191     harris41 8779: 
                   8780: =item *
                   8781: 
1.243     albertel 8782: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8783: all args are optional
1.191     harris41 8784: 
                   8785: =item *
                   8786: 
1.717     albertel 8787: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8788: dumps the complete (or key matching regexp) namespace into a hash
                   8789: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8790: normally &store()ed into
                   8791: 
                   8792: $range should be either an integer '100' (give me the first 100
                   8793:                                            matching records)
                   8794:               or be  two integers sperated by a - with no spaces
                   8795:                  '30-50' (give me the 30th through the 50th matching
                   8796:                           records)
                   8797: 
                   8798: 
                   8799: =item *
                   8800: 
                   8801: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8802: replaces a &store() version of data with a replacement set of data
                   8803: for a particular resource in a namespace passed in the $storehash hash 
                   8804: reference
                   8805: 
                   8806: =item *
                   8807: 
1.243     albertel 8808: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8809: works very similar to store/cstore, but all data is stored in a
                   8810: temporary location and can be reset using tmpreset, $storehash should
                   8811: be a hash reference, returns nothing on success
1.191     harris41 8812: 
                   8813: =item *
                   8814: 
1.243     albertel 8815: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8816: similar to restore, but all data is stored in a temporary location and
                   8817: can be reset using tmpreset. Returns a hash of values on success,
                   8818: error string otherwise.
1.191     harris41 8819: 
                   8820: =item *
                   8821: 
1.243     albertel 8822: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8823: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8824: 
                   8825: =item *
                   8826: 
1.243     albertel 8827: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8828: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8829: 
                   8830: =item *
                   8831: 
1.243     albertel 8832: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8833: namesp ($udom and $uname are optional)
1.191     harris41 8834: 
                   8835: =item *
                   8836: 
1.702     albertel 8837: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8838: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8839: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8840: 
1.702     albertel 8841: $range should be either an integer '100' (give me the first 100
                   8842:                                            matching records)
                   8843:               or be  two integers sperated by a - with no spaces
                   8844:                  '30-50' (give me the 30th through the 50th matching
                   8845:                           records)
1.449     matthew  8846: =item *
                   8847: 
                   8848: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8849: $store can be a scalar, an array reference, or if the amount to be 
                   8850: incremented is > 1, a hash reference.
                   8851: 
                   8852: ($udom and $uname are optional)
1.191     harris41 8853: 
                   8854: =item *
                   8855: 
1.243     albertel 8856: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8857: ($udom and $uname are optional)
1.191     harris41 8858: 
                   8859: =item *
                   8860: 
1.243     albertel 8861: cput($namespace,$storehash,$udom,$uname) : critical put
                   8862: ($udom and $uname are optional)
1.191     harris41 8863: 
                   8864: =item *
                   8865: 
1.748     albertel 8866: newput($namespace,$storehash,$udom,$uname) :
                   8867: 
                   8868: Attempts to store the items in the $storehash, but only if they don't
                   8869: currently exist, if this succeeds you can be certain that you have 
                   8870: successfully created a new key value pair in the $namespace db.
                   8871: 
                   8872: 
                   8873: Args:
                   8874:  $namespace: name of database to store values to
                   8875:  $storehash: hashref to store to the db
                   8876:  $udom: (optional) domain of user containing the db
                   8877:  $uname: (optional) name of user caontaining the db
                   8878: 
                   8879: Returns:
                   8880:  'ok' -> succeeded in storing all keys of $storehash
                   8881:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8882:                         least <key> already existed in the db (other
                   8883:                         requested keys may also already exist)
                   8884:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8885:  'con_lost' -> unable to contact request server
                   8886:  'refused' -> action was not allowed by remote machine
                   8887: 
                   8888: 
                   8889: =item *
                   8890: 
1.243     albertel 8891: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8892: reference filled in from namesp (encrypts the return communication)
                   8893: ($udom and $uname are optional)
1.191     harris41 8894: 
                   8895: =item *
                   8896: 
1.243     albertel 8897: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8898: critical subroutine
                   8899: 
1.806     raeburn  8900: =item *
                   8901: 
1.860     raeburn  8902: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   8903: array reference filled in from namespace found in domain level on either
                   8904: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  8905: 
                   8906: =item *
                   8907: 
1.860     raeburn  8908: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   8909: domain level either on specified domain server ($uhome) or primary domain 
                   8910: server ($udom and $uhome are optional)
1.806     raeburn  8911: 
1.243     albertel 8912: =back
                   8913: 
                   8914: =head2 Network Status Functions
                   8915: 
                   8916: =over 4
1.191     harris41 8917: 
                   8918: =item *
                   8919: 
                   8920: dirlist($uri) : return directory list based on URI
                   8921: 
                   8922: =item *
                   8923: 
1.243     albertel 8924: spareserver() : find server with least workload from spare.tab
                   8925: 
                   8926: =back
                   8927: 
                   8928: =head2 Apache Request
                   8929: 
                   8930: =over 4
1.191     harris41 8931: 
                   8932: =item *
                   8933: 
1.243     albertel 8934: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8935: localhost, posts hash
                   8936: 
                   8937: =back
                   8938: 
                   8939: =head2 Data to String to Data
                   8940: 
                   8941: =over 4
1.191     harris41 8942: 
                   8943: =item *
                   8944: 
1.243     albertel 8945: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8946: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8947: 
                   8948: =item *
                   8949: 
1.243     albertel 8950: hashref2str($hashref) : convert a hashref into a string complete with
                   8951: escaping and '=' and '&' separators, supports elements that are
                   8952: arrayrefs and hashrefs
1.191     harris41 8953: 
                   8954: =item *
                   8955: 
1.243     albertel 8956: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8957: with escaping and '&' separators, supports elements that are arrayrefs
                   8958: and hashrefs
1.191     harris41 8959: 
                   8960: =item *
                   8961: 
1.243     albertel 8962: str2hash($string) : convert string to hash using unescaping and
                   8963: splitting on '=' and '&', supports elements that are arrayrefs and
                   8964: hashrefs
1.191     harris41 8965: 
                   8966: =item *
                   8967: 
1.243     albertel 8968: str2array($string) : convert string to hash using unescaping and
                   8969: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8970: 
                   8971: =back
                   8972: 
                   8973: =head2 Logging Routines
                   8974: 
                   8975: =over 4
                   8976: 
                   8977: These routines allow one to make log messages in the lonnet.log and
                   8978: lonnet.perm logfiles.
1.191     harris41 8979: 
                   8980: =item *
                   8981: 
1.243     albertel 8982: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8983: 
                   8984: =item *
                   8985: 
1.243     albertel 8986: logthis() : append message to the normal lonnet.log file, it gets
                   8987: preiodically rolled over and deleted.
1.191     harris41 8988: 
                   8989: =item *
                   8990: 
1.243     albertel 8991: logperm() : append a permanent message to lonnet.perm.log, this log
                   8992: file never gets deleted by any automated portion of the system, only
                   8993: messages of critical importance should go in here.
                   8994: 
                   8995: =back
                   8996: 
                   8997: =head2 General File Helper Routines
                   8998: 
                   8999: =over 4
1.191     harris41 9000: 
                   9001: =item *
                   9002: 
1.481     raeburn  9003: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9004: (a) files in /uploaded
                   9005:   (i) If a local copy of the file exists - 
                   9006:       compares modification date of local copy with last-modified date for 
                   9007:       definitive version stored on home server for course. If local copy is 
                   9008:       stale, requests a new version from the home server and stores it. 
                   9009:       If the original has been removed from the home server, then local copy 
                   9010:       is unlinked.
                   9011:   (ii) If local copy does not exist -
                   9012:       requests the file from the home server and stores it. 
                   9013:   
                   9014:   If $caller is 'uploadrep':  
                   9015:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9016:     for request for files originally uploaded via DOCS. 
                   9017:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9018:   
                   9019:   Otherwise:
                   9020:      This indicates a call from the content generation phase of the request.
                   9021:      -  returns the entire contents of the file or -1.
                   9022:      
                   9023: (b) files in /res
                   9024:    - returns the entire contents of a file or -1; 
                   9025:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9026: 
1.712     albertel 9027: 
                   9028: =item *
                   9029: 
                   9030: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9031:                   reference
                   9032: 
                   9033: returns either a stat() list of data about the file or an empty list
                   9034: if the file doesn't exist or couldn't find out about it (connection
                   9035: problems or user unknown)
                   9036: 
1.191     harris41 9037: =item *
                   9038: 
1.243     albertel 9039: filelocation($dir,$file) : returns file system location of a file
                   9040: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9041: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9042: and a file of ../bob will become /a/bob)
1.191     harris41 9043: 
                   9044: =item *
                   9045: 
                   9046: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9047: filelocation except for hrefs
                   9048: 
                   9049: =item *
                   9050: 
                   9051: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9052: 
1.243     albertel 9053: =back
                   9054: 
1.608     albertel 9055: =head2 Usererfile file routines (/uploaded*)
                   9056: 
                   9057: =over 4
                   9058: 
                   9059: =item *
                   9060: 
                   9061: userfileupload(): main rotine for putting a file in a user or course's
                   9062:                   filespace, arguments are,
                   9063: 
1.620     albertel 9064:  formname - required - this is the name of the element in $env where the
1.608     albertel 9065:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9066:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9067:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9068:  coursedoc - if true, store the file in the course of the active role
                   9069:              of the current user
                   9070:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9071:          if undefined, it will be placed in "unknown"
                   9072: 
                   9073:  (This routine calls clean_filename() to remove any dangerous
                   9074:  characters from the filename, and then calls finuserfileupload() to
                   9075:  complete the transaction)
                   9076: 
                   9077:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9078:  and /adm/notfound.html if unsuccessful
                   9079: 
                   9080: =item *
                   9081: 
                   9082: clean_filename(): routine for cleaing a filename up for storage in
                   9083:                  userfile space, argument is:
                   9084: 
                   9085:  filename - proposed filename
                   9086: 
                   9087: returns: the new clean filename
                   9088: 
                   9089: =item *
                   9090: 
                   9091: finishuserfileupload(): routine that creaes and sends the file to
                   9092: userspace, probably shouldn't be called directly
                   9093: 
                   9094:   docuname: username or courseid of destination for the file
                   9095:   docudom: domain of user/course of destination for the file
                   9096:   formname: same as for userfileupload()
                   9097:   fname: filename (inculding subdirectories) for the file
                   9098: 
                   9099:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9100:  and /adm/notfound.html if unsuccessful
                   9101: 
                   9102: =item *
                   9103: 
                   9104: renameuserfile(): renames an existing userfile to a new name
                   9105: 
                   9106:   Args:
                   9107:    docuname: username or courseid of destination for the file
                   9108:    docudom: domain of user/course of destination for the file
                   9109:    old: current file name (including any subdirs under userfiles)
                   9110:    new: desired file name (including any subdirs under userfiles)
                   9111: 
                   9112: =item *
                   9113: 
                   9114: mkdiruserfile(): creates a directory is a userfiles dir
                   9115: 
                   9116:   Args:
                   9117:    docuname: username or courseid of destination for the file
                   9118:    docudom: domain of user/course of destination for the file
                   9119:    dir: dir to create (including any subdirs under userfiles)
                   9120: 
                   9121: =item *
                   9122: 
                   9123: removeuserfile(): removes a file that exists in userfiles
                   9124: 
                   9125:   Args:
                   9126:    docuname: username or courseid of destination for the file
                   9127:    docudom: domain of user/course of destination for the file
                   9128:    fname: filname to delete (including any subdirs under userfiles)
                   9129: 
                   9130: =item *
                   9131: 
                   9132: removeuploadedurl(): convience function for removeuserfile()
                   9133: 
                   9134:   Args:
                   9135:    url:  a full /uploaded/... url to delete
                   9136: 
1.747     albertel 9137: =item * 
                   9138: 
                   9139: get_portfile_permissions():
                   9140:   Args:
                   9141:     domain: domain of user or course contain the portfolio files
                   9142:     user: name of user or num of course contain the portfolio files
                   9143:   Returns:
                   9144:     hashref of a dump of the proper file_permissions.db
                   9145:    
                   9146: 
                   9147: =item * 
                   9148: 
                   9149: get_access_controls():
                   9150: 
                   9151: Args:
                   9152:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9153:   group: (optional) the group you want the files associated with
                   9154:   file: (optional) the file you want access info on
                   9155: 
                   9156: Returns:
1.749     raeburn  9157:     a hash (keys are file names) of hashes containing
                   9158:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9159:         values are XML containing access control settings (see below) 
1.747     albertel 9160: 
                   9161: Internal notes:
                   9162: 
1.749     raeburn  9163:  access controls are stored in file_permissions.db as key=value pairs.
                   9164:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9165:         where scope -> public,guest,course,group,domains or users.
                   9166:               end -> UNIX time for end of access (0 -> no end date)
                   9167:               start -> UNIX time for start of access
                   9168: 
                   9169:     value -> XML description of access control
                   9170:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9171:             <start></start>
                   9172:             <end></end>
                   9173: 
                   9174:             <password></password>  for scope type = guest
                   9175: 
                   9176:             <domain></domain>     for scope type = course or group
                   9177:             <number></number>
                   9178:             <roles id="">
                   9179:              <role></role>
                   9180:              <access></access>
                   9181:              <section></section>
                   9182:              <group></group>
                   9183:             </roles>
                   9184: 
                   9185:             <dom></dom>         for scope type = domains
                   9186: 
                   9187:             <users>             for scope type = users
                   9188:              <user>
                   9189:               <uname></uname>
                   9190:               <udom></udom>
                   9191:              </user>
                   9192:             </users>
                   9193:            </scope> 
                   9194:               
                   9195:  Access data is also aggregated for each file in an additional key=value pair:
                   9196:  key -> path to file/file_name\0accesscontrol 
                   9197:  value -> reference to hash
                   9198:           hash contains key = value pairs
                   9199:           where key = uniqueID:scope_end_start
                   9200:                 value = UNIX time record was last updated
                   9201: 
                   9202:           Used to improve speed of look-ups of access controls for each file.  
                   9203:  
                   9204:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9205: 
                   9206: modify_access_controls():
                   9207: 
                   9208: Modifies access controls for a portfolio file
                   9209: Args
                   9210: 1. file name
                   9211: 2. reference to hash of required changes,
                   9212: 3. domain
                   9213: 4. username
                   9214:   where domain,username are the domain of the portfolio owner 
                   9215:   (either a user or a course) 
                   9216: 
                   9217: Returns:
                   9218: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9219: 2. result of deletions ('ok' or 'error', with error message).
                   9220: 3. reference to hash of any new or updated access controls.
                   9221: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9222:    key = integer (inbound ID)
                   9223:    value = uniqueID  
1.747     albertel 9224: 
1.608     albertel 9225: =back
                   9226: 
1.243     albertel 9227: =head2 HTTP Helper Routines
                   9228: 
                   9229: =over 4
                   9230: 
1.191     harris41 9231: =item *
                   9232: 
                   9233: escape() : unpack non-word characters into CGI-compatible hex codes
                   9234: 
                   9235: =item *
                   9236: 
                   9237: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9238: 
1.243     albertel 9239: =back
                   9240: 
                   9241: =head1 PRIVATE SUBROUTINES
                   9242: 
                   9243: =head2 Underlying communication routines (Shouldn't call)
                   9244: 
                   9245: =over 4
                   9246: 
                   9247: =item *
                   9248: 
                   9249: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9250: 
                   9251: =item *
                   9252: 
                   9253: reply() : uses subreply to send a message to remote machine, logs all failures
                   9254: 
                   9255: =item *
                   9256: 
                   9257: critical() : passes a critical message to another server; if cannot
                   9258: get through then place message in connection buffer directory and
                   9259: returns con_delayed, if incapable of saving message, returns
                   9260: con_failed
                   9261: 
                   9262: =item *
                   9263: 
                   9264: reconlonc() : tries to reconnect lonc client processes.
                   9265: 
                   9266: =back
                   9267: 
                   9268: =head2 Resource Access Logging
                   9269: 
                   9270: =over 4
                   9271: 
                   9272: =item *
                   9273: 
                   9274: flushcourselogs() : flush (save) buffer logs and access logs
                   9275: 
                   9276: =item *
                   9277: 
                   9278: courselog($what) : save message for course in hash
                   9279: 
                   9280: =item *
                   9281: 
                   9282: courseacclog($what) : save message for course using &courselog().  Perform
                   9283: special processing for specific resource types (problems, exams, quizzes, etc).
                   9284: 
1.191     harris41 9285: =item *
                   9286: 
                   9287: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9288: as a PerlChildExitHandler
1.243     albertel 9289: 
                   9290: =back
                   9291: 
                   9292: =head2 Other
                   9293: 
                   9294: =over 4
                   9295: 
                   9296: =item *
                   9297: 
                   9298: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9299: 
                   9300: =back
                   9301: 
                   9302: =cut
1.877     foxr     9303: 

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