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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.914   ! albertel    4: # $Id: lonnet.pm,v 1.913 2007/09/25 00:21:12 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: }
1.914   ! albertel  585: 
        !           586: # --------------------------- ask offload servers if user already has a session
        !           587: sub find_existing_session {
        !           588:     my ($udom,$uname) = @_;
        !           589:     foreach my $try_server (@{ $spareid{'primary'} },
        !           590: 			    @{ $spareid{'default'} }) {
        !           591: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
        !           592:     }
        !           593:     return;
        !           594: }
        !           595: 
        !           596: # -------------------------------- ask if server already has a session for user
        !           597: sub has_user_session {
        !           598:     my ($lonid,$udom,$uname) = @_;
        !           599:     my $result = &reply(join(':','userhassession',
        !           600: 			     map {&escape($_)} ($udom,$uname)),$lonid);
        !           601:     return 1 if ($result eq 'ok');
        !           602: 
        !           603:     return 0;
        !           604: }
        !           605: 
1.202     matthew   606: # --------------------------------------------- Try to change a user's password
                    607: 
                    608: sub changepass {
1.799     raeburn   609:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   610:     $currentpass = &escape($currentpass);
                    611:     $newpass     = &escape($newpass);
1.799     raeburn   612:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   613: 		       $server);
                    614:     if (! $answer) {
                    615: 	&logthis("No reply on password change request to $server ".
                    616: 		 "by $uname in domain $udom.");
                    617:     } elsif ($answer =~ "^ok") {
                    618:         &logthis("$uname in $udom successfully changed their password ".
                    619: 		 "on $server.");
                    620:     } elsif ($answer =~ "^pwchange_failure") {
                    621: 	&logthis("$uname in $udom was unable to change their password ".
                    622: 		 "on $server.  The action was blocked by either lcpasswd ".
                    623: 		 "or pwchange");
                    624:     } elsif ($answer =~ "^non_authorized") {
                    625:         &logthis("$uname in $udom did not get their password correct when ".
                    626: 		 "attempting to change it on $server.");
                    627:     } elsif ($answer =~ "^auth_mode_error") {
                    628:         &logthis("$uname in $udom attempted to change their password despite ".
                    629: 		 "not being locally or internally authenticated on $server.");
                    630:     } elsif ($answer =~ "^unknown_user") {
                    631:         &logthis("$uname in $udom attempted to change their password ".
                    632: 		 "on $server but were unable to because $server is not ".
                    633: 		 "their home server.");
                    634:     } elsif ($answer =~ "^refused") {
                    635: 	&logthis("$server refused to change $uname in $udom password because ".
                    636: 		 "it was sent an unencrypted request to change the password.");
                    637:     }
                    638:     return $answer;
1.1       albertel  639: }
                    640: 
1.169     harris41  641: # ----------------------- Try to determine user's current authentication scheme
                    642: 
                    643: sub queryauthenticate {
                    644:     my ($uname,$udom)=@_;
1.456     albertel  645:     my $uhome=&homeserver($uname,$udom);
                    646:     if (!$uhome) {
                    647: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    648: 	return 'no_host';
                    649:     }
                    650:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    651:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    652: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  653:     }
1.456     albertel  654:     return $answer;
1.169     harris41  655: }
                    656: 
1.1       albertel  657: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       658: 
1.1       albertel  659: sub authenticate {
                    660:     my ($uname,$upass,$udom)=@_;
1.807     albertel  661:     $upass=&escape($upass);
                    662:     $uname= &LONCAPA::clean_username($uname);
1.836     www       663:     my $uhome=&homeserver($uname,$udom,1);
                    664:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    665: # Maybe the machine was offline and only re-appeared again recently?
                    666:         &reconlonc();
                    667: # One more
                    668: 	my $uhome=&homeserver($uname,$udom,1);
                    669: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    670: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    671: 	}
1.471     albertel  672: 	return 'no_host';
1.1       albertel  673:     }
1.471     albertel  674:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    675:     if ($answer eq 'authorized') {
                    676: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    677: 	return $uhome; 
                    678:     }
                    679:     if ($answer eq 'non_authorized') {
                    680: 	&logthis("User $uname at $udom rejected by $uhome");
                    681: 	return 'no_host'; 
1.9       www       682:     }
1.471     albertel  683:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  684:     return 'no_host';
                    685: }
                    686: 
                    687: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       688: 
1.599     albertel  689: my %homecache;
1.1       albertel  690: sub homeserver {
1.230     stredwic  691:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  692:     my $index="$uname:$udom";
1.426     albertel  693: 
1.599     albertel  694:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  695: 
                    696:     my %servers = &get_servers($udom,'library');
                    697:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  698:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  699: 		 exists($badServerCache{$tryserver}));
1.841     albertel  700: 
                    701: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    702: 	if ($answer eq 'found') {
                    703: 	    delete($badServerCache{$tryserver}); 
                    704: 	    return $homecache{$index}=$tryserver;
                    705: 	} elsif ($answer eq 'no_host') {
                    706: 	    $badServerCache{$tryserver}=1;
                    707: 	}
1.1       albertel  708:     }    
                    709:     return 'no_host';
1.70      www       710: }
                    711: 
                    712: # ------------------------------------- Find the usernames behind a list of IDs
                    713: 
                    714: sub idget {
                    715:     my ($udom,@ids)=@_;
                    716:     my %returnhash=();
                    717:     
1.841     albertel  718:     my %servers = &get_servers($udom,'library');
                    719:     foreach my $tryserver (keys(%servers)) {
                    720: 	my $idlist=join('&',@ids);
                    721: 	$idlist=~tr/A-Z/a-z/; 
                    722: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    723: 	my @answer=();
                    724: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    725: 	    @answer=split(/\&/,$reply);
                    726: 	}                    ;
                    727: 	my $i;
                    728: 	for ($i=0;$i<=$#ids;$i++) {
                    729: 	    if ($answer[$i]) {
                    730: 		$returnhash{$ids[$i]}=$answer[$i];
                    731: 	    } 
                    732: 	}
                    733:     } 
1.70      www       734:     return %returnhash;
                    735: }
                    736: 
                    737: # ------------------------------------- Find the IDs behind a list of usernames
                    738: 
                    739: sub idrget {
                    740:     my ($udom,@unames)=@_;
                    741:     my %returnhash=();
1.800     albertel  742:     foreach my $uname (@unames) {
                    743:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  744:     }
1.70      www       745:     return %returnhash;
                    746: }
                    747: 
                    748: # ------------------------------- Store away a list of names and associated IDs
                    749: 
                    750: sub idput {
                    751:     my ($udom,%ids)=@_;
                    752:     my %servers=();
1.800     albertel  753:     foreach my $uname (keys(%ids)) {
                    754: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    755:         my $uhom=&homeserver($uname,$udom);
1.70      www       756:         if ($uhom ne 'no_host') {
1.800     albertel  757:             my $id=&escape($ids{$uname});
1.70      www       758:             $id=~tr/A-Z/a-z/;
1.800     albertel  759:             my $esc_unam=&escape($uname);
1.70      www       760: 	    if ($servers{$uhom}) {
1.800     albertel  761: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       762:             } else {
1.800     albertel  763:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       764:             }
                    765:         }
1.191     harris41  766:     }
1.800     albertel  767:     foreach my $server (keys(%servers)) {
                    768:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  769:     }
1.344     www       770: }
                    771: 
1.806     raeburn   772: # ------------------------------------------- get items from domain db files   
                    773: 
                    774: sub get_dom {
1.860     raeburn   775:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   776:     my $items='';
                    777:     foreach my $item (@$storearr) {
                    778:         $items.=&escape($item).'&';
                    779:     }
                    780:     $items=~s/\&$//;
1.860     raeburn   781:     if (!$udom) {
                    782:         $udom=$env{'user.domain'};
                    783:         if (defined(&domain($udom,'primary'))) {
                    784:             $uhome=&domain($udom,'primary');
                    785:         } else {
1.874     albertel  786:             undef($uhome);
1.860     raeburn   787:         }
                    788:     } else {
                    789:         if (!$uhome) {
                    790:             if (defined(&domain($udom,'primary'))) {
                    791:                 $uhome=&domain($udom,'primary');
                    792:             }
                    793:         }
                    794:     }
                    795:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   796:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   797:         my %returnhash;
1.875     albertel  798:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   799:             return %returnhash;
                    800:         }
1.806     raeburn   801:         my @pairs=split(/\&/,$rep);
                    802:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    803:             return @pairs;
                    804:         }
                    805:         my $i=0;
                    806:         foreach my $item (@$storearr) {
                    807:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    808:             $i++;
                    809:         }
                    810:         return %returnhash;
                    811:     } else {
1.880     banghart  812:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   813:     }
                    814: }
                    815: 
                    816: # -------------------------------------------- put items in domain db files 
                    817: 
                    818: sub put_dom {
1.860     raeburn   819:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    820:     if (!$udom) {
                    821:         $udom=$env{'user.domain'};
                    822:         if (defined(&domain($udom,'primary'))) {
                    823:             $uhome=&domain($udom,'primary');
                    824:         } else {
1.874     albertel  825:             undef($uhome);
1.860     raeburn   826:         }
                    827:     } else {
                    828:         if (!$uhome) {
                    829:             if (defined(&domain($udom,'primary'))) {
                    830:                 $uhome=&domain($udom,'primary');
                    831:             }
                    832:         }
                    833:     } 
                    834:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   835:         my $items='';
                    836:         foreach my $item (keys(%$storehash)) {
                    837:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    838:         }
                    839:         $items=~s/\&$//;
                    840:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    841:     } else {
1.860     raeburn   842:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   843:     }
                    844: }
                    845: 
1.837     raeburn   846: sub retrieve_inst_usertypes {
                    847:     my ($udom) = @_;
                    848:     my (%returnhash,@order);
1.846     albertel  849:     if (defined(&domain($udom,'primary'))) {
                    850:         my $uhome=&domain($udom,'primary');
1.837     raeburn   851:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    852:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    853:         my @pairs=split(/\&/,$hashitems);
                    854:         foreach my $item (@pairs) {
                    855:             my ($key,$value)=split(/=/,$item,2);
                    856:             $key = &unescape($key);
                    857:             next if ($key =~ /^error: 2 /);
                    858:             $returnhash{$key}=&thaw_unescape($value);
                    859:         }
                    860:         my @esc_order = split(/\&/,$orderitems);
                    861:         foreach my $item (@esc_order) {
                    862:             push(@order,&unescape($item));
                    863:         }
                    864:     } else {
                    865:         &logthis("get_dom failed - no primary domain server for $udom");
                    866:     }
                    867:     return (\%returnhash,\@order);
                    868: }
                    869: 
1.868     raeburn   870: sub is_domainimage {
                    871:     my ($url) = @_;
                    872:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    873:         if (&domain($1) ne '') {
                    874:             return '1';
                    875:         }
                    876:     }
                    877:     return;
                    878: }
                    879: 
1.899     raeburn   880: sub inst_directory_query {
                    881:     my ($srch) = @_;
                    882:     my $udom = $srch->{'srchdomain'};
                    883:     my %results;
                    884:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   885:     my $outcome;
1.899     raeburn   886:     if ($homeserver ne '') {
1.904     albertel  887: 	my $queryid=&reply("querysend:instdirsearch:".
                    888: 			   &escape($srch->{'srchby'}).':'.
                    889: 			   &escape($srch->{'srchterm'}).':'.
                    890: 			   &escape($srch->{'srchtype'}),$homeserver);
                    891: 	my $host=&hostname($homeserver);
                    892: 	if ($queryid !~/^\Q$host\E\_/) {
                    893: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    894: 	    return;
                    895: 	}
                    896: 	my $response = &get_query_reply($queryid);
                    897: 	my $maxtries = 5;
                    898: 	my $tries = 1;
                    899: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    900: 	    $response = &get_query_reply($queryid);
                    901: 	    $tries ++;
                    902: 	}
                    903: 
                    904:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn   905:             if ($response eq 'unavailable') {
                    906:                 $outcome = $response;
                    907:             } else {
                    908:                 $outcome = 'ok';
                    909:                 my @matches = split(/\n/,$response);
                    910:                 foreach my $match (@matches) {
                    911:                     my ($key,$value) = split(/=/,$match);
                    912:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                    913:                 }
1.899     raeburn   914:             }
                    915:         }
                    916:     }
1.909     raeburn   917:     return ($outcome,%results);
1.899     raeburn   918: }
                    919: 
                    920: sub usersearch {
                    921:     my ($srch) = @_;
                    922:     my $dom = $srch->{'srchdomain'};
                    923:     my %results;
                    924:     my %libserv = &all_library();
                    925:     my $query = 'usersearch';
                    926:     foreach my $tryserver (keys(%libserv)) {
                    927:         if (&host_domain($tryserver) eq $dom) {
                    928:             my $host=&hostname($tryserver);
                    929:             my $queryid=
1.911     raeburn   930:                 &reply("querysend:".&escape($query).':'.
                    931:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn   932:                        &escape($srch->{'srchtype'}).':'.
                    933:                        &escape($srch->{'srchterm'}),$tryserver);
                    934:             if ($queryid !~/^\Q$host\E\_/) {
                    935:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   936:                 next;
1.899     raeburn   937:             }
                    938:             my $reply = &get_query_reply($queryid);
                    939:             my $maxtries = 1;
                    940:             my $tries = 1;
                    941:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    942:                 $reply = &get_query_reply($queryid);
                    943:                 $tries ++;
                    944:             }
                    945:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    946:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    947:             } else {
1.911     raeburn   948:                 my @matches;
                    949:                 if ($reply =~ /\n/) {
                    950:                     @matches = split(/\n/,$reply);
                    951:                 } else {
                    952:                     @matches = split(/\&/,$reply);
                    953:                 }
1.899     raeburn   954:                 foreach my $match (@matches) {
                    955:                     my ($uname,$udom,%userhash);
1.911     raeburn   956:                     foreach my $entry (split(/:/,$match)) {
                    957:                         my ($key,$value) =
                    958:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn   959:                         $userhash{$key} = $value;
                    960:                         if ($key eq 'username') {
                    961:                             $uname = $value;
                    962:                         } elsif ($key eq 'domain') {
                    963:                             $udom = $value;
1.911     raeburn   964:                         }
1.899     raeburn   965:                     }
                    966:                     $results{$uname.':'.$udom} = \%userhash;
                    967:                 }
                    968:             }
                    969:         }
                    970:     }
                    971:     return %results;
                    972: }
                    973: 
1.912     raeburn   974: sub get_instuser {
                    975:     my ($udom,$uname,$id) = @_;
                    976:     my $homeserver = &domain($udom,'primary');
                    977:     my ($outcome,%results);
                    978:     if ($homeserver ne '') {
                    979:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                    980:                            &escape($id).':'.&escape($udom),$homeserver);
                    981:         my $host=&hostname($homeserver);
                    982:         if ($queryid !~/^\Q$host\E\_/) {
                    983:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    984:             return;
                    985:         }
                    986:         my $response = &get_query_reply($queryid);
                    987:         my $maxtries = 5;
                    988:         my $tries = 1;
                    989:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    990:             $response = &get_query_reply($queryid);
                    991:             $tries ++;
                    992:         }
                    993:         if (!&error($response) && $response ne 'refused') {
                    994:             if ($response eq 'unavailable') {
                    995:                 $outcome = $response;
                    996:             } else {
                    997:                 $outcome = 'ok';
                    998:                 my @matches = split(/\n/,$response);
                    999:                 foreach my $match (@matches) {
                   1000:                     my ($key,$value) = split(/=/,$match);
                   1001:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1002:                 }
                   1003:             }
                   1004:         }
                   1005:     }
                   1006:     my %userinfo;
                   1007:     if (ref($results{$uname}) eq 'HASH') {
                   1008:         %userinfo = %{$results{$uname}};
                   1009:     } 
                   1010:     return ($outcome,%userinfo);
                   1011: }
                   1012: 
                   1013: sub inst_rulecheck {
                   1014:     my ($udom,$uname,$rules) = @_;
                   1015:     my %returnhash;
                   1016:     if ($udom ne '') {
                   1017:         if (ref($rules) eq 'ARRAY') {
                   1018:             @{$rules} = map {&escape($_);} (@{$rules});
                   1019:             my $rulestr = join(':',@{$rules});
                   1020:             my $homeserver=&domain($udom,'primary');
                   1021:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
                   1022:                 my $response=&unescape(&reply('instrulecheck:'.&escape($udom).':'.
                   1023:                                               &escape($uname).':'.$rulestr,
                   1024:                                               $homeserver));
                   1025:                 if ($response ne 'refused') {
                   1026:                     my @pairs=split(/\&/,$response);
                   1027:                     foreach my $item (@pairs) {
                   1028:                         my ($key,$value)=split(/=/,$item,2);
                   1029:                         $key = &unescape($key);
                   1030:                         next if ($key =~ /^error: 2 /);
                   1031:                         $returnhash{$key}=&thaw_unescape($value);
                   1032:                     }
                   1033:                 }
                   1034:             }
                   1035:         }
                   1036:     }
                   1037:     return %returnhash;
                   1038: }
                   1039: 
                   1040: sub inst_userrules {
                   1041:     my ($udom) = @_;
                   1042:     my (%ruleshash,@ruleorder);
                   1043:     if ($udom ne '') {
                   1044:         my $homeserver=&domain($udom,'primary');
                   1045:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
                   1046:             my $response=&reply('instuserrules:'.&escape($udom),
                   1047:                                  $homeserver);
                   1048:             if (($response ne 'refused') && ($response ne 'error') && 
                   1049:                 ($response ne 'no_such_host')) {
                   1050:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1051:                 my @pairs=split(/\&/,$hashitems);
                   1052:                 foreach my $item (@pairs) {
                   1053:                     my ($key,$value)=split(/=/,$item,2);
                   1054:                     $key = &unescape($key);
                   1055:                     next if ($key =~ /^error: 2 /);
                   1056:                     $ruleshash{$key}=&thaw_unescape($value);
                   1057:                 }
                   1058:                 my @esc_order = split(/\&/,$orderitems);
                   1059:                 foreach my $item (@esc_order) {
                   1060:                     push(@ruleorder,&unescape($item));
                   1061:                 }
                   1062:             }
                   1063:         }
                   1064:     }
                   1065:     return (\%ruleshash,\@ruleorder);
                   1066: }
                   1067: 
1.344     www      1068: # --------------------------------------------------- Assign a key to a student
                   1069: 
                   1070: sub assign_access_key {
1.364     www      1071: #
                   1072: # a valid key looks like uname:udom#comments
                   1073: # comments are being appended
                   1074: #
1.498     www      1075:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1076:     $kdom=
1.620     albertel 1077:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1078:     $knum=
1.620     albertel 1079:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1080:     $cdom=
1.620     albertel 1081:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1082:     $cnum=
1.620     albertel 1083:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1084:     $udom=$env{'user.name'} unless (defined($udom));
                   1085:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1086:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1087:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1088:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1089:                                                   # assigned to this person
                   1090:                                                   # - this should not happen,
1.345     www      1091:                                                   # unless something went wrong
                   1092:                                                   # the first time around
                   1093: # ready to assign
1.364     www      1094:         $logentry=$1.'; '.$logentry;
1.496     www      1095:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1096:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1097: # key now belongs to user
1.346     www      1098: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1099:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                   1100:                 &appenv('environment.'.$envkey => $ckey);
                   1101:                 return 'ok';
                   1102:             } else {
                   1103:                 return 
                   1104:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1105: 	    }
                   1106:         } else {
                   1107:             return 'error: Could not assign key, try again later.';
                   1108:         }
1.364     www      1109:     } elsif (!$existing{$ckey}) {
1.345     www      1110: # the key does not exist
                   1111: 	return 'error: The key does not exist';
                   1112:     } else {
                   1113: # the key is somebody else's
                   1114: 	return 'error: The key is already in use';
                   1115:     }
1.344     www      1116: }
                   1117: 
1.364     www      1118: # ------------------------------------------ put an additional comment on a key
                   1119: 
                   1120: sub comment_access_key {
                   1121: #
                   1122: # a valid key looks like uname:udom#comments
                   1123: # comments are being appended
                   1124: #
                   1125:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1126:     $cdom=
1.620     albertel 1127:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1128:     $cnum=
1.620     albertel 1129:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1130:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1131:     if ($existing{$ckey}) {
                   1132:         $existing{$ckey}.='; '.$logentry;
                   1133: # ready to assign
1.367     www      1134:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1135:                                                  $cdom,$cnum) eq 'ok') {
                   1136: 	    return 'ok';
                   1137:         } else {
                   1138: 	    return 'error: Count not store comment.';
                   1139:         }
                   1140:     } else {
                   1141: # the key does not exist
                   1142: 	return 'error: The key does not exist';
                   1143:     }
                   1144: }
                   1145: 
1.344     www      1146: # ------------------------------------------------------ Generate a set of keys
                   1147: 
                   1148: sub generate_access_keys {
1.364     www      1149:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1150:     $cdom=
1.620     albertel 1151:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1152:     $cnum=
1.620     albertel 1153:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1154:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1155:     unless (($cdom) && ($cnum)) { return 0; }
                   1156:     if ($number>10000) { return 0; }
                   1157:     sleep(2); # make sure don't get same seed twice
                   1158:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1159:     my $total=0;
                   1160:     for (my $i=1;$i<=$number;$i++) {
                   1161:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1162:                   sprintf("%lx",int(100000*rand)).'-'.
                   1163:                   sprintf("%lx",int(100000*rand));
                   1164:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1165:        $newkey=~s/0/h/g; # and also 0 and O
                   1166:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1167:        if ($existing{$newkey}) {
                   1168:            $i--;
                   1169:        } else {
1.364     www      1170: 	  if (&put('accesskeys',
                   1171:               { $newkey => '# generated '.localtime().
1.620     albertel 1172:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1173:                            '; '.$logentry },
                   1174: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1175:               $total++;
                   1176: 	  }
                   1177:        }
                   1178:     }
1.620     albertel 1179:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1180:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1181:     return $total;
                   1182: }
                   1183: 
                   1184: # ------------------------------------------------------- Validate an accesskey
                   1185: 
                   1186: sub validate_access_key {
                   1187:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1188:     $cdom=
1.620     albertel 1189:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1190:     $cnum=
1.620     albertel 1191:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1192:     $udom=$env{'user.domain'} unless (defined($udom));
                   1193:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1194:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1195:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1196: }
                   1197: 
                   1198: # ------------------------------------- Find the section of student in a course
1.652     albertel 1199: sub devalidate_getsection_cache {
                   1200:     my ($udom,$unam,$courseid)=@_;
                   1201:     my $hashid="$udom:$unam:$courseid";
                   1202:     &devalidate_cache_new('getsection',$hashid);
                   1203: }
1.298     matthew  1204: 
1.815     albertel 1205: sub courseid_to_courseurl {
                   1206:     my ($courseid) = @_;
                   1207:     #already url style courseid
                   1208:     return $courseid if ($courseid =~ m{^/});
                   1209: 
                   1210:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1211: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1212: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1213: 	return "/$cdom/$cnum";
                   1214:     }
                   1215: 
                   1216:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1217:     if (exists($courseinfo{'num'})) {
                   1218: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1219:     }
                   1220: 
                   1221:     return undef;
                   1222: }
                   1223: 
1.298     matthew  1224: sub getsection {
                   1225:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1226:     my $cachetime=1800;
1.551     albertel 1227: 
                   1228:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1229:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1230:     if (defined($cached)) { return $result; }
                   1231: 
1.298     matthew  1232:     my %Pending; 
                   1233:     my %Expired;
                   1234:     #
                   1235:     # Each role can either have not started yet (pending), be active, 
                   1236:     #    or have expired.
                   1237:     #
                   1238:     # If there is an active role, we are done.
                   1239:     #
                   1240:     # If there is more than one role which has not started yet, 
                   1241:     #     choose the one which will start sooner
                   1242:     # If there is one role which has not started yet, return it.
                   1243:     #
                   1244:     # If there is more than one expired role, choose the one which ended last.
                   1245:     # If there is a role which has expired, return it.
                   1246:     #
1.815     albertel 1247:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1248:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1249:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1250:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1251:         my $section=$1;
                   1252:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1253:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1254:         my $now=time;
1.548     albertel 1255:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1256:             $Expired{$end}=$section;
                   1257:             next;
                   1258:         }
1.548     albertel 1259:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1260:             $Pending{$start}=$section;
                   1261:             next;
                   1262:         }
1.599     albertel 1263:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1264:     }
                   1265:     #
                   1266:     # Presumedly there will be few matching roles from the above
                   1267:     # loop and the sorting time will be negligible.
                   1268:     if (scalar(keys(%Pending))) {
                   1269:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1270:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1271:     } 
                   1272:     if (scalar(keys(%Expired))) {
                   1273:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1274:         my $time = pop(@sorted);
1.599     albertel 1275:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1276:     }
1.599     albertel 1277:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1278: }
1.70      www      1279: 
1.599     albertel 1280: sub save_cache {
                   1281:     &purge_remembered();
1.722     albertel 1282:     #&Apache::loncommon::validate_page();
1.620     albertel 1283:     undef(%env);
1.780     albertel 1284:     undef($env_loaded);
1.599     albertel 1285: }
1.452     albertel 1286: 
1.599     albertel 1287: my $to_remember=-1;
                   1288: my %remembered;
                   1289: my %accessed;
                   1290: my $kicks=0;
                   1291: my $hits=0;
1.849     albertel 1292: sub make_key {
                   1293:     my ($name,$id) = @_;
1.872     albertel 1294:     if (length($id) > 65 
                   1295: 	&& length(&escape($id)) > 200) {
                   1296: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1297:     }
1.849     albertel 1298:     return &escape($name.':'.$id);
                   1299: }
                   1300: 
1.599     albertel 1301: sub devalidate_cache_new {
                   1302:     my ($name,$id,$debug) = @_;
                   1303:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1304:     $id=&make_key($name,$id);
1.599     albertel 1305:     $memcache->delete($id);
                   1306:     delete($remembered{$id});
                   1307:     delete($accessed{$id});
                   1308: }
                   1309: 
                   1310: sub is_cached_new {
                   1311:     my ($name,$id,$debug) = @_;
1.849     albertel 1312:     $id=&make_key($name,$id);
1.599     albertel 1313:     if (exists($remembered{$id})) {
                   1314: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1315: 	$accessed{$id}=[&gettimeofday()];
                   1316: 	$hits++;
                   1317: 	return ($remembered{$id},1);
                   1318:     }
                   1319:     my $value = $memcache->get($id);
                   1320:     if (!(defined($value))) {
                   1321: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1322: 	return (undef,undef);
1.416     albertel 1323:     }
1.599     albertel 1324:     if ($value eq '__undef__') {
                   1325: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1326: 	$value=undef;
                   1327:     }
                   1328:     &make_room($id,$value,$debug);
                   1329:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1330:     return ($value,1);
                   1331: }
                   1332: 
                   1333: sub do_cache_new {
                   1334:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1335:     $id=&make_key($name,$id);
1.599     albertel 1336:     my $setvalue=$value;
                   1337:     if (!defined($setvalue)) {
                   1338: 	$setvalue='__undef__';
                   1339:     }
1.623     albertel 1340:     if (!defined($time) ) {
                   1341: 	$time=600;
                   1342:     }
1.599     albertel 1343:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1344:     my $result = $memcache->set($id,$setvalue,$time);
                   1345:     if (! $result) {
1.872     albertel 1346: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1347: 	$memcache->disconnect_all();
1.872     albertel 1348:     }
1.600     albertel 1349:     # need to make a copy of $value
                   1350:     #&make_room($id,$value,$debug);
1.599     albertel 1351:     return $value;
                   1352: }
                   1353: 
                   1354: sub make_room {
                   1355:     my ($id,$value,$debug)=@_;
                   1356:     $remembered{$id}=$value;
                   1357:     if ($to_remember<0) { return; }
                   1358:     $accessed{$id}=[&gettimeofday()];
                   1359:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1360:     my $to_kick;
                   1361:     my $max_time=0;
                   1362:     foreach my $other (keys(%accessed)) {
                   1363: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1364: 	    $to_kick=$other;
                   1365: 	    $max_time=&tv_interval($accessed{$other});
                   1366: 	}
                   1367:     }
                   1368:     delete($remembered{$to_kick});
                   1369:     delete($accessed{$to_kick});
                   1370:     $kicks++;
                   1371:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1372:     return;
                   1373: }
                   1374: 
1.599     albertel 1375: sub purge_remembered {
1.604     albertel 1376:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1377:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1378:     undef(%remembered);
                   1379:     undef(%accessed);
1.428     albertel 1380: }
1.70      www      1381: # ------------------------------------- Read an entry from a user's environment
                   1382: 
                   1383: sub userenvironment {
                   1384:     my ($udom,$unam,@what)=@_;
                   1385:     my %returnhash=();
                   1386:     my @answer=split(/\&/,
                   1387:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1388:                       &homeserver($unam,$udom)));
                   1389:     my $i;
                   1390:     for ($i=0;$i<=$#what;$i++) {
                   1391: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1392:     }
                   1393:     return %returnhash;
1.1       albertel 1394: }
                   1395: 
1.617     albertel 1396: # ---------------------------------------------------------- Get a studentphoto
                   1397: sub studentphoto {
                   1398:     my ($udom,$unam,$ext) = @_;
                   1399:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1400:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1401:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1402:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1403:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1404:             } else {
                   1405:                 my ($result,$perm_reqd)=
1.707     albertel 1406: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1407:                 if ($result eq 'ok') {
                   1408:                     if (!($perm_reqd eq 'yes')) {
                   1409:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1410:                     }
                   1411:                 }
                   1412:             }
                   1413:         }
                   1414:     } else {
                   1415:         my ($result,$perm_reqd) = 
1.707     albertel 1416: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1417:         if ($result eq 'ok') {
                   1418:             if (!($perm_reqd eq 'yes')) {
                   1419:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1420:             }
                   1421:         }
                   1422:     }
                   1423:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1424: }
                   1425: 
                   1426: sub retrievestudentphoto {
                   1427:     my ($udom,$unam,$ext,$type) = @_;
                   1428:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1429:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1430:     if ($ret eq 'ok') {
                   1431:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1432:         if ($type eq 'thumbnail') {
                   1433:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1434:         }
                   1435:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1436:         return $tokenurl;
                   1437:     } else {
                   1438:         if ($type eq 'thumbnail') {
                   1439:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1440:         } else { 
                   1441:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1442:         }
1.617     albertel 1443:     }
                   1444: }
                   1445: 
1.263     www      1446: # -------------------------------------------------------------------- New chat
                   1447: 
                   1448: sub chatsend {
1.724     raeburn  1449:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1450:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1451:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1452:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1453:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1454: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1455: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1456: }
                   1457: 
                   1458: # ------------------------------------------ Find current version of a resource
                   1459: 
                   1460: sub getversion {
                   1461:     my $fname=&clutter(shift);
                   1462:     unless ($fname=~/^\/res\//) { return -1; }
                   1463:     return &currentversion(&filelocation('',$fname));
                   1464: }
                   1465: 
                   1466: sub currentversion {
                   1467:     my $fname=shift;
1.599     albertel 1468:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1469:     if (defined($cached)) { return $result; }
1.292     www      1470:     my $author=$fname;
                   1471:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1472:     my ($udom,$uname)=split(/\//,$author);
                   1473:     my $home=homeserver($uname,$udom);
                   1474:     if ($home eq 'no_host') { 
                   1475:         return -1; 
                   1476:     }
                   1477:     my $answer=reply("currentversion:$fname",$home);
                   1478:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1479: 	return -1;
                   1480:     }
1.599     albertel 1481:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1482: }
                   1483: 
1.1       albertel 1484: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1485: 
1.1       albertel 1486: sub subscribe {
                   1487:     my $fname=shift;
1.761     raeburn  1488:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1489:     $fname=~s/[\n\r]//g;
1.1       albertel 1490:     my $author=$fname;
                   1491:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1492:     my ($udom,$uname)=split(/\//,$author);
                   1493:     my $home=homeserver($uname,$udom);
1.335     albertel 1494:     if ($home eq 'no_host') {
                   1495:         return 'not_found';
1.1       albertel 1496:     }
                   1497:     my $answer=reply("sub:$fname",$home);
1.64      www      1498:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1499: 	$answer.=' by '.$home;
                   1500:     }
1.1       albertel 1501:     return $answer;
                   1502: }
                   1503:     
1.8       www      1504: # -------------------------------------------------------------- Replicate file
                   1505: 
                   1506: sub repcopy {
                   1507:     my $filename=shift;
1.23      www      1508:     $filename=~s/\/+/\//g;
1.607     raeburn  1509:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1510:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1511:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1512: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1513: 	return &repcopy_userfile($filename);
                   1514:     }
1.532     albertel 1515:     $filename=~s/[\n\r]//g;
1.8       www      1516:     my $transname="$filename.in.transfer";
1.828     www      1517: # FIXME: this should flock
1.607     raeburn  1518:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1519:     my $remoteurl=subscribe($filename);
1.64      www      1520:     if ($remoteurl =~ /^con_lost by/) {
                   1521: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1522:            return 'unavailable';
1.8       www      1523:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1524: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1525: 	   return 'not_found';
1.64      www      1526:     } elsif ($remoteurl =~ /^rejected by/) {
                   1527: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1528:            return 'forbidden';
1.20      www      1529:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1530:            return 'ok';
1.8       www      1531:     } else {
1.290     www      1532:         my $author=$filename;
                   1533:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1534:         my ($udom,$uname)=split(/\//,$author);
                   1535:         my $home=homeserver($uname,$udom);
                   1536:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1537:            my @parts=split(/\//,$filename);
                   1538:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1539:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1540:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1541: 	       return 'bad_request';
1.8       www      1542:            }
                   1543:            my $count;
                   1544:            for ($count=5;$count<$#parts;$count++) {
                   1545:                $path.="/$parts[$count]";
                   1546:                if ((-e $path)!=1) {
                   1547: 		   mkdir($path,0777);
                   1548:                }
                   1549:            }
                   1550:            my $ua=new LWP::UserAgent;
                   1551:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1552:            my $response=$ua->request($request,$transname);
                   1553:            if ($response->is_error()) {
                   1554: 	       unlink($transname);
                   1555:                my $message=$response->status_line;
1.672     albertel 1556:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1557:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1558:                return 'unavailable';
1.8       www      1559:            } else {
1.16      www      1560: 	       if ($remoteurl!~/\.meta$/) {
                   1561:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1562:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1563:                   if ($mresponse->is_error()) {
                   1564: 		      unlink($filename.'.meta');
                   1565:                       &logthis(
1.672     albertel 1566:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1567:                   }
                   1568: 	       }
1.8       www      1569:                rename($transname,$filename);
1.607     raeburn  1570:                return 'ok';
1.8       www      1571:            }
1.290     www      1572:        }
1.8       www      1573:     }
1.330     www      1574: }
                   1575: 
                   1576: # ------------------------------------------------ Get server side include body
                   1577: sub ssi_body {
1.381     albertel 1578:     my ($filelink,%form)=@_;
1.606     matthew  1579:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1580:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1581:     }
1.330     www      1582:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1583:                                      &ssi($filelink,%form));
1.778     albertel 1584:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1585:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1586:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1587:     return $output;
1.8       www      1588: }
                   1589: 
1.15      www      1590: # --------------------------------------------------------- Server Side Include
                   1591: 
1.782     albertel 1592: sub absolute_url {
                   1593:     my ($host_name) = @_;
                   1594:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1595:     if ($host_name eq '') {
                   1596: 	$host_name = $ENV{'SERVER_NAME'};
                   1597:     }
                   1598:     return $protocol.$host_name;
                   1599: }
                   1600: 
1.15      www      1601: sub ssi {
                   1602: 
1.23      www      1603:     my ($fn,%form)=@_;
1.15      www      1604: 
                   1605:     my $ua=new LWP::UserAgent;
1.23      www      1606:     
                   1607:     my $request;
1.711     albertel 1608: 
                   1609:     $form{'no_update_last_known'}=1;
1.895     albertel 1610:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1611:     if (%form) {
1.782     albertel 1612:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1613:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1614:     } else {
1.782     albertel 1615:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1616:     }
                   1617: 
1.15      www      1618:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1619:     my $response=$ua->request($request);
                   1620: 
1.324     www      1621:     return $response->content;
                   1622: }
                   1623: 
                   1624: sub externalssi {
                   1625:     my ($url)=@_;
                   1626:     my $ua=new LWP::UserAgent;
                   1627:     my $request=new HTTP::Request('GET',$url);
                   1628:     my $response=$ua->request($request);
1.15      www      1629:     return $response->content;
                   1630: }
1.254     www      1631: 
1.492     albertel 1632: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1633: 
                   1634: sub allowuploaded {
                   1635:     my ($srcurl,$url)=@_;
                   1636:     $url=&clutter(&declutter($url));
                   1637:     my $dir=$url;
                   1638:     $dir=~s/\/[^\/]+$//;
                   1639:     my %httpref=();
                   1640:     my $httpurl=&hreflocation('',$url);
                   1641:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1642:     &Apache::lonnet::appenv(%httpref);
1.254     www      1643: }
1.477     raeburn  1644: 
1.478     albertel 1645: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1646: # input: action, courseID, current domain, intended
1.637     raeburn  1647: #        path to file, source of file, instruction to parse file for objects,
                   1648: #        ref to hash for embedded objects,
                   1649: #        ref to hash for codebase of java objects.
                   1650: #
1.485     raeburn  1651: # output: url to file (if action was uploaddoc), 
                   1652: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1653: #
1.478     albertel 1654: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1655: # course.
1.477     raeburn  1656: #
1.478     albertel 1657: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1658: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1659: #          course's home server.
1.477     raeburn  1660: #
1.478     albertel 1661: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1662: #          be copied from $source (current location) to 
                   1663: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1664: #         and will then be copied to
                   1665: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1666: #         course's home server.
1.485     raeburn  1667: #
1.481     raeburn  1668: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1669: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1670: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1671: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1672: #         in course's home server.
1.637     raeburn  1673: #
1.477     raeburn  1674: 
                   1675: sub process_coursefile {
1.638     albertel 1676:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1677:     my $fetchresult;
1.638     albertel 1678:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1679:     if ($action eq 'propagate') {
1.638     albertel 1680:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1681: 			     $home);
1.481     raeburn  1682:     } else {
1.477     raeburn  1683:         my $fpath = '';
                   1684:         my $fname = $file;
1.478     albertel 1685:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1686:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1687:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1688:         if ($action eq 'copy') {
                   1689:             if ($source eq '') {
                   1690:                 $fetchresult = 'no source file';
                   1691:                 return $fetchresult;
                   1692:             } else {
                   1693:                 my $destination = $filepath.'/'.$fname;
                   1694:                 rename($source,$destination);
                   1695:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1696:                                  $home);
1.481     raeburn  1697:             }
                   1698:         } elsif ($action eq 'uploaddoc') {
                   1699:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1700:             print $fh $env{'form.'.$source};
1.481     raeburn  1701:             close($fh);
1.637     raeburn  1702:             if ($parser eq 'parse') {
                   1703:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1704:                 unless ($parse_result eq 'ok') {
                   1705:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1706:                 }
                   1707:             }
1.477     raeburn  1708:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1709:                                  $home);
1.481     raeburn  1710:             if ($fetchresult eq 'ok') {
                   1711:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1712:             } else {
                   1713:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1714:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1715:                 return '/adm/notfound.html';
                   1716:             }
1.477     raeburn  1717:         }
                   1718:     }
1.485     raeburn  1719:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1720:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1721:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1722:     }
                   1723:     return $fetchresult;
                   1724: }
                   1725: 
1.637     raeburn  1726: sub build_filepath {
                   1727:     my ($fpath) = @_;
                   1728:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1729:     unless ($fpath eq '') {
                   1730:         my @parts=split('/',$fpath);
                   1731:         foreach my $part (@parts) {
                   1732:             $filepath.= '/'.$part;
                   1733:             if ((-e $filepath)!=1) {
                   1734:                 mkdir($filepath,0777);
                   1735:             }
                   1736:         }
                   1737:     }
                   1738:     return $filepath;
                   1739: }
                   1740: 
                   1741: sub store_edited_file {
1.638     albertel 1742:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1743:     my $file = $primary_url;
                   1744:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1745:     my $fpath = '';
                   1746:     my $fname = $file;
                   1747:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1748:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1749:     my $filepath = &build_filepath($fpath);
                   1750:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1751:     print $fh $content;
                   1752:     close($fh);
1.638     albertel 1753:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1754:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1755: 			  $home);
1.637     raeburn  1756:     if ($$fetchresult eq 'ok') {
                   1757:         return '/uploaded/'.$fpath.'/'.$fname;
                   1758:     } else {
1.638     albertel 1759:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1760: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1761:         return '/adm/notfound.html';
                   1762:     }
                   1763: }
                   1764: 
1.531     albertel 1765: sub clean_filename {
1.831     albertel 1766:     my ($fname,$args)=@_;
1.315     www      1767: # Replace Windows backslashes by forward slashes
1.257     www      1768:     $fname=~s/\\/\//g;
1.831     albertel 1769:     if (!$args->{'keep_path'}) {
                   1770:         # Get rid of everything but the actual filename
                   1771: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1772:     }
1.315     www      1773: # Replace spaces by underscores
                   1774:     $fname=~s/\s+/\_/g;
                   1775: # Replace all other weird characters by nothing
1.831     albertel 1776:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1777: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1778: # numbers
                   1779:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1780:     return $fname;
                   1781: }
                   1782: 
1.608     albertel 1783: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1784: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1785: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1786: #        $coursedoc - if true up to the current course
                   1787: #                     if false
                   1788: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1789: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1790: #        $allfiles - reference to hash for embedded objects
                   1791: #        $codebase - reference to hash for codebase of java objects
                   1792: #        $desuname - username for permanent storage of uploaded file
                   1793: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1794: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1795: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1796: # 
1.686     albertel 1797: # output: url of file in userspace, or error: <message> 
                   1798: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1799: 
                   1800: 
1.531     albertel 1801: sub userfileupload {
1.860     raeburn  1802:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1803:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1804:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1805:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1806:     $fname=&clean_filename($fname);
1.315     www      1807: # See if there is anything left
1.257     www      1808:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1809:     chop($env{'form.'.$formname});
1.523     raeburn  1810:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1811:         my $now = time;
                   1812:         my $filepath = 'tmp/helprequests/'.$now;
                   1813:         my @parts=split(/\//,$filepath);
                   1814:         my $fullpath = $perlvar{'lonDaemons'};
                   1815:         for (my $i=0;$i<@parts;$i++) {
                   1816:             $fullpath .= '/'.$parts[$i];
                   1817:             if ((-e $fullpath)!=1) {
                   1818:                 mkdir($fullpath,0777);
                   1819:             }
                   1820:         }
                   1821:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1822:         print $fh $env{'form.'.$formname};
1.523     raeburn  1823:         close($fh);
1.741     raeburn  1824:         return $fullpath.'/'.$fname;
                   1825:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1826:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1827:                        '_'.$env{'user.domain'}.'/pending';
                   1828:         my @parts=split(/\//,$filepath);
                   1829:         my $fullpath = $perlvar{'lonDaemons'};
                   1830:         for (my $i=0;$i<@parts;$i++) {
                   1831:             $fullpath .= '/'.$parts[$i];
                   1832:             if ((-e $fullpath)!=1) {
                   1833:                 mkdir($fullpath,0777);
                   1834:             }
                   1835:         }
                   1836:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1837:         print $fh $env{'form.'.$formname};
                   1838:         close($fh);
                   1839:         return $fullpath.'/'.$fname;
1.523     raeburn  1840:     }
1.719     banghart 1841:     
1.258     www      1842: # Create the directory if not present
1.493     albertel 1843:     $fname="$subdir/$fname";
1.259     www      1844:     if ($coursedoc) {
1.638     albertel 1845: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1846: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1847:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1848:             return &finishuserfileupload($docuname,$docudom,
                   1849: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1850: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1851:         } else {
1.620     albertel 1852:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1853:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1854: 				       $fname,$formname,$parser,
                   1855: 				       $allfiles,$codebase);
1.481     raeburn  1856:         }
1.719     banghart 1857:     } elsif (defined($destuname)) {
                   1858:         my $docuname=$destuname;
                   1859:         my $docudom=$destudom;
1.860     raeburn  1860: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1861: 				     $parser,$allfiles,$codebase,
                   1862:                                      $thumbwidth,$thumbheight);
1.719     banghart 1863:         
1.259     www      1864:     } else {
1.638     albertel 1865:         my $docuname=$env{'user.name'};
                   1866:         my $docudom=$env{'user.domain'};
1.714     raeburn  1867:         if (exists($env{'form.group'})) {
                   1868:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1869:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1870:         }
1.860     raeburn  1871: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1872: 				     $parser,$allfiles,$codebase,
                   1873:                                      $thumbwidth,$thumbheight);
1.259     www      1874:     }
1.271     www      1875: }
                   1876: 
                   1877: sub finishuserfileupload {
1.860     raeburn  1878:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1879:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1880:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1881:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1882:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1883:     $file=$fname;
                   1884:     if ($fname=~m|/|) {
                   1885:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1886: 	$path.=$fnamepath.'/';
                   1887:     }
1.259     www      1888:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1889:     my $count;
                   1890:     for ($count=4;$count<=$#parts;$count++) {
                   1891:         $filepath.="/$parts[$count]";
                   1892:         if ((-e $filepath)!=1) {
                   1893: 	    mkdir($filepath,0777);
                   1894:         }
                   1895:     }
                   1896: # Save the file
                   1897:     {
1.701     albertel 1898: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1899: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1900: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1901: 	    return '/adm/notfound.html';
                   1902: 	}
                   1903: 	if (!print FH ($env{'form.'.$formname})) {
                   1904: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1905: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1906: 	    return '/adm/notfound.html';
                   1907: 	}
1.570     albertel 1908: 	close(FH);
1.258     www      1909:     }
1.637     raeburn  1910:     if ($parser eq 'parse') {
1.638     albertel 1911:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1912: 						   $codebase);
1.637     raeburn  1913:         unless ($parse_result eq 'ok') {
1.638     albertel 1914:             &logthis('Failed to parse '.$filepath.$file.
                   1915: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1916:         }
                   1917:     }
1.860     raeburn  1918:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1919:         my $input = $filepath.'/'.$file;
                   1920:         my $output = $filepath.'/'.'tn-'.$file;
                   1921:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1922:         system("convert -sample $thumbsize $input $output");
                   1923:         if (-e $filepath.'/'.'tn-'.$file) {
                   1924:             $fetchthumb  = 1; 
                   1925:         }
                   1926:     }
1.858     raeburn  1927:  
1.259     www      1928: # Notify homeserver to grep it
                   1929: #
1.638     albertel 1930:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1931:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1932:     if ($fetchresult eq 'ok') {
1.860     raeburn  1933:         if ($fetchthumb) {
                   1934:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1935:             if ($thumbresult ne 'ok') {
                   1936:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1937:                          $docuhome.': '.$thumbresult);
                   1938:             }
                   1939:         }
1.259     www      1940: #
1.258     www      1941: # Return the URL to it
1.494     albertel 1942:         return '/uploaded/'.$path.$file;
1.263     www      1943:     } else {
1.494     albertel 1944:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1945: 		 ': '.$fetchresult);
1.263     www      1946:         return '/adm/notfound.html';
1.858     raeburn  1947:     }
1.493     albertel 1948: }
                   1949: 
1.637     raeburn  1950: sub extract_embedded_items {
1.648     raeburn  1951:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1952:     my @state = ();
                   1953:     my %javafiles = (
                   1954:                       codebase => '',
                   1955:                       code => '',
                   1956:                       archive => ''
                   1957:                     );
                   1958:     my %mediafiles = (
                   1959:                       src => '',
                   1960:                       movie => '',
                   1961:                      );
1.648     raeburn  1962:     my $p;
                   1963:     if ($content) {
                   1964:         $p = HTML::LCParser->new($content);
                   1965:     } else {
                   1966:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1967:     }
1.641     albertel 1968:     while (my $t=$p->get_token()) {
1.640     albertel 1969: 	if ($t->[0] eq 'S') {
                   1970: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1971: 	    push(@state, $tagname);
1.648     raeburn  1972:             if (lc($tagname) eq 'allow') {
                   1973:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1974:             }
1.640     albertel 1975: 	    if (lc($tagname) eq 'img') {
                   1976: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1977: 	    }
1.886     albertel 1978: 	    if (lc($tagname) eq 'a') {
                   1979: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1980: 	    }
1.645     raeburn  1981:             if (lc($tagname) eq 'script') {
                   1982:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1983:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1984:                 } else {
                   1985:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1986:                 }
                   1987:             }
                   1988:             if (lc($tagname) eq 'link') {
                   1989:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1990:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1991:                 }
                   1992:             }
1.640     albertel 1993: 	    if (lc($tagname) eq 'object' ||
                   1994: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1995: 		foreach my $item (keys(%javafiles)) {
                   1996: 		    $javafiles{$item} = '';
                   1997: 		}
                   1998: 	    }
                   1999: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2000: 		my $name = lc($attr->{'name'});
                   2001: 		foreach my $item (keys(%javafiles)) {
                   2002: 		    if ($name eq $item) {
                   2003: 			$javafiles{$item} = $attr->{'value'};
                   2004: 			last;
                   2005: 		    }
                   2006: 		}
                   2007: 		foreach my $item (keys(%mediafiles)) {
                   2008: 		    if ($name eq $item) {
                   2009: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2010: 			last;
                   2011: 		    }
                   2012: 		}
                   2013: 	    }
                   2014: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2015: 		foreach my $item (keys(%javafiles)) {
                   2016: 		    if ($attr->{$item}) {
                   2017: 			$javafiles{$item} = $attr->{$item};
                   2018: 			last;
                   2019: 		    }
                   2020: 		}
                   2021: 		foreach my $item (keys(%mediafiles)) {
                   2022: 		    if ($attr->{$item}) {
                   2023: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2024: 			last;
                   2025: 		    }
                   2026: 		}
                   2027: 	    }
                   2028: 	} elsif ($t->[0] eq 'E') {
                   2029: 	    my ($tagname) = ($t->[1]);
                   2030: 	    if ($javafiles{'codebase'} ne '') {
                   2031: 		$javafiles{'codebase'} .= '/';
                   2032: 	    }  
                   2033: 	    if (lc($tagname) eq 'applet' ||
                   2034: 		lc($tagname) eq 'object' ||
                   2035: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2036: 		) {
                   2037: 		foreach my $item (keys(%javafiles)) {
                   2038: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2039: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2040: 			&add_filetype($allfiles,$file,$item);
                   2041: 		    }
                   2042: 		}
                   2043: 	    } 
                   2044: 	    pop @state;
                   2045: 	}
                   2046:     }
1.637     raeburn  2047:     return 'ok';
                   2048: }
                   2049: 
1.639     albertel 2050: sub add_filetype {
                   2051:     my ($allfiles,$file,$type)=@_;
                   2052:     if (exists($allfiles->{$file})) {
                   2053: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2054: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2055: 	}
                   2056:     } else {
                   2057: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2058:     }
                   2059: }
                   2060: 
1.493     albertel 2061: sub removeuploadedurl {
                   2062:     my ($url)=@_;
                   2063:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2064:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2065: }
                   2066: 
                   2067: sub removeuserfile {
                   2068:     my ($docuname,$docudom,$fname)=@_;
                   2069:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2070:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2071:     if ($result eq 'ok') {
                   2072:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2073:             my $metafile = $fname.'.meta';
                   2074:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2075: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2076:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2077:             my $sqlresult = 
1.823     albertel 2078:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2079:                                         'portfolio_metadata',$group,
                   2080:                                         'delete');
1.798     raeburn  2081:         }
                   2082:     }
                   2083:     return $result;
1.257     www      2084: }
1.15      www      2085: 
1.530     albertel 2086: sub mkdiruserfile {
                   2087:     my ($docuname,$docudom,$dir)=@_;
                   2088:     my $home=&homeserver($docuname,$docudom);
                   2089:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2090: }
                   2091: 
1.531     albertel 2092: sub renameuserfile {
                   2093:     my ($docuname,$docudom,$old,$new)=@_;
                   2094:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2095:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2096:                         &escape("$old").':'.&escape("$new"),$home);
                   2097:     if ($result eq 'ok') {
                   2098:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2099:             my $oldmeta = $old.'.meta';
                   2100:             my $newmeta = $new.'.meta';
                   2101:             my $metaresult = 
                   2102:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2103: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2104:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2105:             my $sqlresult = 
1.823     albertel 2106:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2107:                                         'portfolio_metadata',$group,
                   2108:                                         'delete');
1.798     raeburn  2109:         }
                   2110:     }
                   2111:     return $result;
1.531     albertel 2112: }
                   2113: 
1.14      www      2114: # ------------------------------------------------------------------------- Log
                   2115: 
                   2116: sub log {
                   2117:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2118:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2119: }
                   2120: 
                   2121: # ------------------------------------------------------------------ Course Log
1.352     www      2122: #
                   2123: # This routine flushes several buffers of non-mission-critical nature
                   2124: #
1.157     www      2125: 
                   2126: sub flushcourselogs {
1.352     www      2127:     &logthis('Flushing log buffers');
                   2128: #
                   2129: # course logs
                   2130: # This is a log of all transactions in a course, which can be used
                   2131: # for data mining purposes
                   2132: #
                   2133: # It also collects the courseid database, which lists last transaction
                   2134: # times and course titles for all courseids
                   2135: #
                   2136:     my %courseidbuffer=();
1.800     albertel 2137:     foreach my $crsid (keys %courselogs) {
1.352     www      2138:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2139: 		          &escape($courselogs{$crsid}),
                   2140: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2141: 	    delete $courselogs{$crsid};
                   2142:         } else {
                   2143:             &logthis('Failed to flush log buffer for '.$crsid);
                   2144:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2145:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2146:                         " exceeded maximum size, deleting.</font>");
                   2147:                delete $courselogs{$crsid};
                   2148:             }
1.352     www      2149:         }
                   2150:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2151:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2152: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2153:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2154:         } else {
                   2155:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2156: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2157:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2158:         }
1.191     harris41 2159:     }
1.352     www      2160: #
                   2161: # Write course id database (reverse lookup) to homeserver of courses 
                   2162: # Is used in pickcourse
                   2163: #
1.840     albertel 2164:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2165:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2166: 		     $crs_home);
1.352     www      2167:     }
                   2168: #
                   2169: # File accesses
                   2170: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2171: #
1.449     matthew  2172:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2173:         if ($entry =~ /___count$/) {
                   2174:             my ($dom,$name);
1.807     albertel 2175:             ($dom,$name,undef)=
1.811     albertel 2176: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2177:             if (! defined($dom) || $dom eq '' || 
                   2178:                 ! defined($name) || $name eq '') {
1.620     albertel 2179:                 my $cid = $env{'request.course.id'};
                   2180:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2181:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2182:             }
1.450     matthew  2183:             my $value = $accesshash{$entry};
                   2184:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2185:             my %temphash=($url => $value);
1.449     matthew  2186:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2187:             if ($result eq 'ok') {
                   2188:                 delete $accesshash{$entry};
                   2189:             } elsif ($result eq 'unknown_cmd') {
                   2190:                 # Target server has old code running on it.
1.450     matthew  2191:                 my %temphash=($entry => $value);
1.449     matthew  2192:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2193:                     delete $accesshash{$entry};
                   2194:                 }
                   2195:             }
                   2196:         } else {
1.811     albertel 2197:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2198:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2199:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2200:                 delete $accesshash{$entry};
                   2201:             }
1.185     www      2202:         }
1.191     harris41 2203:     }
1.352     www      2204: #
                   2205: # Roles
                   2206: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2207: #
1.800     albertel 2208:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2209:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2210: 	    split(/\:/,$entry);
                   2211:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2212:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2213:                 $rudom,$runame) eq 'ok') {
                   2214: 	    delete $userrolehash{$entry};
                   2215:         }
                   2216:     }
1.662     raeburn  2217: #
                   2218: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2219: #
                   2220:     my %domrolebuffer = ();
                   2221:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2222:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2223:         if ($domrolebuffer{$rudom}) {
                   2224:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2225:                       '='.&escape($domainrolehash{$entry});
                   2226:         } else {
                   2227:             $domrolebuffer{$rudom}.=&escape($entry).
                   2228:                       '='.&escape($domainrolehash{$entry});
                   2229:         }
                   2230:         delete $domainrolehash{$entry};
                   2231:     }
                   2232:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2233: 	my %servers = &get_servers($dom,'library');
                   2234: 	foreach my $tryserver (keys(%servers)) {
                   2235: 	    unless (&reply('domroleput:'.$dom.':'.
                   2236: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2237: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2238: 	    }
1.662     raeburn  2239:         }
                   2240:     }
1.186     www      2241:     $dumpcount++;
1.157     www      2242: }
                   2243: 
                   2244: sub courselog {
                   2245:     my $what=shift;
1.158     www      2246:     $what=time.':'.$what;
1.620     albertel 2247:     unless ($env{'request.course.id'}) { return ''; }
                   2248:     $coursedombuf{$env{'request.course.id'}}=
                   2249:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2250:     $coursenumbuf{$env{'request.course.id'}}=
                   2251:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2252:     $coursehombuf{$env{'request.course.id'}}=
                   2253:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2254:     $coursedescrbuf{$env{'request.course.id'}}=
                   2255:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2256:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2257:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2258:     $courseownerbuf{$env{'request.course.id'}}=
                   2259:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2260:     $coursetypebuf{$env{'request.course.id'}}=
                   2261:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2262:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2263: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2264:     } else {
1.620     albertel 2265: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2266:     }
1.620     albertel 2267:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2268: 	&flushcourselogs();
                   2269:     }
1.158     www      2270: }
                   2271: 
                   2272: sub courseacclog {
                   2273:     my $fnsymb=shift;
1.620     albertel 2274:     unless ($env{'request.course.id'}) { return ''; }
                   2275:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2276:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2277:         $what.=':POST';
1.583     matthew  2278:         # FIXME: Probably ought to escape things....
1.800     albertel 2279: 	foreach my $key (keys(%env)) {
                   2280:             if ($key=~/^form\.(.*)/) {
                   2281: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2282:             }
1.191     harris41 2283:         }
1.583     matthew  2284:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2285:         # FIXME: We should not be depending on a form parameter that someone
                   2286:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2287:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2288:             $what.= ':POST';
                   2289:             # FIXME: Probably ought to escape things....
                   2290:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2291:                                  'crsdiscuss') {
1.620     albertel 2292:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2293:             }
                   2294:         }
1.158     www      2295:     }
                   2296:     &courselog($what);
1.149     www      2297: }
                   2298: 
1.185     www      2299: sub countacc {
                   2300:     my $url=&declutter(shift);
1.458     matthew  2301:     return if (! defined($url) || $url eq '');
1.620     albertel 2302:     unless ($env{'request.course.id'}) { return ''; }
                   2303:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2304:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2305:     $accesshash{$key}++;
1.185     www      2306: }
1.349     www      2307: 
1.361     www      2308: sub linklog {
                   2309:     my ($from,$to)=@_;
                   2310:     $from=&declutter($from);
                   2311:     $to=&declutter($to);
                   2312:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2313:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2314: }
                   2315:   
1.349     www      2316: sub userrolelog {
                   2317:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2318:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2319:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2320:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2321:         ($trole=~/^ta/)) {
1.350     www      2322:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2323:        $userrolehash
                   2324:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2325:                     =$tend.':'.$tstart;
1.662     raeburn  2326:     }
1.898     albertel 2327:     if (($env{'request.role'} =~ /dc\./) &&
                   2328: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2329: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2330: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2331:        $userrolehash
                   2332:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2333:                     =$tend.':'.$tstart;
                   2334:     }
1.662     raeburn  2335:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2336:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2337:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2338:         ($trole=~/^sc/)) {
                   2339:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2340:        $domainrolehash
                   2341:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2342:                     = $tend.':'.$tstart;
                   2343:     }
1.351     www      2344: }
                   2345: 
                   2346: sub get_course_adv_roles {
                   2347:     my $cid=shift;
1.620     albertel 2348:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2349:     my %coursehash=&coursedescription($cid);
1.470     www      2350:     my %nothide=();
1.800     albertel 2351:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2352: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2353:     }
1.351     www      2354:     my %returnhash=();
                   2355:     my %dumphash=
                   2356:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2357:     my $now=time;
1.800     albertel 2358:     foreach my $entry (keys %dumphash) {
                   2359: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2360:         if (($tstart) && ($tstart<0)) { next; }
                   2361:         if (($tend) && ($tend<$now)) { next; }
                   2362:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2363:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2364: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2365: 	if ((&privileged($username,$domain)) && 
                   2366: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2367: 	if ($role eq 'cr') { next; }
1.351     www      2368:         my $key=&plaintext($role);
                   2369:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2370:         if ($returnhash{$key}) {
                   2371: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2372:         } else {
                   2373:             $returnhash{$key}=$username.':'.$domain;
                   2374:         }
1.400     www      2375:      }
                   2376:     return %returnhash;
                   2377: }
                   2378: 
                   2379: sub get_my_roles {
1.858     raeburn  2380:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2381:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2382:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2383:     my %dumphash;
                   2384:     if ($context eq 'userroles') { 
                   2385:         %dumphash = &dump('roles',$udom,$uname);
                   2386:     } else {
                   2387:         %dumphash=
1.400     www      2388:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2389:     }
1.400     www      2390:     my %returnhash=();
                   2391:     my $now=time;
1.800     albertel 2392:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2393:         my ($role,$tend,$tstart);
                   2394:         if ($context eq 'userroles') {
                   2395: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2396:         } else {
                   2397:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2398:         }
1.400     www      2399:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2400:         my $status = 'active';
                   2401:         if (($tend) && ($tend<$now)) {
                   2402:             $status = 'previous';
                   2403:         } 
                   2404:         if (($tstart) && ($now<$tstart)) {
                   2405:             $status = 'future';
                   2406:         }
                   2407:         if (ref($types) eq 'ARRAY') {
                   2408:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2409:                 next;
                   2410:             } 
                   2411:         } else {
                   2412:             if ($status ne 'active') {
                   2413:                 next;
                   2414:             }
                   2415:         }
1.867     raeburn  2416:         my ($rolecode,$username,$domain,$section,$area);
                   2417:         if ($context eq 'userroles') {
                   2418:             ($area,$rolecode) = split(/_/,$entry);
                   2419:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2420:         } else {
                   2421:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2422:         }
1.832     raeburn  2423:         if (ref($roledoms) eq 'ARRAY') {
                   2424:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2425:                 next;
                   2426:             }
                   2427:         }
                   2428:         if (ref($roles) eq 'ARRAY') {
                   2429:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2430:                 next;
                   2431:             }
1.867     raeburn  2432:         }
1.400     www      2433: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2434:     }
1.373     www      2435:     return %returnhash;
1.399     www      2436: }
                   2437: 
                   2438: # ----------------------------------------------------- Frontpage Announcements
                   2439: #
                   2440: #
                   2441: 
                   2442: sub postannounce {
                   2443:     my ($server,$text)=@_;
1.844     albertel 2444:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2445:     unless ($text=~/\w/) { $text=''; }
                   2446:     return &reply('setannounce:'.&escape($text),$server);
                   2447: }
                   2448: 
                   2449: sub getannounce {
1.448     albertel 2450: 
                   2451:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2452: 	my $announcement='';
1.800     albertel 2453: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2454: 	close($fh);
1.399     www      2455: 	if ($announcement=~/\w/) { 
                   2456: 	    return 
                   2457:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2458:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2459: 	} else {
                   2460: 	    return '';
                   2461: 	}
                   2462:     } else {
                   2463: 	return '';
                   2464:     }
1.351     www      2465: }
1.353     www      2466: 
                   2467: # ---------------------------------------------------------- Course ID routines
                   2468: # Deal with domain's nohist_courseid.db files
                   2469: #
                   2470: 
                   2471: sub courseidput {
                   2472:     my ($domain,$what,$coursehome)=@_;
                   2473:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2474: }
                   2475: 
                   2476: sub courseiddump {
1.791     raeburn  2477:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2478:     my %returnhash=();
1.355     www      2479:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2480:     my %libserv = &all_library();
                   2481:     foreach my $tryserver (keys(%libserv)) {
                   2482:         if ( (  $hostidflag == 1 
                   2483: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2484: 	     || (!defined($hostidflag)) ) {
                   2485: 
                   2486: 	    if ($domfilter eq ''
                   2487: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2488: 	        foreach my $line (
1.844     albertel 2489:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2490: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2491:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2492:                                $tryserver))) {
1.800     albertel 2493: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2494:                     if (($key) && ($value)) {
1.516     raeburn  2495: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2496:                     }
1.353     www      2497:                 }
                   2498:             }
                   2499:         }
                   2500:     }
                   2501:     return %returnhash;
                   2502: }
                   2503: 
1.658     raeburn  2504: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2505: 
                   2506: sub dcmailput {
1.685     raeburn  2507:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2508:     my $status = &Apache::lonnet::critical(
1.740     www      2509:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2510:        &escape($message),$server);
1.662     raeburn  2511:     return $status;
                   2512: }
                   2513: 
1.658     raeburn  2514: sub dcmaildump {
                   2515:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2516:     my %returnhash=();
1.846     albertel 2517: 
                   2518:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2519:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2520:                                                          &escape($enddate).':';
                   2521: 	my @esc_senders=map { &escape($_)} @$senders;
                   2522: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2523: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2524:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2525:             if (($key) && ($value)) {
                   2526:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2527:             }
                   2528:         }
                   2529:     }
                   2530:     return %returnhash;
                   2531: }
1.662     raeburn  2532: # ---------------------------------------------------------- Domain roles
                   2533: 
                   2534: sub get_domain_roles {
                   2535:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2536:     if (undef($startdate) || $startdate eq '') {
                   2537:         $startdate = '.';
                   2538:     }
                   2539:     if (undef($enddate) || $enddate eq '') {
                   2540:         $enddate = '.';
                   2541:     }
                   2542:     my $rolelist = join(':',@{$roles});
                   2543:     my %personnel = ();
1.841     albertel 2544: 
                   2545:     my %servers = &get_servers($dom,'library');
                   2546:     foreach my $tryserver (keys(%servers)) {
                   2547: 	%{$personnel{$tryserver}}=();
                   2548: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2549: 					    &escape($startdate).':'.
                   2550: 					    &escape($enddate).':'.
                   2551: 					    &escape($rolelist), $tryserver))) {
                   2552: 	    my ($key,$value) = split(/\=/,$line,2);
                   2553: 	    if (($key) && ($value)) {
                   2554: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2555: 	    }
                   2556: 	}
1.662     raeburn  2557:     }
                   2558:     return %personnel;
                   2559: }
1.658     raeburn  2560: 
1.149     www      2561: # ----------------------------------------------------------- Check out an item
                   2562: 
1.504     albertel 2563: sub get_first_access {
                   2564:     my ($type,$argsymb)=@_;
1.790     albertel 2565:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2566:     if ($argsymb) { $symb=$argsymb; }
                   2567:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2568:     if ($type eq 'map') {
                   2569: 	$res=&symbread($map);
                   2570:     } else {
                   2571: 	$res=$symb;
                   2572:     }
                   2573:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2574:     return $times{"$courseid\0$res"};
1.504     albertel 2575: }
                   2576: 
                   2577: sub set_first_access {
                   2578:     my ($type)=@_;
1.790     albertel 2579:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2580:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2581:     if ($type eq 'map') {
                   2582: 	$res=&symbread($map);
                   2583:     } else {
                   2584: 	$res=$symb;
                   2585:     }
                   2586:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2587:     if (!$firstaccess) {
1.588     albertel 2588: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2589:     }
                   2590:     return 'already_set';
1.504     albertel 2591: }
                   2592: 
1.149     www      2593: sub checkout {
                   2594:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2595:     my $now=time;
                   2596:     my $lonhost=$perlvar{'lonHostID'};
                   2597:     my $infostr=&escape(
1.234     www      2598:                  'CHECKOUTTOKEN&'.
1.149     www      2599:                  $tuname.'&'.
                   2600:                  $tudom.'&'.
                   2601:                  $tcrsid.'&'.
                   2602:                  $symb.'&'.
                   2603: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2604:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2605:     if ($token=~/^error\:/) { 
1.672     albertel 2606:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2607:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2608:                  "</font>");
                   2609:         return ''; 
                   2610:     }
                   2611: 
1.149     www      2612:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2613:     $token=~tr/a-z/A-Z/;
                   2614: 
1.153     www      2615:     my %infohash=('resource.0.outtoken' => $token,
                   2616:                   'resource.0.checkouttime' => $now,
                   2617:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2618: 
                   2619:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2620:        return '';
1.151     www      2621:     } else {
1.672     albertel 2622:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2623:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2624:                  "</font>");
1.149     www      2625:     }    
                   2626: 
                   2627:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2628:                          &escape('Checkout '.$infostr.' - '.
                   2629:                                                  $token)) ne 'ok') {
                   2630: 	return '';
1.151     www      2631:     } else {
1.672     albertel 2632:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2633:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2634:                  "</font>");
1.149     www      2635:     }
1.151     www      2636:     return $token;
1.149     www      2637: }
                   2638: 
                   2639: # ------------------------------------------------------------ Check in an item
                   2640: 
                   2641: sub checkin {
                   2642:     my $token=shift;
1.150     www      2643:     my $now=time;
                   2644:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2645:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2646:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2647:     $dtoken=~s/\W/\_/g;
1.234     www      2648:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2649:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2650: 
1.154     www      2651:     unless (($tuname) && ($tudom)) {
                   2652:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2653:         return '';
                   2654:     }
                   2655:     
                   2656:     unless (&allowed('mgr',$tcrsid)) {
                   2657:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2658:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2659:         return '';
                   2660:     }
                   2661: 
1.153     www      2662:     my %infohash=('resource.0.intoken' => $token,
                   2663:                   'resource.0.checkintime' => $now,
                   2664:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2665: 
                   2666:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2667:        return '';
                   2668:     }    
                   2669: 
                   2670:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2671:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2672: 	return '';
                   2673:     }
                   2674: 
                   2675:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2676: }
                   2677: 
                   2678: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2679: 
                   2680: sub expirespread {
                   2681:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2682:     my $cid=$env{'request.course.id'}; 
1.110     www      2683:     if ($cid) {
                   2684:        my $now=time;
                   2685:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2686:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2687:                             $env{'course.'.$cid.'.num'}.
1.110     www      2688: 	        	    ':nohist_expirationdates:'.
                   2689:                             &escape($key).'='.$now,
1.620     albertel 2690:                             $env{'course.'.$cid.'.home'})
1.110     www      2691:     }
                   2692:     return 'ok';
1.14      www      2693: }
                   2694: 
1.109     www      2695: # ----------------------------------------------------- Devalidate Spreadsheets
                   2696: 
                   2697: sub devalidate {
1.325     www      2698:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2699:     my $cid=$env{'request.course.id'}; 
1.109     www      2700:     if ($cid) {
1.391     matthew  2701:         # delete the stored spreadsheets for
                   2702:         # - the student level sheet of this user in course's homespace
                   2703:         # - the assessment level sheet for this resource 
                   2704:         #   for this user in user's homespace
1.553     albertel 2705: 	# - current conditional state info
1.325     www      2706: 	my $key=$uname.':'.$udom.':';
1.109     www      2707:         my $status=
1.299     matthew  2708: 	    &del('nohist_calculatedsheets',
1.391     matthew  2709: 		 [$key.'studentcalc:'],
1.620     albertel 2710: 		 $env{'course.'.$cid.'.domain'},
                   2711: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2712: 		.' '.
                   2713: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2714: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2715:         unless ($status eq 'ok ok') {
                   2716:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2717:                     $uname.' at '.$udom.' for '.
1.109     www      2718: 		    $symb.': '.$status);
1.133     albertel 2719:         }
1.553     albertel 2720: 	&delenv('user.state.'.$cid);
1.109     www      2721:     }
                   2722: }
                   2723: 
1.265     albertel 2724: sub get_scalar {
                   2725:     my ($string,$end) = @_;
                   2726:     my $value;
                   2727:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2728: 	$value = $1;
                   2729:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2730: 	$value = $1;
                   2731:     }
                   2732:     return &unescape($value);
                   2733: }
                   2734: 
                   2735: sub array2str {
                   2736:   my (@array) = @_;
                   2737:   my $result=&arrayref2str(\@array);
                   2738:   $result=~s/^__ARRAY_REF__//;
                   2739:   $result=~s/__END_ARRAY_REF__$//;
                   2740:   return $result;
                   2741: }
                   2742: 
1.204     albertel 2743: sub arrayref2str {
                   2744:   my ($arrayref) = @_;
1.265     albertel 2745:   my $result='__ARRAY_REF__';
1.204     albertel 2746:   foreach my $elem (@$arrayref) {
1.265     albertel 2747:     if(ref($elem) eq 'ARRAY') {
                   2748:       $result.=&arrayref2str($elem).'&';
                   2749:     } elsif(ref($elem) eq 'HASH') {
                   2750:       $result.=&hashref2str($elem).'&';
                   2751:     } elsif(ref($elem)) {
                   2752:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2753:     } else {
                   2754:       $result.=&escape($elem).'&';
                   2755:     }
                   2756:   }
                   2757:   $result=~s/\&$//;
1.265     albertel 2758:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2759:   return $result;
                   2760: }
                   2761: 
1.168     albertel 2762: sub hash2str {
1.204     albertel 2763:   my (%hash) = @_;
                   2764:   my $result=&hashref2str(\%hash);
1.265     albertel 2765:   $result=~s/^__HASH_REF__//;
                   2766:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2767:   return $result;
                   2768: }
                   2769: 
                   2770: sub hashref2str {
                   2771:   my ($hashref)=@_;
1.265     albertel 2772:   my $result='__HASH_REF__';
1.800     albertel 2773:   foreach my $key (sort(keys(%$hashref))) {
                   2774:     if (ref($key) eq 'ARRAY') {
                   2775:       $result.=&arrayref2str($key).'=';
                   2776:     } elsif (ref($key) eq 'HASH') {
                   2777:       $result.=&hashref2str($key).'=';
                   2778:     } elsif (ref($key)) {
1.265     albertel 2779:       $result.='=';
1.800     albertel 2780:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2781:     } else {
1.800     albertel 2782: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2783:     }
                   2784: 
1.800     albertel 2785:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2786:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2787:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2788:       $result.=&hashref2str($hashref->{$key}).'&';
                   2789:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2790:        $result.='&';
1.800     albertel 2791:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2792:     } else {
1.800     albertel 2793:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2794:     }
                   2795:   }
1.168     albertel 2796:   $result=~s/\&$//;
1.265     albertel 2797:   $result .= '__END_HASH_REF__';
1.168     albertel 2798:   return $result;
                   2799: }
                   2800: 
                   2801: sub str2hash {
1.265     albertel 2802:     my ($string)=@_;
                   2803:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2804:     return %$hash;
                   2805: }
                   2806: 
                   2807: sub str2hashref {
1.168     albertel 2808:   my ($string) = @_;
1.265     albertel 2809: 
                   2810:   my %hash;
                   2811: 
                   2812:   if($string !~ /^__HASH_REF__/) {
                   2813:       if (! ($string eq '' || !defined($string))) {
                   2814: 	  $hash{'error'}='Not hash reference';
                   2815:       }
                   2816:       return (\%hash, $string);
                   2817:   }
                   2818: 
                   2819:   $string =~ s/^__HASH_REF__//;
                   2820: 
                   2821:   while($string !~ /^__END_HASH_REF__/) {
                   2822:       #key
                   2823:       my $key='';
                   2824:       if($string =~ /^__HASH_REF__/) {
                   2825:           ($key, $string)=&str2hashref($string);
                   2826:           if(defined($key->{'error'})) {
                   2827:               $hash{'error'}='Bad data';
                   2828:               return (\%hash, $string);
                   2829:           }
                   2830:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2831:           ($key, $string)=&str2arrayref($string);
                   2832:           if($key->[0] eq 'Array reference error') {
                   2833:               $hash{'error'}='Bad data';
                   2834:               return (\%hash, $string);
                   2835:           }
                   2836:       } else {
                   2837:           $string =~ s/^(.*?)=//;
1.267     albertel 2838: 	  $key=&unescape($1);
1.265     albertel 2839:       }
                   2840:       $string =~ s/^=//;
                   2841: 
                   2842:       #value
                   2843:       my $value='';
                   2844:       if($string =~ /^__HASH_REF__/) {
                   2845:           ($value, $string)=&str2hashref($string);
                   2846:           if(defined($value->{'error'})) {
                   2847:               $hash{'error'}='Bad data';
                   2848:               return (\%hash, $string);
                   2849:           }
                   2850:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2851:           ($value, $string)=&str2arrayref($string);
                   2852:           if($value->[0] eq 'Array reference error') {
                   2853:               $hash{'error'}='Bad data';
                   2854:               return (\%hash, $string);
                   2855:           }
                   2856:       } else {
                   2857: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2858:       }
                   2859:       $string =~ s/^&//;
                   2860: 
                   2861:       $hash{$key}=$value;
1.204     albertel 2862:   }
1.265     albertel 2863: 
                   2864:   $string =~ s/^__END_HASH_REF__//;
                   2865: 
                   2866:   return (\%hash, $string);
1.204     albertel 2867: }
                   2868: 
                   2869: sub str2array {
1.265     albertel 2870:     my ($string)=@_;
                   2871:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2872:     return @$array;
                   2873: }
                   2874: 
                   2875: sub str2arrayref {
1.204     albertel 2876:   my ($string) = @_;
1.265     albertel 2877:   my @array;
                   2878: 
                   2879:   if($string !~ /^__ARRAY_REF__/) {
                   2880:       if (! ($string eq '' || !defined($string))) {
                   2881: 	  $array[0]='Array reference error';
                   2882:       }
                   2883:       return (\@array, $string);
                   2884:   }
                   2885: 
                   2886:   $string =~ s/^__ARRAY_REF__//;
                   2887: 
                   2888:   while($string !~ /^__END_ARRAY_REF__/) {
                   2889:       my $value='';
                   2890:       if($string =~ /^__HASH_REF__/) {
                   2891:           ($value, $string)=&str2hashref($string);
                   2892:           if(defined($value->{'error'})) {
                   2893:               $array[0] ='Array reference error';
                   2894:               return (\@array, $string);
                   2895:           }
                   2896:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2897:           ($value, $string)=&str2arrayref($string);
                   2898:           if($value->[0] eq 'Array reference error') {
                   2899:               $array[0] ='Array reference error';
                   2900:               return (\@array, $string);
                   2901:           }
                   2902:       } else {
                   2903: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2904:       }
                   2905:       $string =~ s/^&//;
                   2906: 
                   2907:       push(@array, $value);
1.191     harris41 2908:   }
1.265     albertel 2909: 
                   2910:   $string =~ s/^__END_ARRAY_REF__//;
                   2911: 
                   2912:   return (\@array, $string);
1.168     albertel 2913: }
                   2914: 
1.167     albertel 2915: # -------------------------------------------------------------------Temp Store
                   2916: 
1.168     albertel 2917: sub tmpreset {
                   2918:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2919:   if (!$symb) {
                   2920:     $symb=&symbread();
1.620     albertel 2921:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2922:   }
                   2923:   $symb=escape($symb);
                   2924: 
1.620     albertel 2925:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2926:   $namespace=~s/\//\_/g;
                   2927:   $namespace=~s/\W//g;
                   2928: 
1.620     albertel 2929:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2930:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2931:   if ($domain eq 'public' && $stuname eq 'public') {
                   2932:       $stuname=$ENV{'REMOTE_ADDR'};
                   2933:   }
1.168     albertel 2934:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2935:   my %hash;
                   2936:   if (tie(%hash,'GDBM_File',
                   2937: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2938: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2939:     foreach my $key (keys %hash) {
1.180     albertel 2940:       if ($key=~ /:$symb/) {
1.168     albertel 2941: 	delete($hash{$key});
                   2942:       }
                   2943:     }
                   2944:   }
                   2945: }
                   2946: 
1.167     albertel 2947: sub tmpstore {
1.168     albertel 2948:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2949: 
                   2950:   if (!$symb) {
                   2951:     $symb=&symbread();
1.620     albertel 2952:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2953:   }
                   2954:   $symb=escape($symb);
                   2955: 
                   2956:   if (!$namespace) {
                   2957:     # I don't think we would ever want to store this for a course.
                   2958:     # it seems this will only be used if we don't have a course.
1.620     albertel 2959:     #$namespace=$env{'request.course.id'};
1.168     albertel 2960:     #if (!$namespace) {
1.620     albertel 2961:       $namespace=$env{'request.state'};
1.168     albertel 2962:     #}
                   2963:   }
                   2964:   $namespace=~s/\//\_/g;
                   2965:   $namespace=~s/\W//g;
1.620     albertel 2966:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2967:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2968:   if ($domain eq 'public' && $stuname eq 'public') {
                   2969:       $stuname=$ENV{'REMOTE_ADDR'};
                   2970:   }
1.168     albertel 2971:   my $now=time;
                   2972:   my %hash;
                   2973:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2974:   if (tie(%hash,'GDBM_File',
                   2975: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2976: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2977:     $hash{"version:$symb"}++;
                   2978:     my $version=$hash{"version:$symb"};
                   2979:     my $allkeys=''; 
                   2980:     foreach my $key (keys(%$storehash)) {
                   2981:       $allkeys.=$key.':';
1.591     albertel 2982:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2983:     }
                   2984:     $hash{"$version:$symb:timestamp"}=$now;
                   2985:     $allkeys.='timestamp';
                   2986:     $hash{"$version:keys:$symb"}=$allkeys;
                   2987:     if (untie(%hash)) {
                   2988:       return 'ok';
                   2989:     } else {
                   2990:       return "error:$!";
                   2991:     }
                   2992:   } else {
                   2993:     return "error:$!";
                   2994:   }
                   2995: }
1.167     albertel 2996: 
1.168     albertel 2997: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2998: 
1.168     albertel 2999: sub tmprestore {
                   3000:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3001: 
1.168     albertel 3002:   if (!$symb) {
                   3003:     $symb=&symbread();
1.620     albertel 3004:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3005:   }
                   3006:   $symb=escape($symb);
                   3007: 
1.620     albertel 3008:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3009: 
1.620     albertel 3010:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3011:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3012:   if ($domain eq 'public' && $stuname eq 'public') {
                   3013:       $stuname=$ENV{'REMOTE_ADDR'};
                   3014:   }
1.168     albertel 3015:   my %returnhash;
                   3016:   $namespace=~s/\//\_/g;
                   3017:   $namespace=~s/\W//g;
                   3018:   my %hash;
                   3019:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3020:   if (tie(%hash,'GDBM_File',
                   3021: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3022: 	  &GDBM_READER(),0640)) {
1.168     albertel 3023:     my $version=$hash{"version:$symb"};
                   3024:     $returnhash{'version'}=$version;
                   3025:     my $scope;
                   3026:     for ($scope=1;$scope<=$version;$scope++) {
                   3027:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3028:       my @keys=split(/:/,$vkeys);
                   3029:       my $key;
                   3030:       $returnhash{"$scope:keys"}=$vkeys;
                   3031:       foreach $key (@keys) {
1.591     albertel 3032: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3033: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3034:       }
                   3035:     }
1.168     albertel 3036:     if (!(untie(%hash))) {
                   3037:       return "error:$!";
                   3038:     }
                   3039:   } else {
                   3040:     return "error:$!";
                   3041:   }
                   3042:   return %returnhash;
1.167     albertel 3043: }
                   3044: 
1.9       www      3045: # ----------------------------------------------------------------------- Store
                   3046: 
                   3047: sub store {
1.124     www      3048:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3049:     my $home='';
                   3050: 
1.168     albertel 3051:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3052: 
1.213     www      3053:     $symb=&symbclean($symb);
1.122     albertel 3054:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3055: 
1.620     albertel 3056:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3057:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3058: 
                   3059:     &devalidate($symb,$stuname,$domain);
1.109     www      3060: 
                   3061:     $symb=escape($symb);
1.187     www      3062:     if (!$namespace) { 
1.620     albertel 3063:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3064:           return ''; 
                   3065:        } 
                   3066:     }
1.620     albertel 3067:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3068: 
                   3069:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3070:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3071: 
1.12      www      3072:     my $namevalue='';
1.800     albertel 3073:     foreach my $key (keys(%$storehash)) {
                   3074:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3075:     }
1.12      www      3076:     $namevalue=~s/\&$//;
1.187     www      3077:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3078:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3079: }
                   3080: 
1.47      www      3081: # -------------------------------------------------------------- Critical Store
                   3082: 
                   3083: sub cstore {
1.124     www      3084:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3085:     my $home='';
                   3086: 
1.168     albertel 3087:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3088: 
1.213     www      3089:     $symb=&symbclean($symb);
1.122     albertel 3090:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3091: 
1.620     albertel 3092:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3093:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3094: 
                   3095:     &devalidate($symb,$stuname,$domain);
1.109     www      3096: 
                   3097:     $symb=escape($symb);
1.187     www      3098:     if (!$namespace) { 
1.620     albertel 3099:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3100:           return ''; 
                   3101:        } 
                   3102:     }
1.620     albertel 3103:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3104: 
                   3105:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3106:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3107: 
1.47      www      3108:     my $namevalue='';
1.800     albertel 3109:     foreach my $key (keys(%$storehash)) {
                   3110:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3111:     }
1.47      www      3112:     $namevalue=~s/\&$//;
1.187     www      3113:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3114:     return critical
                   3115:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3116: }
                   3117: 
1.9       www      3118: # --------------------------------------------------------------------- Restore
                   3119: 
                   3120: sub restore {
1.124     www      3121:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3122:     my $home='';
                   3123: 
1.168     albertel 3124:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3125: 
1.122     albertel 3126:     if (!$symb) {
                   3127:       unless ($symb=escape(&symbread())) { return ''; }
                   3128:     } else {
1.213     www      3129:       $symb=&escape(&symbclean($symb));
1.122     albertel 3130:     }
1.188     www      3131:     if (!$namespace) { 
1.620     albertel 3132:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3133:           return ''; 
                   3134:        } 
                   3135:     }
1.620     albertel 3136:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3137:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3138:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3139:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3140: 
1.12      www      3141:     my %returnhash=();
1.800     albertel 3142:     foreach my $line (split(/\&/,$answer)) {
                   3143: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3144:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3145:     }
1.75      www      3146:     my $version;
                   3147:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3148:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3149:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3150:        }
1.75      www      3151:     }
1.13      www      3152:     return %returnhash;
1.34      www      3153: }
                   3154: 
                   3155: # ---------------------------------------------------------- Course Description
                   3156: 
                   3157: sub coursedescription {
1.731     albertel 3158:     my ($courseid,$args)=@_;
1.34      www      3159:     $courseid=~s/^\///;
1.49      www      3160:     $courseid=~s/\_/\//g;
1.34      www      3161:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3162:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3163:     my $normalid=$cdomain.'_'.$cnum;
                   3164:     # need to always cache even if we get errors otherwise we keep 
                   3165:     # trying and trying and trying to get the course description.
                   3166:     my %envhash=();
                   3167:     my %returnhash=();
1.731     albertel 3168:     
                   3169:     my $expiretime=600;
                   3170:     if ($env{'request.course.id'} eq $normalid) {
                   3171: 	$expiretime=120;
                   3172:     }
                   3173: 
                   3174:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3175:     if (!$args->{'freshen_cache'}
                   3176: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3177: 	foreach my $key (keys(%env)) {
                   3178: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3179: 	    my ($setting) = $1;
                   3180: 	    $returnhash{$setting} = $env{$key};
                   3181: 	}
                   3182: 	return %returnhash;
                   3183:     }
                   3184: 
                   3185:     # get the data agin
                   3186:     if (!$args->{'one_time'}) {
                   3187: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3188:     }
1.811     albertel 3189: 
1.34      www      3190:     if ($chome ne 'no_host') {
1.302     albertel 3191:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3192:        if (!exists($returnhash{'con_lost'})) {
                   3193:            $returnhash{'home'}= $chome;
                   3194: 	   $returnhash{'domain'} = $cdomain;
                   3195: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3196:            if (!defined($returnhash{'type'})) {
                   3197:                $returnhash{'type'} = 'Course';
                   3198:            }
1.130     albertel 3199:            while (my ($name,$value) = each %returnhash) {
1.53      www      3200:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3201:            }
1.270     www      3202:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3203:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3204: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3205:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3206:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3207:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3208:        }
                   3209:     }
1.731     albertel 3210:     if (!$args->{'one_time'}) {
                   3211: 	&appenv(%envhash);
                   3212:     }
1.302     albertel 3213:     return %returnhash;
1.461     www      3214: }
                   3215: 
                   3216: # -------------------------------------------------See if a user is privileged
                   3217: 
                   3218: sub privileged {
                   3219:     my ($username,$domain)=@_;
                   3220:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3221: 			&homeserver($username,$domain));
                   3222:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3223:     my $now=time;
                   3224:     if ($rolesdump ne '') {
1.800     albertel 3225:         foreach my $entry (split(/&/,$rolesdump)) {
                   3226: 	    if ($entry!~/^rolesdef_/) {
                   3227: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3228: 		$area=~s/\_\w\w$//;
                   3229: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3230: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3231: 		    my $active=1;
                   3232: 		    if ($tend) {
                   3233: 			if ($tend<$now) { $active=0; }
                   3234: 		    }
                   3235: 		    if ($tstart) {
                   3236: 			if ($tstart>$now) { $active=0; }
                   3237: 		    }
                   3238: 		    if ($active) { return 1; }
                   3239: 		}
                   3240: 	    }
                   3241: 	}
                   3242:     }
                   3243:     return 0;
1.9       www      3244: }
1.1       albertel 3245: 
1.103     harris41 3246: # -------------------------------------------------------- Get user privileges
1.11      www      3247: 
                   3248: sub rolesinit {
                   3249:     my ($domain,$username,$authhost)=@_;
                   3250:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3251:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3252:     my %allroles=();
1.678     raeburn  3253:     my %allgroups=();   
1.11      www      3254:     my $now=time;
1.743     albertel 3255:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3256:     my $group_privs;
1.11      www      3257: 
                   3258:     if ($rolesdump ne '') {
1.800     albertel 3259:         foreach my $entry (split(/&/,$rolesdump)) {
                   3260: 	  if ($entry!~/^rolesdef_/) {
                   3261:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3262: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3263:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3264: 	    if ($role=~/^cr/) { 
1.807     albertel 3265: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3266: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3267: 		    ($tend,$tstart)=split('_',$trest);
                   3268: 		} else {
                   3269: 		    $trole=$role;
                   3270: 		}
1.678     raeburn  3271:             } elsif ($role =~ m|^gr/|) {
                   3272:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3273:                 ($trole,$group_privs) = split(/\//,$trole);
                   3274:                 $group_privs = &unescape($group_privs);
1.587     albertel 3275: 	    } else {
                   3276: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3277: 	    }
1.743     albertel 3278: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3279: 					 $username);
                   3280: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3281:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3282:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3283:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3284: 		my $spec=$trole.'.'.$area;
                   3285: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3286: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3287:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3288:                 } elsif ($trole eq 'gr') {
                   3289:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3290: 		} else {
1.567     raeburn  3291:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3292: 		}
1.12      www      3293:             }
1.662     raeburn  3294:           }
1.191     harris41 3295:         }
1.743     albertel 3296:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3297:         $userroles{'user.adv'}    = $adv;
                   3298: 	$userroles{'user.author'} = $author;
1.620     albertel 3299:         $env{'user.adv'}=$adv;
1.11      www      3300:     }
1.743     albertel 3301:     return \%userroles;  
1.11      www      3302: }
                   3303: 
1.567     raeburn  3304: sub set_arearole {
                   3305:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3306: # log the associated role with the area
                   3307:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3308:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3309: }
                   3310: 
                   3311: sub custom_roleprivs {
                   3312:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3313:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3314:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3315:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3316:         my ($rdummy,$roledef)=
                   3317:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3318:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3319:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3320:             if (defined($syspriv)) {
                   3321:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3322:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3323:             }
                   3324:             if ($tdomain ne '') {
                   3325:                 if (defined($dompriv)) {
                   3326:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3327:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3328:                 }
                   3329:                 if (($trest ne '') && (defined($coursepriv))) {
                   3330:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3331:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3332:                 }
                   3333:             }
                   3334:         }
                   3335:     }
                   3336: }
                   3337: 
1.678     raeburn  3338: sub group_roleprivs {
                   3339:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3340:     my $access = 1;
                   3341:     my $now = time;
                   3342:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3343:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3344:     if ($access) {
1.811     albertel 3345:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3346:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3347:     }
                   3348: }
1.567     raeburn  3349: 
                   3350: sub standard_roleprivs {
                   3351:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3352:     if (defined($pr{$trole.':s'})) {
                   3353:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3354:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3355:     }
                   3356:     if ($tdomain ne '') {
                   3357:         if (defined($pr{$trole.':d'})) {
                   3358:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3359:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3360:         }
                   3361:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3362:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3363:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3364:         }
                   3365:     }
                   3366: }
                   3367: 
                   3368: sub set_userprivs {
1.678     raeburn  3369:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3370:     my $author=0;
                   3371:     my $adv=0;
1.678     raeburn  3372:     my %grouproles = ();
                   3373:     if (keys(%{$allgroups}) > 0) {
                   3374:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3375:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3376:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3377:                 $trole = $1;
                   3378:                 $area = $2;
1.681     raeburn  3379:                 $sec = $3;
                   3380:                 $extendedarea = $area.$sec;
                   3381:                 if (exists($$allgroups{$area})) {
                   3382:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3383:                         my $spec = $trole.'.'.$extendedarea;
                   3384:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3385:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3386:                     }
                   3387:                 }
                   3388:             }
                   3389:         }
                   3390:     }
1.800     albertel 3391:     foreach my $group (keys(%grouproles)) {
                   3392:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3393:     }
1.800     albertel 3394:     foreach my $role (keys(%{$allroles})) {
                   3395:         my %thesepriv;
                   3396:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3397:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3398:             if ($item ne '') {
                   3399:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3400:                 if ($restrictions eq '') {
                   3401:                     $thesepriv{$privilege}='F';
                   3402:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3403:                     $thesepriv{$privilege}.=$restrictions;
                   3404:                 }
                   3405:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3406:             }
                   3407:         }
                   3408:         my $thesestr='';
1.800     albertel 3409:         foreach my $priv (keys(%thesepriv)) {
                   3410: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3411: 	}
                   3412:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3413:     }
                   3414:     return ($author,$adv);
                   3415: }
                   3416: 
1.12      www      3417: # --------------------------------------------------------------- get interface
                   3418: 
                   3419: sub get {
1.131     albertel 3420:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3421:    my $items='';
1.800     albertel 3422:    foreach my $item (@$storearr) {
                   3423:        $items.=&escape($item).'&';
1.191     harris41 3424:    }
1.12      www      3425:    $items=~s/\&$//;
1.620     albertel 3426:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3427:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3428:    my $uhome=&homeserver($uname,$udomain);
                   3429: 
1.133     albertel 3430:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3431:    my @pairs=split(/\&/,$rep);
1.273     albertel 3432:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3433:      return @pairs;
                   3434:    }
1.15      www      3435:    my %returnhash=();
1.42      www      3436:    my $i=0;
1.800     albertel 3437:    foreach my $item (@$storearr) {
                   3438:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3439:       $i++;
1.191     harris41 3440:    }
1.15      www      3441:    return %returnhash;
1.27      www      3442: }
                   3443: 
                   3444: # --------------------------------------------------------------- del interface
                   3445: 
                   3446: sub del {
1.133     albertel 3447:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3448:    my $items='';
1.800     albertel 3449:    foreach my $item (@$storearr) {
                   3450:        $items.=&escape($item).'&';
1.191     harris41 3451:    }
1.27      www      3452:    $items=~s/\&$//;
1.620     albertel 3453:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3454:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3455:    my $uhome=&homeserver($uname,$udomain);
                   3456: 
                   3457:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3458: }
                   3459: 
                   3460: # -------------------------------------------------------------- dump interface
                   3461: 
                   3462: sub dump {
1.755     albertel 3463:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3464:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3465:     if (!$uname) { $uname=$env{'user.name'}; }
                   3466:     my $uhome=&homeserver($uname,$udomain);
                   3467:     if ($regexp) {
                   3468: 	$regexp=&escape($regexp);
                   3469:     } else {
                   3470: 	$regexp='.';
                   3471:     }
                   3472:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3473:     my @pairs=split(/\&/,$rep);
                   3474:     my %returnhash=();
                   3475:     foreach my $item (@pairs) {
                   3476: 	my ($key,$value)=split(/=/,$item,2);
                   3477: 	$key = &unescape($key);
                   3478: 	next if ($key =~ /^error: 2 /);
                   3479: 	$returnhash{$key}=&thaw_unescape($value);
                   3480:     }
                   3481:     return %returnhash;
1.407     www      3482: }
                   3483: 
1.717     albertel 3484: # --------------------------------------------------------- dumpstore interface
                   3485: 
                   3486: sub dumpstore {
                   3487:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3488:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3489:    if (!$uname) { $uname=$env{'user.name'}; }
                   3490:    my $uhome=&homeserver($uname,$udomain);
                   3491:    if ($regexp) {
                   3492:        $regexp=&escape($regexp);
                   3493:    } else {
                   3494:        $regexp='.';
                   3495:    }
                   3496:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3497:    my @pairs=split(/\&/,$rep);
                   3498:    my %returnhash=();
                   3499:    foreach my $item (@pairs) {
                   3500:        my ($key,$value)=split(/=/,$item,2);
                   3501:        next if ($key =~ /^error: 2 /);
                   3502:        $returnhash{$key}=&thaw_unescape($value);
                   3503:    }
                   3504:    return %returnhash;
1.717     albertel 3505: }
                   3506: 
1.407     www      3507: # -------------------------------------------------------------- keys interface
                   3508: 
                   3509: sub getkeys {
                   3510:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3511:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3512:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3513:    my $uhome=&homeserver($uname,$udomain);
                   3514:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3515:    my @keyarray=();
1.800     albertel 3516:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3517:       next if ($key =~ /^error: 2 /);
1.800     albertel 3518:       push(@keyarray,&unescape($key));
1.407     www      3519:    }
                   3520:    return @keyarray;
1.318     matthew  3521: }
                   3522: 
1.319     matthew  3523: # --------------------------------------------------------------- currentdump
                   3524: sub currentdump {
1.328     matthew  3525:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3526:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3527:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3528:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3529:    my $uhome = &homeserver($sname,$sdom);
                   3530:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3531:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3532:    #
1.318     matthew  3533:    my %returnhash=();
1.319     matthew  3534:    #
                   3535:    if ($rep eq "unknown_cmd") { 
                   3536:        # an old lond will not know currentdump
                   3537:        # Do a dump and make it look like a currentdump
1.822     albertel 3538:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3539:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3540:        my %hash = @tmp;
                   3541:        @tmp=();
1.424     matthew  3542:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3543:    } else {
                   3544:        my @pairs=split(/\&/,$rep);
1.800     albertel 3545:        foreach my $pair (@pairs) {
                   3546:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3547:            my ($symb,$param) = split(/:/,$key);
                   3548:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3549:                                                         &thaw_unescape($value);
1.319     matthew  3550:        }
1.191     harris41 3551:    }
1.12      www      3552:    return %returnhash;
1.424     matthew  3553: }
                   3554: 
                   3555: sub convert_dump_to_currentdump{
                   3556:     my %hash = %{shift()};
                   3557:     my %returnhash;
                   3558:     # Code ripped from lond, essentially.  The only difference
                   3559:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3560:     # we might run in to problems with parameter names =~ /^v\./
                   3561:     while (my ($key,$value) = each(%hash)) {
                   3562:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3563: 	$symb  = &unescape($symb);
                   3564: 	$param = &unescape($param);
1.424     matthew  3565:         next if ($v eq 'version' || $symb eq 'keys');
                   3566:         next if (exists($returnhash{$symb}) &&
                   3567:                  exists($returnhash{$symb}->{$param}) &&
                   3568:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3569:         $returnhash{$symb}->{$param}=$value;
                   3570:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3571:     }
                   3572:     #
                   3573:     # Remove all of the keys in the hashes which keep track of
                   3574:     # the version of the parameter.
                   3575:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3576:         # use a foreach because we are going to delete from the hash.
                   3577:         foreach my $key (keys(%$param_hash)) {
                   3578:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3579:         }
                   3580:     }
                   3581:     return \%returnhash;
1.12      www      3582: }
                   3583: 
1.627     albertel 3584: # ------------------------------------------------------ critical inc interface
                   3585: 
                   3586: sub cinc {
                   3587:     return &inc(@_,'critical');
                   3588: }
                   3589: 
1.449     matthew  3590: # --------------------------------------------------------------- inc interface
                   3591: 
                   3592: sub inc {
1.627     albertel 3593:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3594:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3595:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3596:     my $uhome=&homeserver($uname,$udomain);
                   3597:     my $items='';
                   3598:     if (! ref($store)) {
                   3599:         # got a single value, so use that instead
                   3600:         $items = &escape($store).'=&';
                   3601:     } elsif (ref($store) eq 'SCALAR') {
                   3602:         $items = &escape($$store).'=&';        
                   3603:     } elsif (ref($store) eq 'ARRAY') {
                   3604:         $items = join('=&',map {&escape($_);} @{$store});
                   3605:     } elsif (ref($store) eq 'HASH') {
                   3606:         while (my($key,$value) = each(%{$store})) {
                   3607:             $items.= &escape($key).'='.&escape($value).'&';
                   3608:         }
                   3609:     }
                   3610:     $items=~s/\&$//;
1.627     albertel 3611:     if ($critical) {
                   3612: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3613:     } else {
                   3614: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3615:     }
1.449     matthew  3616: }
                   3617: 
1.12      www      3618: # --------------------------------------------------------------- put interface
                   3619: 
                   3620: sub put {
1.134     albertel 3621:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3622:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3623:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3624:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3625:    my $items='';
1.800     albertel 3626:    foreach my $item (keys(%$storehash)) {
                   3627:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3628:    }
1.12      www      3629:    $items=~s/\&$//;
1.134     albertel 3630:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3631: }
                   3632: 
1.631     albertel 3633: # ------------------------------------------------------------ newput interface
                   3634: 
                   3635: sub newput {
                   3636:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3637:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3638:    if (!$uname) { $uname=$env{'user.name'}; }
                   3639:    my $uhome=&homeserver($uname,$udomain);
                   3640:    my $items='';
                   3641:    foreach my $key (keys(%$storehash)) {
                   3642:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3643:    }
                   3644:    $items=~s/\&$//;
                   3645:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3646: }
                   3647: 
                   3648: # ---------------------------------------------------------  putstore interface
                   3649: 
1.524     raeburn  3650: sub putstore {
1.715     albertel 3651:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3652:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3653:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3654:    my $uhome=&homeserver($uname,$udomain);
                   3655:    my $items='';
1.715     albertel 3656:    foreach my $key (keys(%$storehash)) {
                   3657:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3658:    }
1.715     albertel 3659:    $items=~s/\&$//;
1.716     albertel 3660:    my $esc_symb=&escape($symb);
                   3661:    my $esc_v=&escape($version);
1.715     albertel 3662:    my $reply =
1.716     albertel 3663:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3664: 	      $uhome);
                   3665:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3666:        # gfall back to way things use to be done
1.715     albertel 3667:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3668: 			    $uname);
1.524     raeburn  3669:    }
1.715     albertel 3670:    return $reply;
                   3671: }
                   3672: 
                   3673: sub old_putstore {
1.716     albertel 3674:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3675:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3676:     if (!$uname) { $uname=$env{'user.name'}; }
                   3677:     my $uhome=&homeserver($uname,$udomain);
                   3678:     my %newstorehash;
1.800     albertel 3679:     foreach my $item (keys(%$storehash)) {
                   3680: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3681: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3682:     }
                   3683:     my $items='';
                   3684:     my %allitems = ();
1.800     albertel 3685:     foreach my $item (keys(%newstorehash)) {
                   3686: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3687: 	    my $key = $1.':keys:'.$2;
                   3688: 	    $allitems{$key} .= $3.':';
                   3689: 	}
1.800     albertel 3690: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3691:     }
1.800     albertel 3692:     foreach my $item (keys(%allitems)) {
                   3693: 	$allitems{$item} =~ s/\:$//;
                   3694: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3695:     }
                   3696:     $items=~s/\&$//;
                   3697:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3698: }
                   3699: 
1.47      www      3700: # ------------------------------------------------------ critical put interface
                   3701: 
                   3702: sub cput {
1.134     albertel 3703:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3704:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3705:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3706:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3707:    my $items='';
1.800     albertel 3708:    foreach my $item (keys(%$storehash)) {
                   3709:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3710:    }
1.47      www      3711:    $items=~s/\&$//;
1.134     albertel 3712:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3713: }
                   3714: 
                   3715: # -------------------------------------------------------------- eget interface
                   3716: 
                   3717: sub eget {
1.133     albertel 3718:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3719:    my $items='';
1.800     albertel 3720:    foreach my $item (@$storearr) {
                   3721:        $items.=&escape($item).'&';
1.191     harris41 3722:    }
1.12      www      3723:    $items=~s/\&$//;
1.620     albertel 3724:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3725:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3726:    my $uhome=&homeserver($uname,$udomain);
                   3727:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3728:    my @pairs=split(/\&/,$rep);
                   3729:    my %returnhash=();
1.42      www      3730:    my $i=0;
1.800     albertel 3731:    foreach my $item (@$storearr) {
                   3732:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3733:       $i++;
1.191     harris41 3734:    }
1.12      www      3735:    return %returnhash;
                   3736: }
                   3737: 
1.667     albertel 3738: # ------------------------------------------------------------ tmpput interface
                   3739: sub tmpput {
1.802     raeburn  3740:     my ($storehash,$server,$context)=@_;
1.667     albertel 3741:     my $items='';
1.800     albertel 3742:     foreach my $item (keys(%$storehash)) {
                   3743: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3744:     }
                   3745:     $items=~s/\&$//;
1.802     raeburn  3746:     if (defined($context)) {
                   3747:         $items .= ':'.&escape($context);
                   3748:     }
1.667     albertel 3749:     return &reply("tmpput:$items",$server);
                   3750: }
                   3751: 
                   3752: # ------------------------------------------------------------ tmpget interface
                   3753: sub tmpget {
1.688     albertel 3754:     my ($token,$server)=@_;
                   3755:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3756:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3757:     my %returnhash;
                   3758:     foreach my $item (split(/\&/,$rep)) {
                   3759: 	my ($key,$value)=split(/=/,$item);
                   3760: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3761:     }
                   3762:     return %returnhash;
                   3763: }
                   3764: 
1.688     albertel 3765: # ------------------------------------------------------------ tmpget interface
                   3766: sub tmpdel {
                   3767:     my ($token,$server)=@_;
                   3768:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3769:     return &reply("tmpdel:$token",$server);
                   3770: }
                   3771: 
1.765     albertel 3772: # -------------------------------------------------- portfolio access checking
                   3773: 
                   3774: sub portfolio_access {
1.766     albertel 3775:     my ($requrl) = @_;
1.765     albertel 3776:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3777:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3778:     if ($result) {
                   3779:         my %setters;
                   3780:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3781:             my ($startblock,$endblock) =
                   3782:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3783:             if ($startblock && $endblock) {
                   3784:                 return 'B';
                   3785:             }
                   3786:         } else {
                   3787:             my ($startblock,$endblock) =
                   3788:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3789:             if ($startblock && $endblock) {
                   3790:                 return 'B';
                   3791:             }
                   3792:         }
                   3793:     }
1.765     albertel 3794:     if ($result eq 'ok') {
1.766     albertel 3795:        return 'F';
1.765     albertel 3796:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3797:        return 'A';
1.765     albertel 3798:     }
1.766     albertel 3799:     return '';
1.765     albertel 3800: }
                   3801: 
                   3802: sub get_portfolio_access {
1.767     albertel 3803:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3804: 
                   3805:     if (!ref($access_hash)) {
                   3806: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3807: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3808: 						   $file_name);
                   3809: 	$access_hash = $access_controls{$file_name};
                   3810:     }
                   3811: 
1.765     albertel 3812:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3813:     my $now = time;
                   3814:     if (ref($access_hash) eq 'HASH') {
                   3815:         foreach my $key (keys(%{$access_hash})) {
                   3816:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3817:             if ($start > $now) {
                   3818:                 next;
                   3819:             }
                   3820:             if ($end && $end<$now) {
                   3821:                 next;
                   3822:             }
                   3823:             if ($scope eq 'public') {
                   3824:                 $public = $key;
                   3825:                 last;
                   3826:             } elsif ($scope eq 'guest') {
                   3827:                 $guest = $key;
                   3828:             } elsif ($scope eq 'domains') {
                   3829:                 push(@domains,$key);
                   3830:             } elsif ($scope eq 'users') {
                   3831:                 push(@users,$key);
                   3832:             } elsif ($scope eq 'course') {
                   3833:                 push(@courses,$key);
                   3834:             } elsif ($scope eq 'group') {
                   3835:                 push(@groups,$key);
                   3836:             }
                   3837:         }
                   3838:         if ($public) {
                   3839:             return 'ok';
                   3840:         }
                   3841:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3842:             if ($guest) {
                   3843:                 return $guest;
                   3844:             }
                   3845:         } else {
                   3846:             if (@domains > 0) {
                   3847:                 foreach my $domkey (@domains) {
                   3848:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3849:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3850:                             return 'ok';
                   3851:                         }
                   3852:                     }
                   3853:                 }
                   3854:             }
                   3855:             if (@users > 0) {
                   3856:                 foreach my $userkey (@users) {
1.865     raeburn  3857:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3858:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3859:                             if (ref($item) eq 'HASH') {
                   3860:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3861:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3862:                                     return 'ok';
                   3863:                                 }
                   3864:                             }
                   3865:                         }
                   3866:                     } 
1.765     albertel 3867:                 }
                   3868:             }
                   3869:             my %roleshash;
                   3870:             my @courses_and_groups = @courses;
                   3871:             push(@courses_and_groups,@groups); 
                   3872:             if (@courses_and_groups > 0) {
                   3873:                 my (%allgroups,%allroles); 
                   3874:                 my ($start,$end,$role,$sec,$group);
                   3875:                 foreach my $envkey (%env) {
1.811     albertel 3876:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3877:                         my $cid = $2.'_'.$3; 
                   3878:                         if ($1 eq 'gr') {
                   3879:                             $group = $4;
                   3880:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3881:                         } else {
                   3882:                             if ($4 eq '') {
                   3883:                                 $sec = 'none';
                   3884:                             } else {
                   3885:                                 $sec = $4;
                   3886:                             }
                   3887:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3888:                         }
1.811     albertel 3889:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3890:                         my $cid = $2.'_'.$3;
                   3891:                         if ($4 eq '') {
                   3892:                             $sec = 'none';
                   3893:                         } else {
                   3894:                             $sec = $4;
                   3895:                         }
                   3896:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3897:                     }
                   3898:                 }
                   3899:                 if (keys(%allroles) == 0) {
                   3900:                     return;
                   3901:                 }
                   3902:                 foreach my $key (@courses_and_groups) {
                   3903:                     my %content = %{$$access_hash{$key}};
                   3904:                     my $cnum = $content{'number'};
                   3905:                     my $cdom = $content{'domain'};
                   3906:                     my $cid = $cdom.'_'.$cnum;
                   3907:                     if (!exists($allroles{$cid})) {
                   3908:                         next;
                   3909:                     }    
                   3910:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3911:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3912:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3913:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3914:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3915:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3916:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3917:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3918:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3919:                                         if (grep/^all$/,@sections) {
                   3920:                                             return 'ok';
                   3921:                                         } else {
                   3922:                                             if (grep/^$sec$/,@sections) {
                   3923:                                                 return 'ok';
                   3924:                                             }
                   3925:                                         }
                   3926:                                     }
                   3927:                                 }
                   3928:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3929:                                     if (grep/^none$/,@groups) {
                   3930:                                         return 'ok';
                   3931:                                     }
                   3932:                                 } else {
                   3933:                                     if (grep/^all$/,@groups) {
                   3934:                                         return 'ok';
                   3935:                                     } 
                   3936:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3937:                                         if (grep/^$group$/,@groups) {
                   3938:                                             return 'ok';
                   3939:                                         }
                   3940:                                     }
                   3941:                                 } 
                   3942:                             }
                   3943:                         }
                   3944:                     }
                   3945:                 }
                   3946:             }
                   3947:             if ($guest) {
                   3948:                 return $guest;
                   3949:             }
                   3950:         }
                   3951:     }
                   3952:     return;
                   3953: }
                   3954: 
                   3955: sub course_group_datechecker {
                   3956:     my ($dates,$now,$status) = @_;
                   3957:     my ($start,$end) = split(/\./,$dates);
                   3958:     if (!$start && !$end) {
                   3959:         return 'ok';
                   3960:     }
                   3961:     if (grep/^active$/,@{$status}) {
                   3962:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3963:             return 'ok';
                   3964:         }
                   3965:     }
                   3966:     if (grep/^previous$/,@{$status}) {
                   3967:         if ($end > $now ) {
                   3968:             return 'ok';
                   3969:         }
                   3970:     }
                   3971:     if (grep/^future$/,@{$status}) {
                   3972:         if ($start > $now) {
                   3973:             return 'ok';
                   3974:         }
                   3975:     }
                   3976:     return; 
                   3977: }
                   3978: 
                   3979: sub parse_portfolio_url {
                   3980:     my ($url) = @_;
                   3981: 
                   3982:     my ($type,$udom,$unum,$group,$file_name);
                   3983:     
1.823     albertel 3984:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3985: 	$type = 1;
                   3986:         $udom = $1;
                   3987:         $unum = $2;
                   3988:         $file_name = $3;
1.823     albertel 3989:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3990: 	$type = 2;
                   3991:         $udom = $1;
                   3992:         $unum = $2;
                   3993:         $group = $3;
                   3994:         $file_name = $3.'/'.$4;
                   3995:     }
                   3996:     if (wantarray) {
                   3997: 	return ($type,$udom,$unum,$file_name,$group);
                   3998:     }
                   3999:     return $type;
                   4000: }
                   4001: 
                   4002: sub is_portfolio_url {
                   4003:     my ($url) = @_;
                   4004:     return scalar(&parse_portfolio_url($url));
                   4005: }
                   4006: 
1.798     raeburn  4007: sub is_portfolio_file {
                   4008:     my ($file) = @_;
1.820     raeburn  4009:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4010:         return 1;
                   4011:     }
                   4012:     return;
                   4013: }
                   4014: 
                   4015: 
1.341     www      4016: # ---------------------------------------------- Custom access rule evaluation
                   4017: 
                   4018: sub customaccess {
                   4019:     my ($priv,$uri)=@_;
1.807     albertel 4020:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4021:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4022:     $udom = &LONCAPA::clean_domain($udom);
                   4023:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4024:     my $access=0;
1.800     albertel 4025:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4026: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4027: 	if ($type eq 'user') {
                   4028: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4029: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4030: 		if ($tdom) {
                   4031: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4032: 		}
1.896     albertel 4033: 		if ($tuname) {
                   4034: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4035: 		}
                   4036: 		$access=($effect eq 'allow');
                   4037: 		last;
                   4038: 	    }
                   4039: 	} else {
                   4040: 	    if ($role) {
                   4041: 		if ($role ne $urole) { next; }
                   4042: 	    }
                   4043: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4044: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4045: 		if ($tdom) {
                   4046: 		    if ($tdom ne $udom) { next; }
                   4047: 		}
                   4048: 		if ($tcrs) {
                   4049: 		    if ($tcrs ne $ucrs) { next; }
                   4050: 		}
                   4051: 		if ($tsec) {
                   4052: 		    if ($tsec ne $usec) { next; }
                   4053: 		}
                   4054: 		$access=($effect eq 'allow');
                   4055: 		last;
                   4056: 	    }
                   4057: 	    if ($realm eq '' && $role eq '') {
                   4058: 		$access=($effect eq 'allow');
                   4059: 	    }
1.402     bowersj2 4060: 	}
1.341     www      4061:     }
                   4062:     return $access;
                   4063: }
                   4064: 
1.103     harris41 4065: # ------------------------------------------------- Check for a user privilege
1.12      www      4066: 
                   4067: sub allowed {
1.810     raeburn  4068:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4069:     my $ver_orguri=$uri;
1.439     www      4070:     $uri=&deversion($uri);
1.152     www      4071:     my $orguri=$uri;
1.52      www      4072:     $uri=&declutter($uri);
1.809     raeburn  4073: 
1.810     raeburn  4074:     if ($priv eq 'evb') {
                   4075: # Evade communication block restrictions for specified role in a course
                   4076:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4077:             return $1;
                   4078:         } else {
                   4079:             return;
                   4080:         }
                   4081:     }
                   4082: 
1.620     albertel 4083:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4084: # Free bre access to adm and meta resources
1.775     albertel 4085:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4086: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4087: 	&& ($priv eq 'bre')) {
1.14      www      4088: 	return 'F';
1.159     www      4089:     }
                   4090: 
1.545     banghart 4091: # Free bre access to user's own portfolio contents
1.714     raeburn  4092:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4093:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4094: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4095:         my %setters;
                   4096:         my ($startblock,$endblock) = 
                   4097:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4098:         if ($startblock && $endblock) {
                   4099:             return 'B';
                   4100:         } else {
                   4101:             return 'F';
                   4102:         }
1.545     banghart 4103:     }
                   4104: 
1.762     raeburn  4105: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4106:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4107:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4108:         if (exists($env{'request.course.id'})) {
                   4109:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4110:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4111:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4112:                 my $courseprivid=$env{'request.course.id'};
                   4113:                 $courseprivid=~s/\_/\//;
                   4114:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4115:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4116:                     return $1; 
1.762     raeburn  4117:                 } else {
                   4118:                     if ($env{'request.course.sec'}) {
                   4119:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4120:                     }
                   4121:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4122:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4123:                         return $2;
                   4124:                     }
1.714     raeburn  4125:                 }
                   4126:             }
                   4127:         }
                   4128:     }
                   4129: 
1.159     www      4130: # Free bre to public access
                   4131: 
                   4132:     if ($priv eq 'bre') {
1.238     www      4133:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4134: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4135:            return 'F'; 
                   4136:         }
1.238     www      4137:         if ($copyright eq 'priv') {
                   4138:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4139: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4140: 		return '';
                   4141:             }
                   4142:         }
                   4143:         if ($copyright eq 'domain') {
                   4144:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4145: 	    unless (($env{'user.domain'} eq $1) ||
                   4146:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4147: 		return '';
                   4148:             }
1.262     matthew  4149:         }
1.620     albertel 4150:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4151:             # Library role, so allow browsing of resources in this domain.
                   4152:             return 'F';
1.238     www      4153:         }
1.341     www      4154:         if ($copyright eq 'custom') {
                   4155: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4156:         }
1.14      www      4157:     }
1.264     matthew  4158:     # Domain coordinator is trying to create a course
1.620     albertel 4159:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4160:         # uri is the requested domain in this case.
                   4161:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4162:         # a role of dc for the domain in question.
1.620     albertel 4163:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4164:     }
1.29      www      4165: 
1.52      www      4166:     my $thisallowed='';
                   4167:     my $statecond=0;
                   4168:     my $courseprivid='';
                   4169: 
                   4170: # Course
                   4171: 
1.620     albertel 4172:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4173:        $thisallowed.=$1;
                   4174:     }
1.29      www      4175: 
1.52      www      4176: # Domain
                   4177: 
1.620     albertel 4178:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4179:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4180:        $thisallowed.=$1;
                   4181:     }
1.52      www      4182: 
                   4183: # Course: uri itself is a course
1.66      www      4184:     my $courseuri=$uri;
                   4185:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4186:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4187: 
1.620     albertel 4188:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4189:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4190:        $thisallowed.=$1;
                   4191:     }
1.29      www      4192: 
1.665     albertel 4193: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4194: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4195:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4196: 	$thisallowed='';
1.671     raeburn  4197:         my ($match)=&is_on_map($uri);
                   4198:         if ($match) {
                   4199:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4200:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4201:                 $thisallowed.=$1;
                   4202:             }
                   4203:         } else {
1.705     albertel 4204:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4205:             if ($refuri) {
                   4206:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4207:                     $thisallowed='F';
1.671     raeburn  4208:                 } else {
                   4209:                     $refuri=&declutter($refuri);
                   4210:                     my ($match) = &is_on_map($refuri);
                   4211:                     if ($match) {
                   4212:                         $thisallowed='F';
                   4213:                     }
1.669     raeburn  4214:                 }
1.671     raeburn  4215:             }
                   4216:         }
1.314     www      4217:     }
1.492     albertel 4218: 
1.766     albertel 4219:     if ($priv eq 'bre'
                   4220: 	&& $thisallowed ne 'F' 
                   4221: 	&& $thisallowed ne '2'
                   4222: 	&& &is_portfolio_url($uri)) {
                   4223: 	$thisallowed = &portfolio_access($uri);
                   4224:     }
                   4225:     
1.52      www      4226: # Full access at system, domain or course-wide level? Exit.
1.29      www      4227: 
                   4228:     if ($thisallowed=~/F/) {
                   4229: 	return 'F';
                   4230:     }
                   4231: 
1.52      www      4232: # If this is generating or modifying users, exit with special codes
1.29      www      4233: 
1.643     www      4234:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4235: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4236: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4237: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4238: 	    unless ($auname) { return $thisallowed; }
                   4239: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4240: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4241: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4242: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4243: 	}
1.52      www      4244: 	return $thisallowed;
                   4245:     }
                   4246: #
1.103     harris41 4247: # Gathered so far: system, domain and course wide privileges
1.52      www      4248: #
                   4249: # Course: See if uri or referer is an individual resource that is part of 
                   4250: # the course
                   4251: 
1.620     albertel 4252:     if ($env{'request.course.id'}) {
1.232     www      4253: 
1.620     albertel 4254:        $courseprivid=$env{'request.course.id'};
                   4255:        if ($env{'request.course.sec'}) {
                   4256:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4257:        }
                   4258:        $courseprivid=~s/\_/\//;
                   4259:        my $checkreferer=1;
1.232     www      4260:        my ($match,$cond)=&is_on_map($uri);
                   4261:        if ($match) {
                   4262:            $statecond=$cond;
1.620     albertel 4263:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4264:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4265:                $thisallowed.=$1;
                   4266:                $checkreferer=0;
                   4267:            }
1.29      www      4268:        }
1.83      www      4269:        
1.148     www      4270:        if ($checkreferer) {
1.620     albertel 4271: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4272:             unless ($refuri) {
1.800     albertel 4273:                 foreach my $key (keys(%env)) {
                   4274: 		    if ($key=~/^httpref\..*\*/) {
                   4275: 			my $pattern=$key;
1.156     www      4276:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4277:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4278:                         $pattern=~s/\//\\\//g;
1.152     www      4279:                         if ($orguri=~/$pattern/) {
1.800     albertel 4280: 			    $refuri=$env{$key};
1.148     www      4281:                         }
                   4282:                     }
1.191     harris41 4283:                 }
1.148     www      4284:             }
1.232     www      4285: 
1.148     www      4286:          if ($refuri) { 
1.152     www      4287: 	  $refuri=&declutter($refuri);
1.232     www      4288:           my ($match,$cond)=&is_on_map($refuri);
                   4289:             if ($match) {
                   4290:               my $refstatecond=$cond;
1.620     albertel 4291:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4292:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4293:                   $thisallowed.=$1;
1.53      www      4294:                   $uri=$refuri;
                   4295:                   $statecond=$refstatecond;
1.52      www      4296:               }
                   4297:           }
1.148     www      4298:         }
1.29      www      4299:        }
1.52      www      4300:    }
1.29      www      4301: 
1.52      www      4302: #
1.103     harris41 4303: # Gathered now: all privileges that could apply, and condition number
1.52      www      4304: # 
                   4305: #
                   4306: # Full or no access?
                   4307: #
1.29      www      4308: 
1.52      www      4309:     if ($thisallowed=~/F/) {
                   4310: 	return 'F';
                   4311:     }
1.29      www      4312: 
1.52      www      4313:     unless ($thisallowed) {
                   4314:         return '';
                   4315:     }
1.29      www      4316: 
1.52      www      4317: # Restrictions exist, deal with them
                   4318: #
                   4319: #   C:according to course preferences
                   4320: #   R:according to resource settings
                   4321: #   L:unless locked
                   4322: #   X:according to user session state
                   4323: #
                   4324: 
                   4325: # Possibly locked functionality, check all courses
1.54      www      4326: # Locks might take effect only after 10 minutes cache expiration for other
                   4327: # courses, and 2 minutes for current course
1.52      www      4328: 
                   4329:     my $envkey;
                   4330:     if ($thisallowed=~/L/) {
1.620     albertel 4331:         foreach $envkey (keys %env) {
1.54      www      4332:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4333:                my $courseid=$2;
                   4334:                my $roleid=$1.'.'.$2;
1.92      www      4335:                $courseid=~s/^\///;
1.54      www      4336:                my $expiretime=600;
1.620     albertel 4337:                if ($env{'request.role'} eq $roleid) {
1.54      www      4338: 		  $expiretime=120;
                   4339:                }
                   4340: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4341:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4342:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4343: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4344:                }
1.620     albertel 4345:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4346:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4347: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4348:                        &log($env{'user.domain'},$env{'user.name'},
                   4349:                             $env{'user.home'},
1.57      www      4350:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4351:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4352:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4353: 		       return '';
                   4354:                    }
                   4355:                }
1.620     albertel 4356:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4357:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4358: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4359:                        &log($env{'user.domain'},$env{'user.name'},
                   4360:                             $env{'user.home'},
1.57      www      4361:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4362:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4363:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4364: 		       return '';
                   4365:                    }
                   4366:                }
                   4367: 	   }
1.29      www      4368:        }
1.52      www      4369:     }
                   4370:    
                   4371: #
                   4372: # Rest of the restrictions depend on selected course
                   4373: #
                   4374: 
1.620     albertel 4375:     unless ($env{'request.course.id'}) {
1.766     albertel 4376: 	if ($thisallowed eq 'A') {
                   4377: 	    return 'A';
1.814     raeburn  4378:         } elsif ($thisallowed eq 'B') {
                   4379:             return 'B';
1.766     albertel 4380: 	} else {
                   4381: 	    return '1';
                   4382: 	}
1.52      www      4383:     }
1.29      www      4384: 
1.52      www      4385: #
                   4386: # Now user is definitely in a course
                   4387: #
1.53      www      4388: 
                   4389: 
                   4390: # Course preferences
                   4391: 
                   4392:    if ($thisallowed=~/C/) {
1.620     albertel 4393:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4394:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4395:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4396: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4397: 	   if ($priv ne 'pch') { 
                   4398: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4399: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4400: 			$env{'request.course.id'});
                   4401: 	   }
1.237     www      4402:            return '';
                   4403:        }
                   4404: 
1.620     albertel 4405:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4406: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4407: 	   if ($priv ne 'pch') { 
                   4408: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4409: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4410: 			$env{'request.course.id'});
                   4411: 	   }
1.54      www      4412:            return '';
                   4413:        }
1.53      www      4414:    }
                   4415: 
                   4416: # Resource preferences
                   4417: 
                   4418:    if ($thisallowed=~/R/) {
1.620     albertel 4419:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4420:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4421: 	   if ($priv ne 'pch') { 
                   4422: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4423: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4424: 	   }
                   4425: 	   return '';
1.54      www      4426:        }
1.53      www      4427:    }
1.30      www      4428: 
1.246     www      4429: # Restricted by state or randomout?
1.30      www      4430: 
1.52      www      4431:    if ($thisallowed=~/X/) {
1.620     albertel 4432:       if ($env{'acc.randomout'}) {
1.579     albertel 4433: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4434:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4435:             return ''; 
                   4436:          }
1.247     www      4437:       }
                   4438:       if (&condval($statecond)) {
1.52      www      4439: 	 return '2';
                   4440:       } else {
                   4441:          return '';
                   4442:       }
                   4443:    }
1.30      www      4444: 
1.766     albertel 4445:     if ($thisallowed eq 'A') {
                   4446: 	return 'A';
1.814     raeburn  4447:     } elsif ($thisallowed eq 'B') {
                   4448:         return 'B';
1.766     albertel 4449:     }
1.52      www      4450:    return 'F';
1.232     www      4451: }
                   4452: 
1.710     albertel 4453: sub split_uri_for_cond {
                   4454:     my $uri=&deversion(&declutter(shift));
                   4455:     my @uriparts=split(/\//,$uri);
                   4456:     my $filename=pop(@uriparts);
                   4457:     my $pathname=join('/',@uriparts);
                   4458:     return ($pathname,$filename);
                   4459: }
1.232     www      4460: # --------------------------------------------------- Is a resource on the map?
                   4461: 
                   4462: sub is_on_map {
1.710     albertel 4463:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4464:     #Trying to find the conditional for the file
1.620     albertel 4465:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4466: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4467:     if ($match) {
1.289     bowersj2 4468: 	return (1,$1);
                   4469:     } else {
1.434     www      4470: 	return (0,0);
1.289     bowersj2 4471:     }
1.12      www      4472: }
                   4473: 
1.427     www      4474: # --------------------------------------------------------- Get symb from alias
                   4475: 
                   4476: sub get_symb_from_alias {
                   4477:     my $symb=shift;
                   4478:     my ($map,$resid,$url)=&decode_symb($symb);
                   4479: # Already is a symb
                   4480:     if ($url) { return $symb; }
                   4481: # Must be an alias
                   4482:     my $aliassymb='';
                   4483:     my %bighash;
1.620     albertel 4484:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4485:                             &GDBM_READER(),0640)) {
                   4486:         my $rid=$bighash{'mapalias_'.$symb};
                   4487: 	if ($rid) {
                   4488: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4489: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4490: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4491: 	}
                   4492:         untie %bighash;
                   4493:     }
                   4494:     return $aliassymb;
                   4495: }
                   4496: 
1.12      www      4497: # ----------------------------------------------------------------- Define Role
                   4498: 
                   4499: sub definerole {
                   4500:   if (allowed('mcr','/')) {
                   4501:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4502:     foreach my $role (split(':',$sysrole)) {
                   4503: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4504:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4505:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4506: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4507:                return "refused:s:$crole&$cqual"; 
                   4508:             }
                   4509:         }
1.191     harris41 4510:     }
1.800     albertel 4511:     foreach my $role (split(':',$domrole)) {
                   4512: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4513:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4514:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4515: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4516:                return "refused:d:$crole&$cqual"; 
                   4517:             }
                   4518:         }
1.191     harris41 4519:     }
1.800     albertel 4520:     foreach my $role (split(':',$courole)) {
                   4521: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4522:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4523:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4524: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4525:                return "refused:c:$crole&$cqual"; 
                   4526:             }
                   4527:         }
1.191     harris41 4528:     }
1.620     albertel 4529:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4530:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4531: 	        "rolesdef_$rolename=".
                   4532:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4533:     return reply($command,$env{'user.home'});
1.12      www      4534:   } else {
                   4535:     return 'refused';
                   4536:   }
1.105     harris41 4537: }
                   4538: 
                   4539: # ---------------- Make a metadata query against the network of library servers
                   4540: 
                   4541: sub metadata_query {
1.244     matthew  4542:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4543:     my %rhash;
1.845     albertel 4544:     my %libserv = &all_library();
1.244     matthew  4545:     my @server_list = (defined($server_array) ? @$server_array
                   4546:                                               : keys(%libserv) );
                   4547:     for my $server (@server_list) {
1.118     harris41 4548: 	unless ($custom or $customshow) {
                   4549: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4550: 	    $rhash{$server}=$reply;
                   4551: 	}
                   4552: 	else {
                   4553: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4554: 			     &escape($custom).':'.&escape($customshow),
                   4555: 			     $server);
                   4556: 	    $rhash{$server}=$reply;
                   4557: 	}
1.112     harris41 4558:     }
1.118     harris41 4559:     return \%rhash;
1.240     www      4560: }
                   4561: 
                   4562: # ----------------------------------------- Send log queries and wait for reply
                   4563: 
                   4564: sub log_query {
                   4565:     my ($uname,$udom,$query,%filters)=@_;
                   4566:     my $uhome=&homeserver($uname,$udom);
                   4567:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4568:     my $uhost=&hostname($uhome);
1.800     albertel 4569:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4570:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4571:                        $uhome);
1.479     albertel 4572:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4573:     return get_query_reply($queryid);
                   4574: }
                   4575: 
1.818     raeburn  4576: # -------------------------- Update MySQL table for portfolio file
                   4577: 
                   4578: sub update_portfolio_table {
1.821     raeburn  4579:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4580:     my $homeserver = &homeserver($uname,$udom);
                   4581:     my $queryid=
1.821     raeburn  4582:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4583:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4584:     my $reply = &get_query_reply($queryid);
                   4585:     return $reply;
                   4586: }
                   4587: 
1.899     raeburn  4588: # -------------------------- Update MySQL allusers table
                   4589: 
                   4590: sub update_allusers_table {
                   4591:     my ($uname,$udom,$names) = @_;
                   4592:     my $homeserver = &homeserver($uname,$udom);
                   4593:     my $queryid=
                   4594:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4595:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4596:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4597:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4598:                'generation='.&escape($names->{'generation'}).'%%'.
                   4599:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4600:                'id='.&escape($names->{'id'}),$homeserver);
                   4601:     my $reply = &get_query_reply($queryid);
                   4602:     return $reply;
                   4603: }
                   4604: 
1.508     raeburn  4605: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4606: 
                   4607: sub fetch_enrollment_query {
1.511     raeburn  4608:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4609:     my $homeserver;
1.547     raeburn  4610:     my $maxtries = 1;
1.508     raeburn  4611:     if ($context eq 'automated') {
                   4612:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4613:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4614:     } else {
                   4615:         $homeserver = &homeserver($cnum,$dom);
                   4616:     }
1.838     albertel 4617:     my $host=&hostname($homeserver);
1.506     raeburn  4618:     my $cmd = '';
1.800     albertel 4619:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4620:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4621:     }
                   4622:     $cmd =~ s/%%$//;
                   4623:     $cmd = &escape($cmd);
                   4624:     my $query = 'fetchenrollment';
1.620     albertel 4625:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4626:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4627:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4628:         return 'error: '.$queryid;
                   4629:     }
1.506     raeburn  4630:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4631:     my $tries = 1;
                   4632:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4633:         $reply = &get_query_reply($queryid);
                   4634:         $tries ++;
                   4635:     }
1.526     raeburn  4636:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4637:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4638:     } else {
1.901     albertel 4639:         my @responses = split(/:/,$reply);
1.515     raeburn  4640:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4641:             foreach my $line (@responses) {
                   4642:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4643:                 $$replyref{$key} = $value;
                   4644:             }
                   4645:         } else {
1.506     raeburn  4646:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4647:             foreach my $line (@responses) {
                   4648:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4649:                 $$replyref{$key} = $value;
                   4650:                 if ($value > 0) {
1.800     albertel 4651:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4652:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4653:                         my $destname = $pathname.'/'.$filename;
                   4654:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4655:                         if ($xml_classlist =~ /^error/) {
                   4656:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4657:                         } else {
1.506     raeburn  4658:                             if ( open(FILE,">$destname") ) {
                   4659:                                 print FILE &unescape($xml_classlist);
                   4660:                                 close(FILE);
1.526     raeburn  4661:                             } else {
                   4662:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4663:                             }
                   4664:                         }
                   4665:                     }
                   4666:                 }
                   4667:             }
                   4668:         }
                   4669:         return 'ok';
                   4670:     }
                   4671:     return 'error';
                   4672: }
                   4673: 
1.242     www      4674: sub get_query_reply {
                   4675:     my $queryid=shift;
1.240     www      4676:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4677:     my $reply='';
                   4678:     for (1..100) {
                   4679: 	sleep 2;
                   4680:         if (-e $replyfile.'.end') {
1.448     albertel 4681: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4682: 		$reply = join('',<$fh>);
                   4683: 		close($fh);
1.240     www      4684: 	   } else { return 'error: reply_file_error'; }
1.242     www      4685:            return &unescape($reply);
                   4686: 	}
1.240     www      4687:     }
1.242     www      4688:     return 'timeout:'.$queryid;
1.240     www      4689: }
                   4690: 
                   4691: sub courselog_query {
1.241     www      4692: #
                   4693: # possible filters:
                   4694: # url: url or symb
                   4695: # username
                   4696: # domain
                   4697: # action: view, submit, grade
                   4698: # start: timestamp
                   4699: # end: timestamp
                   4700: #
1.240     www      4701:     my (%filters)=@_;
1.620     albertel 4702:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4703:     if ($filters{'url'}) {
                   4704: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4705:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4706:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4707:     }
1.620     albertel 4708:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4709:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4710:     return &log_query($cname,$cdom,'courselog',%filters);
                   4711: }
                   4712: 
                   4713: sub userlog_query {
1.858     raeburn  4714: #
                   4715: # possible filters:
                   4716: # action: log check role
                   4717: # start: timestamp
                   4718: # end: timestamp
                   4719: #
1.240     www      4720:     my ($uname,$udom,%filters)=@_;
                   4721:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4722: }
                   4723: 
1.506     raeburn  4724: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4725: 
                   4726: sub auto_run {
1.508     raeburn  4727:     my ($cnum,$cdom) = @_;
1.876     raeburn  4728:     my $response = 0;
                   4729:     my $settings;
                   4730:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4731:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4732:         $settings = $domconfig{'autoenroll'};
                   4733:         if ($settings->{'run'} eq '1') {
                   4734:             $response = 1;
                   4735:         }
                   4736:     } else {
                   4737:         my $homeserver = &homeserver($cnum,$cdom);
                   4738:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4739:     }
1.506     raeburn  4740:     return $response;
                   4741: }
1.776     albertel 4742: 
1.506     raeburn  4743: sub auto_get_sections {
1.508     raeburn  4744:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4745:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4746:     my @secs = ();
1.511     raeburn  4747:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4748:     unless ($response eq 'refused') {
1.901     albertel 4749:         @secs = split(/:/,$response);
1.506     raeburn  4750:     }
                   4751:     return @secs;
                   4752: }
1.776     albertel 4753: 
1.506     raeburn  4754: sub auto_new_course {
1.508     raeburn  4755:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4756:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4757:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4758:     return $response;
                   4759: }
1.776     albertel 4760: 
1.506     raeburn  4761: sub auto_validate_courseID {
1.508     raeburn  4762:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4763:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4764:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4765:     return $response;
                   4766: }
1.776     albertel 4767: 
1.506     raeburn  4768: sub auto_create_password {
1.873     raeburn  4769:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4770:     my ($homeserver,$response);
1.506     raeburn  4771:     my $create_passwd = 0;
                   4772:     my $authchk = '';
1.873     raeburn  4773:     if ($udom =~ /^$match_domain$/) {
                   4774:         $homeserver = &domain($udom,'primary');
                   4775:     }
                   4776:     if ($homeserver eq '') {
                   4777:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4778:             $homeserver = &homeserver($cnum,$cdom);
                   4779:         }
                   4780:     }
                   4781:     if ($homeserver eq '') {
                   4782:         $authchk = 'nodomain';
1.506     raeburn  4783:     } else {
1.873     raeburn  4784:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4785:         if ($response eq 'refused') {
                   4786:             $authchk = 'refused';
                   4787:         } else {
1.901     albertel 4788:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4789:         }
1.506     raeburn  4790:     }
                   4791:     return ($authparam,$create_passwd,$authchk);
                   4792: }
                   4793: 
1.706     raeburn  4794: sub auto_photo_permission {
                   4795:     my ($cnum,$cdom,$students) = @_;
                   4796:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4797:     my ($outcome,$perm_reqd,$conditions) = 
                   4798: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4799:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4800: 	return (undef,undef);
                   4801:     }
1.706     raeburn  4802:     return ($outcome,$perm_reqd,$conditions);
                   4803: }
                   4804: 
                   4805: sub auto_checkphotos {
                   4806:     my ($uname,$udom,$pid) = @_;
                   4807:     my $homeserver = &homeserver($uname,$udom);
                   4808:     my ($result,$resulttype);
                   4809:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4810: 				   &escape($uname).':'.&escape($pid),
                   4811: 				   $homeserver));
1.709     albertel 4812:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4813: 	return (undef,undef);
                   4814:     }
1.706     raeburn  4815:     if ($outcome) {
                   4816:         ($result,$resulttype) = split(/:/,$outcome);
                   4817:     } 
                   4818:     return ($result,$resulttype);
                   4819: }
                   4820: 
                   4821: sub auto_photochoice {
                   4822:     my ($cnum,$cdom) = @_;
                   4823:     my $homeserver = &homeserver($cnum,$cdom);
                   4824:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4825: 						       &escape($cdom),
                   4826: 						       $homeserver)));
1.709     albertel 4827:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4828: 	return (undef,undef);
                   4829:     }
1.706     raeburn  4830:     return ($update,$comment);
                   4831: }
                   4832: 
                   4833: sub auto_photoupdate {
                   4834:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4835:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4836:     my $host=&hostname($homeserver);
1.706     raeburn  4837:     my $cmd = '';
                   4838:     my $maxtries = 1;
1.800     albertel 4839:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4840:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4841:     }
                   4842:     $cmd =~ s/%%$//;
                   4843:     $cmd = &escape($cmd);
                   4844:     my $query = 'institutionalphotos';
                   4845:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4846:     unless ($queryid=~/^\Q$host\E\_/) {
                   4847:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4848:         return 'error: '.$queryid;
                   4849:     }
                   4850:     my $reply = &get_query_reply($queryid);
                   4851:     my $tries = 1;
                   4852:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4853:         $reply = &get_query_reply($queryid);
                   4854:         $tries ++;
                   4855:     }
                   4856:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4857:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4858:     } else {
                   4859:         my @responses = split(/:/,$reply);
                   4860:         my $outcome = shift(@responses); 
                   4861:         foreach my $item (@responses) {
                   4862:             my ($key,$value) = split(/=/,$item);
                   4863:             $$photo{$key} = $value;
                   4864:         }
                   4865:         return $outcome;
                   4866:     }
                   4867:     return 'error';
                   4868: }
                   4869: 
1.521     raeburn  4870: sub auto_instcode_format {
1.793     albertel 4871:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4872: 	$cat_order) = @_;
1.521     raeburn  4873:     my $courses = '';
1.772     raeburn  4874:     my @homeservers;
1.521     raeburn  4875:     if ($caller eq 'global') {
1.841     albertel 4876: 	my %servers = &get_servers($codedom,'library');
                   4877: 	foreach my $tryserver (keys(%servers)) {
                   4878: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4879: 		push(@homeservers,$tryserver);
                   4880: 	    }
1.584     raeburn  4881:         }
1.521     raeburn  4882:     } else {
1.772     raeburn  4883:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4884:     }
1.793     albertel 4885:     foreach my $code (keys(%{$instcodes})) {
                   4886:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4887:     }
                   4888:     chop($courses);
1.772     raeburn  4889:     my $ok_response = 0;
                   4890:     my $response;
                   4891:     while (@homeservers > 0 && $ok_response == 0) {
                   4892:         my $server = shift(@homeservers); 
                   4893:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4894:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4895:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4896: 		split(/:/,$response);
1.772     raeburn  4897:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4898:             push(@{$codetitles},&str2array($codetitles_str));
                   4899:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4900:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4901:             $ok_response = 1;
                   4902:         }
                   4903:     }
                   4904:     if ($ok_response) {
1.521     raeburn  4905:         return 'ok';
1.772     raeburn  4906:     } else {
                   4907:         return $response;
1.521     raeburn  4908:     }
                   4909: }
                   4910: 
1.792     raeburn  4911: sub auto_instcode_defaults {
                   4912:     my ($domain,$returnhash,$code_order) = @_;
                   4913:     my @homeservers;
1.841     albertel 4914: 
                   4915:     my %servers = &get_servers($domain,'library');
                   4916:     foreach my $tryserver (keys(%servers)) {
                   4917: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4918: 	    push(@homeservers,$tryserver);
                   4919: 	}
1.792     raeburn  4920:     }
1.841     albertel 4921: 
1.792     raeburn  4922:     my $response;
1.841     albertel 4923:     foreach my $server (@homeservers) {
1.792     raeburn  4924:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4925:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4926: 	
                   4927: 	foreach my $pair (split(/\&/,$response)) {
                   4928: 	    my ($name,$value)=split(/\=/,$pair);
                   4929: 	    if ($name eq 'code_order') {
                   4930: 		@{$code_order} = split(/\&/,&unescape($value));
                   4931: 	    } else {
                   4932: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4933: 	    }
                   4934: 	}
                   4935: 	return 'ok';
1.792     raeburn  4936:     }
1.841     albertel 4937: 
                   4938:     return $response;
1.792     raeburn  4939: } 
                   4940: 
1.777     albertel 4941: sub auto_validate_class_sec {
1.773     raeburn  4942:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4943:     my $homeserver = &homeserver($cnum,$cdom);
                   4944:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4945:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4946:     return $response;
                   4947: }
                   4948: 
1.679     raeburn  4949: # ------------------------------------------------------- Course Group routines
                   4950: 
                   4951: sub get_coursegroups {
1.809     raeburn  4952:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4953:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4954: }
                   4955: 
1.679     raeburn  4956: sub modify_coursegroup {
                   4957:     my ($cdom,$cnum,$groupsettings) = @_;
                   4958:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4959: }
                   4960: 
1.809     raeburn  4961: sub toggle_coursegroup_status {
                   4962:     my ($cdom,$cnum,$group,$action) = @_;
                   4963:     my ($from_namespace,$to_namespace);
                   4964:     if ($action eq 'delete') {
                   4965:         $from_namespace = 'coursegroups';
                   4966:         $to_namespace = 'deleted_groups';
                   4967:     } else {
                   4968:         $from_namespace = 'deleted_groups';
                   4969:         $to_namespace = 'coursegroups';
                   4970:     }
                   4971:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4972:     if (my $tmp = &error(%curr_group)) {
                   4973:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4974:         return ('read error',$tmp);
                   4975:     } else {
                   4976:         my %savedsettings = %curr_group; 
1.809     raeburn  4977:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4978:         my $deloutcome;
                   4979:         if ($result eq 'ok') {
1.809     raeburn  4980:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4981:         } else {
                   4982:             return ('write error',$result);
                   4983:         }
                   4984:         if ($deloutcome eq 'ok') {
                   4985:             return 'ok';
                   4986:         } else {
                   4987:             return ('delete error',$deloutcome);
                   4988:         }
                   4989:     }
                   4990: }
                   4991: 
1.679     raeburn  4992: sub modify_group_roles {
                   4993:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4994:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4995:     my $role = 'gr/'.&escape($userprivs);
                   4996:     my ($uname,$udom) = split(/:/,$user);
                   4997:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4998:     if ($result eq 'ok') {
                   4999:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5000:     }
1.679     raeburn  5001:     return $result;
                   5002: }
                   5003: 
                   5004: sub modify_coursegroup_membership {
                   5005:     my ($cdom,$cnum,$membership) = @_;
                   5006:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5007:     return $result;
                   5008: }
                   5009: 
1.682     raeburn  5010: sub get_active_groups {
                   5011:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5012:     my $now = time;
                   5013:     my %groups = ();
                   5014:     foreach my $key (keys(%env)) {
1.811     albertel 5015:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5016:             my ($start,$end) = split(/\./,$env{$key});
                   5017:             if (($end!=0) && ($end<$now)) { next; }
                   5018:             if (($start!=0) && ($start>$now)) { next; }
                   5019:             if ($1 eq $cdom && $2 eq $cnum) {
                   5020:                 $groups{$3} = $env{$key} ;
                   5021:             }
                   5022:         }
                   5023:     }
                   5024:     return %groups;
                   5025: }
                   5026: 
1.683     raeburn  5027: sub get_group_membership {
                   5028:     my ($cdom,$cnum,$group) = @_;
                   5029:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5030: }
                   5031: 
                   5032: sub get_users_groups {
                   5033:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5034:     my @usersgroups;
1.683     raeburn  5035:     my $cachetime=1800;
                   5036: 
                   5037:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5038:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5039:     if (defined($cached)) {
1.734     albertel 5040:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5041:     } else {  
                   5042:         $grouplist = '';
1.816     raeburn  5043:         my $courseurl = &courseid_to_courseurl($courseid);
                   5044:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5045:         my $access_end = $env{'course.'.$courseid.
                   5046:                               '.default_enrollment_end_date'};
                   5047:         my $now = time;
                   5048:         foreach my $key (keys(%roleshash)) {
                   5049:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5050:                 my $group = $1;
                   5051:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5052:                     my $start = $2;
                   5053:                     my $end = $1;
                   5054:                     if ($start == -1) { next; } # deleted from group
                   5055:                     if (($start!=0) && ($start>$now)) { next; }
                   5056:                     if (($end!=0) && ($end<$now)) {
                   5057:                         if ($access_end && $access_end < $now) {
                   5058:                             if ($access_end - $end < 86400) {
                   5059:                                 push(@usersgroups,$group);
1.733     raeburn  5060:                             }
                   5061:                         }
1.817     raeburn  5062:                         next;
1.733     raeburn  5063:                     }
1.817     raeburn  5064:                     push(@usersgroups,$group);
1.683     raeburn  5065:                 }
                   5066:             }
                   5067:         }
1.817     raeburn  5068:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5069:         $grouplist = join(':',@usersgroups);
                   5070:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5071:     }
1.733     raeburn  5072:     return @usersgroups;
1.683     raeburn  5073: }
                   5074: 
                   5075: sub devalidate_getgroups_cache {
                   5076:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5077:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5078: 
1.683     raeburn  5079:     my $hashid="$udom:$uname:$courseid";
                   5080:     &devalidate_cache_new('getgroups',$hashid);
                   5081: }
                   5082: 
1.12      www      5083: # ------------------------------------------------------------------ Plain Text
                   5084: 
                   5085: sub plaintext {
1.742     raeburn  5086:     my ($short,$type,$cid) = @_;
1.758     albertel 5087:     if ($short =~ /^cr/) {
                   5088: 	return (split('/',$short))[-1];
                   5089:     }
1.742     raeburn  5090:     if (!defined($cid)) {
                   5091:         $cid = $env{'request.course.id'};
                   5092:     }
                   5093:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5094:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5095:                                           '.plaintext'});
                   5096:     }
                   5097:     my %rolenames = (
                   5098:                       Course => 'std',
                   5099:                       Group => 'alt1',
                   5100:                     );
                   5101:     if (defined($type) && 
                   5102:          defined($rolenames{$type}) && 
                   5103:          defined($prp{$short}{$rolenames{$type}})) {
                   5104:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5105:     } else {
                   5106:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5107:     }
1.12      www      5108: }
                   5109: 
                   5110: # ----------------------------------------------------------------- Assign Role
                   5111: 
                   5112: sub assignrole {
1.357     www      5113:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5114:     my $mrole;
                   5115:     if ($role =~ /^cr\//) {
1.393     www      5116:         my $cwosec=$url;
1.811     albertel 5117:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5118: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5119:            &logthis('Refused custom assignrole: '.
                   5120:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5121: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5122:            return 'refused'; 
                   5123:         }
1.21      www      5124:         $mrole='cr';
1.678     raeburn  5125:     } elsif ($role =~ /^gr\//) {
                   5126:         my $cwogrp=$url;
1.811     albertel 5127:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5128:         unless (&allowed('mdg',$cwogrp)) {
                   5129:             &logthis('Refused group assignrole: '.
                   5130:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5131:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5132:             return 'refused';
                   5133:         }
                   5134:         $mrole='gr';
1.21      www      5135:     } else {
1.82      www      5136:         my $cwosec=$url;
1.811     albertel 5137:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5138:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5139:            &logthis('Refused assignrole: '.
                   5140:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5141: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5142:            return 'refused'; 
                   5143:         }
1.21      www      5144:         $mrole=$role;
                   5145:     }
1.620     albertel 5146:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5147:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5148:     if ($end) { $command.='_'.$end; }
1.21      www      5149:     if ($start) {
                   5150: 	if ($end) { 
1.81      www      5151:            $command.='_'.$start; 
1.21      www      5152:         } else {
1.81      www      5153:            $command.='_0_'.$start;
1.21      www      5154:         }
                   5155:     }
1.739     raeburn  5156:     my $origstart = $start;
                   5157:     my $origend = $end;
1.357     www      5158: # actually delete
                   5159:     if ($deleteflag) {
1.373     www      5160: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5161: # modify command to delete the role
1.620     albertel 5162:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5163:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5164: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5165: # set start and finish to negative values for userrolelog
                   5166:            $start=-1;
                   5167:            $end=-1;
                   5168:         }
                   5169:     }
                   5170: # send command
1.349     www      5171:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5172: # log new user role if status is ok
1.349     www      5173:     if ($answer eq 'ok') {
1.663     raeburn  5174: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5175: # for course roles, perform group memberships changes triggered by role change.
                   5176:         unless ($role =~ /^gr/) {
                   5177:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5178:                                              $origstart);
                   5179:         }
1.349     www      5180:     }
                   5181:     return $answer;
1.169     harris41 5182: }
                   5183: 
                   5184: # -------------------------------------------------- Modify user authentication
1.197     www      5185: # Overrides without validation
                   5186: 
1.169     harris41 5187: sub modifyuserauth {
                   5188:     my ($udom,$uname,$umode,$upass)=@_;
                   5189:     my $uhome=&homeserver($uname,$udom);
1.197     www      5190:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5191:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5192:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5193:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5194:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5195: 		     &escape($upass),$uhome);
1.620     albertel 5196:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5197:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5198:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5199:     &log($udom,,$uname,$uhome,
1.620     albertel 5200:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5201:                                      $env{'user.name'}.', '.$umode.
1.197     www      5202:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5203:     unless ($reply eq 'ok') {
1.197     www      5204:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5205: 	return 'error: '.$reply;
                   5206:     }   
1.170     harris41 5207:     return 'ok';
1.80      www      5208: }
                   5209: 
1.81      www      5210: # --------------------------------------------------------------- Modify a user
1.80      www      5211: 
1.81      www      5212: sub modifyuser {
1.206     matthew  5213:     my ($udom,    $uname, $uid,
                   5214:         $umode,   $upass, $first,
                   5215:         $middle,  $last,  $gene,
1.387     www      5216:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5217:     $udom= &LONCAPA::clean_domain($udom);
                   5218:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5219:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5220:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5221: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5222:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5223:                                      ' desiredhome not specified'). 
1.620     albertel 5224:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5225:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5226:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5227: # ----------------------------------------------------------------- Create User
1.406     albertel 5228:     if (($uhome eq 'no_host') && 
                   5229: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5230:         my $unhome='';
1.844     albertel 5231:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5232:             $unhome = $desiredhome;
1.620     albertel 5233: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5234: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5235:         } else { # load balancing routine for determining $unhome
1.81      www      5236:             my $loadm=10000000;
1.841     albertel 5237: 	    my %servers = &get_servers($udom,'library');
                   5238: 	    foreach my $tryserver (keys(%servers)) {
                   5239: 		my $answer=reply('load',$tryserver);
                   5240: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5241: 		    $loadm=$answer;
                   5242: 		    $unhome=$tryserver;
                   5243: 		}
1.80      www      5244: 	    }
                   5245:         }
                   5246:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5247: 	    return 'error: unable to find a home server for '.$uname.
                   5248:                    ' in domain '.$udom;
1.80      www      5249:         }
                   5250:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5251:                          &escape($upass),$unhome);
                   5252: 	unless ($reply eq 'ok') {
                   5253:             return 'error: '.$reply;
                   5254:         }   
1.230     stredwic 5255:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5256:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5257: 	    return 'error: unable verify users home machine.';
1.80      www      5258:         }
1.209     matthew  5259:     }   # End of creation of new user
1.80      www      5260: # ---------------------------------------------------------------------- Add ID
                   5261:     if ($uid) {
                   5262:        $uid=~tr/A-Z/a-z/;
                   5263:        my %uidhash=&idrget($udom,$uname);
1.196     www      5264:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5265:          && (!$forceid)) {
1.80      www      5266: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5267: 	      return 'error: user id "'.$uid.'" does not match '.
                   5268:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5269:           }
                   5270:        } else {
                   5271: 	  &idput($udom,($uname => $uid));
                   5272:        }
                   5273:     }
                   5274: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5275:     my @tmp=&get('environment',
1.899     raeburn  5276: 		   ['firstname','middlename','lastname','generation','id',
                   5277:                     'permanentemail'],
1.134     albertel 5278: 		   $udom,$uname);
1.313     matthew  5279:     my %names;
                   5280:     if ($tmp[0] =~ m/^error:.*/) { 
                   5281:         %names=(); 
                   5282:     } else {
                   5283:         %names = @tmp;
                   5284:     }
1.388     www      5285: #
                   5286: # Make sure to not trash student environment if instructor does not bother
                   5287: # to supply name and email information
                   5288: #
                   5289:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5290:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5291:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5292:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5293:     if ($email) {
                   5294:        $email=~s/[^\w\@\.\-\,]//gs;
                   5295:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5296: 			   $names{'critnotification'} = $email;
                   5297: 			   $names{'permanentemail'} = $email; }
                   5298:     }
1.899     raeburn  5299:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5300:     my $reply = &put('environment', \%names, $udom,$uname);
                   5301:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5302:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5303:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5304:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5305:              $umode.', '.$first.', '.$middle.', '.
                   5306: 	     $last.', '.$gene.' by '.
1.620     albertel 5307:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5308:     return 'ok';
1.80      www      5309: }
                   5310: 
1.81      www      5311: # -------------------------------------------------------------- Modify student
1.80      www      5312: 
1.81      www      5313: sub modifystudent {
                   5314:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5315:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5316:     if (!$cid) {
1.620     albertel 5317: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5318: 	    return 'not_in_class';
                   5319: 	}
1.80      www      5320:     }
                   5321: # --------------------------------------------------------------- Make the user
1.81      www      5322:     my $reply=&modifyuser
1.209     matthew  5323: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5324:          $desiredhome,$email);
1.80      www      5325:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5326:     # This will cause &modify_student_enrollment to get the uid from the
                   5327:     # students environment
                   5328:     $uid = undef if (!$forceid);
1.455     albertel 5329:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5330: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5331:     return $reply;
                   5332: }
                   5333: 
                   5334: sub modify_student_enrollment {
1.515     raeburn  5335:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5336:     my ($cdom,$cnum,$chome);
                   5337:     if (!$cid) {
1.620     albertel 5338: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5339: 	    return 'not_in_class';
                   5340: 	}
1.620     albertel 5341: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5342: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5343:     } else {
                   5344: 	($cdom,$cnum)=split(/_/,$cid);
                   5345:     }
1.620     albertel 5346:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5347:     if (!$chome) {
1.457     raeburn  5348: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5349:     }
1.455     albertel 5350:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5351:     # Make sure the user exists
1.81      www      5352:     my $uhome=&homeserver($uname,$udom);
                   5353:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5354: 	return 'error: no such user';
                   5355:     }
1.297     matthew  5356:     # Get student data if we were not given enough information
                   5357:     if (!defined($first)  || $first  eq '' || 
                   5358:         !defined($last)   || $last   eq '' || 
                   5359:         !defined($uid)    || $uid    eq '' || 
                   5360:         !defined($middle) || $middle eq '' || 
                   5361:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5362:         # They did not supply us with enough data to enroll the student, so
                   5363:         # we need to pick up more information.
1.297     matthew  5364:         my %tmp = &get('environment',
1.294     matthew  5365:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5366:                        ,$udom,$uname);
                   5367: 
1.800     albertel 5368:         #foreach my $key (keys(%tmp)) {
                   5369:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5370:         #}
1.294     matthew  5371:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5372:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5373:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5374:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5375:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5376:     }
1.556     albertel 5377:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5378:     my $reply=cput('classlist',
                   5379: 		   {"$uname:$udom" => 
1.515     raeburn  5380: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5381: 		   $cdom,$cnum);
1.81      www      5382:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5383: 	return 'error: '.$reply;
1.652     albertel 5384:     } else {
                   5385: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5386:     }
1.297     matthew  5387:     # Add student role to user
1.83      www      5388:     my $uurl='/'.$cid;
1.81      www      5389:     $uurl=~s/\_/\//g;
                   5390:     if ($usec) {
                   5391: 	$uurl.='/'.$usec;
                   5392:     }
                   5393:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5394: }
                   5395: 
1.556     albertel 5396: sub format_name {
                   5397:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5398:     my $name;
                   5399:     if ($first ne 'lastname') {
                   5400: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5401:     } else {
                   5402: 	if ($lastname=~/\S/) {
                   5403: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5404: 	    $name=~s/\s+,/,/;
                   5405: 	} else {
                   5406: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5407: 	}
                   5408:     }
                   5409:     $name=~s/^\s+//;
                   5410:     $name=~s/\s+$//;
                   5411:     $name=~s/\s+/ /g;
                   5412:     return $name;
                   5413: }
                   5414: 
1.84      www      5415: # ------------------------------------------------- Write to course preferences
                   5416: 
                   5417: sub writecoursepref {
                   5418:     my ($courseid,%prefs)=@_;
                   5419:     $courseid=~s/^\///;
                   5420:     $courseid=~s/\_/\//g;
                   5421:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5422:     my $chome=homeserver($cnum,$cdomain);
                   5423:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5424: 	return 'error: no such course';
                   5425:     }
                   5426:     my $cstring='';
1.800     albertel 5427:     foreach my $pref (keys(%prefs)) {
                   5428: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5429:     }
1.84      www      5430:     $cstring=~s/\&$//;
                   5431:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5432: }
                   5433: 
                   5434: # ---------------------------------------------------------- Make/modify course
                   5435: 
                   5436: sub createcourse {
1.741     raeburn  5437:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5438:         $course_owner,$crstype)=@_;
1.84      www      5439:     $url=&declutter($url);
                   5440:     my $cid='';
1.264     matthew  5441:     unless (&allowed('ccc',$udom)) {
1.84      www      5442:         return 'refused';
                   5443:     }
                   5444: # ------------------------------------------------------------------- Create ID
1.674     www      5445:    my $uname=int(1+rand(9)).
                   5446:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5447:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5448:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5449: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5450:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5451:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5452:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5453:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5454:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5455:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5456:            return 'error: unable to generate unique course-ID';
                   5457:        } 
                   5458:    }
1.264     matthew  5459: # ------------------------------------------------ Check supplied server name
1.620     albertel 5460:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5461:     if (! &is_library($course_server)) {
1.264     matthew  5462:         return 'error:bad server name '.$course_server;
                   5463:     }
1.84      www      5464: # ------------------------------------------------------------- Make the course
                   5465:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5466:                       $course_server);
1.84      www      5467:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5468:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5469:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5470: 	return 'error: no such course';
                   5471:     }
1.271     www      5472: # ----------------------------------------------------------------- Course made
1.516     raeburn  5473: # log existence
                   5474:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5475:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5476:                   &escape($crstype),$uhome);
1.358     www      5477:     &flushcourselogs();
                   5478: # set toplevel url
1.271     www      5479:     my $topurl=$url;
                   5480:     unless ($nonstandard) {
                   5481: # ------------------------------------------ For standard courses, make top url
                   5482:         my $mapurl=&clutter($url);
1.278     www      5483:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5484:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5485: <map>
                   5486: <resource id="1" type="start"></resource>
                   5487: <resource id="2" src="$mapurl"></resource>
                   5488: <resource id="3" type="finish"></resource>
                   5489: <link index="1" from="1" to="2"></link>
                   5490: <link index="2" from="2" to="3"></link>
                   5491: </map>
                   5492: ENDINITMAP
                   5493:         $topurl=&declutter(
1.638     albertel 5494:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5495:                           );
                   5496:     }
                   5497: # ----------------------------------------------------------- Write preferences
1.84      www      5498:     &writecoursepref($udom.'_'.$uname,
                   5499:                      ('description' => $description,
1.271     www      5500:                       'url'         => $topurl));
1.84      www      5501:     return '/'.$udom.'/'.$uname;
                   5502: }
                   5503: 
1.813     albertel 5504: sub is_course {
                   5505:     my ($cdom,$cnum) = @_;
                   5506:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5507: 				undef,'.');
                   5508:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5509:         return 1;
                   5510:     }
                   5511:     return 0;
                   5512: }
                   5513: 
1.21      www      5514: # ---------------------------------------------------------- Assign Custom Role
                   5515: 
                   5516: sub assigncustomrole {
1.357     www      5517:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5518:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5519:                        $end,$start,$deleteflag);
1.21      www      5520: }
                   5521: 
                   5522: # ----------------------------------------------------------------- Revoke Role
                   5523: 
                   5524: sub revokerole {
1.357     www      5525:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5526:     my $now=time;
1.357     www      5527:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5528: }
                   5529: 
                   5530: # ---------------------------------------------------------- Revoke Custom Role
                   5531: 
                   5532: sub revokecustomrole {
1.357     www      5533:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5534:     my $now=time;
1.357     www      5535:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5536:            $deleteflag);
1.17      www      5537: }
                   5538: 
1.533     banghart 5539: # ------------------------------------------------------------ Disk usage
1.535     albertel 5540: sub diskusage {
1.533     banghart 5541:     my ($udom,$uname,$directoryRoot)=@_;
                   5542:     $directoryRoot =~ s/\/$//;
1.535     albertel 5543:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5544:     return $listing;
1.512     banghart 5545: }
                   5546: 
1.566     banghart 5547: sub is_locked {
                   5548:     my ($file_name, $domain, $user) = @_;
                   5549:     my @check;
                   5550:     my $is_locked;
                   5551:     push @check, $file_name;
1.613     albertel 5552:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5553: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5554:     my ($tmp)=keys(%locked);
                   5555:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5556:     
1.566     banghart 5557:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5558:         $is_locked = 'false';
                   5559:         foreach my $entry (@{$locked{$file_name}}) {
                   5560:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5561:                $is_locked = 'true';
                   5562:                last;
1.745     raeburn  5563:            }
                   5564:        }
1.566     banghart 5565:     } else {
                   5566:         $is_locked = 'false';
                   5567:     }
                   5568: }
                   5569: 
1.759     albertel 5570: sub declutter_portfile {
                   5571:     my ($file) = @_;
1.833     albertel 5572:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5573:     return $file;
                   5574: }
                   5575: 
1.559     banghart 5576: # ------------------------------------------------------------- Mark as Read Only
                   5577: 
                   5578: sub mark_as_readonly {
                   5579:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5580:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5581:     my ($tmp)=keys(%current_permissions);
                   5582:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5583:     foreach my $file (@{$files}) {
1.759     albertel 5584: 	$file = &declutter_portfile($file);
1.561     banghart 5585:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5586:     }
1.613     albertel 5587:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5588:     return;
                   5589: }
                   5590: 
1.572     banghart 5591: # ------------------------------------------------------------Save Selected Files
                   5592: 
                   5593: sub save_selected_files {
                   5594:     my ($user, $path, @files) = @_;
                   5595:     my $filename = $user."savedfiles";
1.573     banghart 5596:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5597:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5598:     foreach my $file (@files) {
1.620     albertel 5599:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5600:     }
                   5601:     foreach my $file (@other_files) {
1.574     banghart 5602:         print (OUT $file."\n");
1.572     banghart 5603:     }
1.574     banghart 5604:     close (OUT);
1.572     banghart 5605:     return 'ok';
                   5606: }
                   5607: 
1.574     banghart 5608: sub clear_selected_files {
                   5609:     my ($user) = @_;
                   5610:     my $filename = $user."savedfiles";
                   5611:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5612:     print (OUT undef);
                   5613:     close (OUT);
                   5614:     return ("ok");    
                   5615: }
                   5616: 
1.572     banghart 5617: sub files_in_path {
                   5618:     my ($user, $path) = @_;
                   5619:     my $filename = $user."savedfiles";
                   5620:     my %return_files;
1.574     banghart 5621:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5622:     while (my $line_in = <IN>) {
1.574     banghart 5623:         chomp ($line_in);
                   5624:         my @paths_and_file = split (m!/!, $line_in);
                   5625:         my $file_part = pop (@paths_and_file);
                   5626:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5627:         $path_part.='/';
                   5628:         my $path_and_file = $path_part.$file_part;
                   5629:         if ($path_part eq $path) {
                   5630:             $return_files{$file_part}= 'selected';
                   5631:         }
                   5632:     }
1.574     banghart 5633:     close (IN);
                   5634:     return (\%return_files);
1.572     banghart 5635: }
                   5636: 
                   5637: # called in portfolio select mode, to show files selected NOT in current directory
                   5638: sub files_not_in_path {
                   5639:     my ($user, $path) = @_;
                   5640:     my $filename = $user."savedfiles";
                   5641:     my @return_files;
                   5642:     my $path_part;
1.800     albertel 5643:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5644:     while (my $line = <IN>) {
1.572     banghart 5645:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5646:         my @paths_and_file = split(m|/|, $line);
                   5647:         my $file_part = pop(@paths_and_file);
                   5648:         chomp($file_part);
                   5649:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5650:         $path_part .= '/';
                   5651:         my $path_and_file = $path_part.$file_part;
                   5652:         if ($path_part ne $path) {
1.800     albertel 5653:             push(@return_files, ($path_and_file));
1.572     banghart 5654:         }
                   5655:     }
1.800     albertel 5656:     close(OUT);
1.574     banghart 5657:     return (@return_files);
1.572     banghart 5658: }
                   5659: 
1.745     raeburn  5660: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5661: 
1.745     raeburn  5662: sub get_portfile_permissions {
                   5663:     my ($domain,$user) = @_;
1.613     albertel 5664:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5665:     my ($tmp)=keys(%current_permissions);
                   5666:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5667:     return \%current_permissions;
                   5668: }
                   5669: 
                   5670: #---------------------------------------------Get portfolio file access controls
                   5671: 
1.749     raeburn  5672: sub get_access_controls {
1.745     raeburn  5673:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5674:     my %access;
                   5675:     my $real_file = $file;
                   5676:     $file =~ s/\.meta$//;
1.745     raeburn  5677:     if (defined($file)) {
1.749     raeburn  5678:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5679:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5680:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5681:             }
                   5682:         }
1.745     raeburn  5683:     } else {
1.749     raeburn  5684:         foreach my $key (keys(%{$current_permissions})) {
                   5685:             if ($key =~ /\0accesscontrol$/) {
                   5686:                 if (defined($group)) {
                   5687:                     if ($key !~ m-^\Q$group\E/-) {
                   5688:                         next;
                   5689:                     }
                   5690:                 }
                   5691:                 my ($fullpath) = split(/\0/,$key);
                   5692:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5693:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5694:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5695:                     }
                   5696:                 }
                   5697:             }
                   5698:         }
                   5699:     }
                   5700:     return %access;
                   5701: }
                   5702: 
                   5703: sub modify_access_controls {
                   5704:     my ($file_name,$changes,$domain,$user)=@_;
                   5705:     my ($outcome,$deloutcome);
                   5706:     my %store_permissions;
                   5707:     my %new_values;
                   5708:     my %new_control;
                   5709:     my %translation;
                   5710:     my @deletions = ();
                   5711:     my $now = time;
                   5712:     if (exists($$changes{'activate'})) {
                   5713:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5714:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5715:             my $numnew = scalar(@newitems);
                   5716:             for (my $i=0; $i<$numnew; $i++) {
                   5717:                 my $newkey = $newitems[$i];
                   5718:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5719:                 if ($newkey =~ /^\d+:/) { 
                   5720:                     $newkey =~ s/^(\d+)/$newid/;
                   5721:                     $translation{$1} = $newid;
                   5722:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5723:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5724:                     $translation{$1} = $newid;
                   5725:                 }
1.749     raeburn  5726:                 $new_values{$file_name."\0".$newkey} = 
                   5727:                                           $$changes{'activate'}{$newitems[$i]};
                   5728:                 $new_control{$newkey} = $now;
                   5729:             }
                   5730:         }
                   5731:     }
                   5732:     my %todelete;
                   5733:     my %changed_items;
                   5734:     foreach my $action ('delete','update') {
                   5735:         if (exists($$changes{$action})) {
                   5736:             if (ref($$changes{$action}) eq 'HASH') {
                   5737:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5738:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5739:                     if ($action eq 'delete') { 
                   5740:                         $todelete{$itemnum} = 1;
                   5741:                     } else {
                   5742:                         $changed_items{$itemnum} = $key;
                   5743:                     }
                   5744:                 }
1.745     raeburn  5745:             }
                   5746:         }
1.749     raeburn  5747:     }
                   5748:     # get lock on access controls for file.
                   5749:     my $lockhash = {
                   5750:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5751:                                                        ':'.$env{'user.domain'},
                   5752:                    }; 
                   5753:     my $tries = 0;
                   5754:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5755:    
                   5756:     while (($gotlock ne 'ok') && $tries <3) {
                   5757:         $tries ++;
                   5758:         sleep 1;
                   5759:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5760:     }
                   5761:     if ($gotlock eq 'ok') {
                   5762:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5763:         my ($tmp)=keys(%curr_permissions);
                   5764:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5765:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5766:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5767:             if (ref($curr_controls) eq 'HASH') {
                   5768:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5769:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5770:                     if (defined($todelete{$itemnum})) {
                   5771:                         push(@deletions,$file_name."\0".$control_item);
                   5772:                     } else {
                   5773:                         if (defined($changed_items{$itemnum})) {
                   5774:                             $new_control{$changed_items{$itemnum}} = $now;
                   5775:                             push(@deletions,$file_name."\0".$control_item);
                   5776:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5777:                         } else {
                   5778:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5779:                         }
                   5780:                     }
1.745     raeburn  5781:                 }
                   5782:             }
                   5783:         }
1.749     raeburn  5784:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5785:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5786:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5787:         #  remove lock
                   5788:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5789:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5790:         my ($file,$group);
                   5791:         if (&is_course($domain,$user)) {
                   5792:             ($group,$file) = split(/\//,$file_name,2);
                   5793:         } else {
                   5794:             $file = $file_name;
                   5795:         }
                   5796:         my $sqlresult =
                   5797:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5798:                                     $group);
1.749     raeburn  5799:     } else {
                   5800:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5801:     }
1.749     raeburn  5802:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5803: }
                   5804: 
1.827     raeburn  5805: sub make_public_indefinitely {
                   5806:     my ($requrl) = @_;
                   5807:     my $now = time;
                   5808:     my $action = 'activate';
                   5809:     my $aclnum = 0;
                   5810:     if (&is_portfolio_url($requrl)) {
                   5811:         my (undef,$udom,$unum,$file_name,$group) =
                   5812:             &parse_portfolio_url($requrl);
                   5813:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5814:         my %access_controls = &get_access_controls($current_perms,
                   5815:                                                    $group,$file_name);
                   5816:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5817:             my ($num,$scope,$end,$start) = 
                   5818:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5819:             if ($scope eq 'public') {
                   5820:                 if ($start <= $now && $end == 0) {
                   5821:                     $action = 'none';
                   5822:                 } else {
                   5823:                     $action = 'update';
                   5824:                     $aclnum = $num;
                   5825:                 }
                   5826:                 last;
                   5827:             }
                   5828:         }
                   5829:         if ($action eq 'none') {
                   5830:              return 'ok';
                   5831:         } else {
                   5832:             my %changes;
                   5833:             my $newend = 0;
                   5834:             my $newstart = $now;
                   5835:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5836:             $changes{$action}{$newkey} = {
                   5837:                 type => 'public',
                   5838:                 time => {
                   5839:                     start => $newstart,
                   5840:                     end   => $newend,
                   5841:                 },
                   5842:             };
                   5843:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5844:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5845:             return $outcome;
                   5846:         }
                   5847:     } else {
                   5848:         return 'invalid';
                   5849:     }
                   5850: }
                   5851: 
1.745     raeburn  5852: #------------------------------------------------------Get Marked as Read Only
                   5853: 
                   5854: sub get_marked_as_readonly {
                   5855:     my ($domain,$user,$what,$group) = @_;
                   5856:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5857:     my @readonly_files;
1.629     banghart 5858:     my $cmp1=$what;
                   5859:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5860:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5861:         if (defined($group)) {
                   5862:             if ($file_name !~ m-^\Q$group\E/-) {
                   5863:                 next;
                   5864:             }
                   5865:         }
1.561     banghart 5866:         if (ref($value) eq "ARRAY"){
                   5867:             foreach my $stored_what (@{$value}) {
1.629     banghart 5868:                 my $cmp2=$stored_what;
1.759     albertel 5869:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5870:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5871:                 }
1.629     banghart 5872:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5873:                     push(@readonly_files, $file_name);
1.745     raeburn  5874:                     last;
1.563     banghart 5875:                 } elsif (!defined($what)) {
                   5876:                     push(@readonly_files, $file_name);
1.745     raeburn  5877:                     last;
1.561     banghart 5878:                 }
                   5879:             }
1.745     raeburn  5880:         }
1.561     banghart 5881:     }
                   5882:     return @readonly_files;
                   5883: }
1.577     banghart 5884: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5885: 
1.577     banghart 5886: sub get_marked_as_readonly_hash {
1.745     raeburn  5887:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5888:     my %readonly_files;
1.745     raeburn  5889:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5890:         if (defined($group)) {
                   5891:             if ($file_name !~ m-^\Q$group\E/-) {
                   5892:                 next;
                   5893:             }
                   5894:         }
1.577     banghart 5895:         if (ref($value) eq "ARRAY"){
                   5896:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5897:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5898:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5899:                         if ($lock_descriptor eq 'graded') {
                   5900:                             $readonly_files{$file_name} = 'graded';
                   5901:                         } elsif ($lock_descriptor eq 'handback') {
                   5902:                             $readonly_files{$file_name} = 'handback';
                   5903:                         } else {
                   5904:                             if (!exists($readonly_files{$file_name})) {
                   5905:                                 $readonly_files{$file_name} = 'locked';
                   5906:                             }
                   5907:                         }
1.745     raeburn  5908:                     }
1.750     banghart 5909:                 } 
1.577     banghart 5910:             }
                   5911:         } 
                   5912:     }
                   5913:     return %readonly_files;
                   5914: }
1.559     banghart 5915: # ------------------------------------------------------------ Unmark as Read Only
                   5916: 
                   5917: sub unmark_as_readonly {
1.629     banghart 5918:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5919:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5920:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5921:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5922:     my $symb_crs = $what;
                   5923:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5924:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5925:     my ($tmp)=keys(%current_permissions);
                   5926:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5927:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5928:     foreach my $file (@readonly_files) {
1.759     albertel 5929: 	my $clean_file = &declutter_portfile($file);
                   5930: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5931: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5932:         my @new_locks;
                   5933:         my @del_keys;
                   5934:         if (ref($current_locks) eq "ARRAY"){
                   5935:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5936:                 my $compare=$locker;
1.749     raeburn  5937:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5938:                     $compare=join('',@{$locker});
1.746     raeburn  5939:                     if ($compare ne $symb_crs) {
                   5940:                         push(@new_locks, $locker);
                   5941:                     }
1.563     banghart 5942:                 }
                   5943:             }
1.650     albertel 5944:             if (scalar(@new_locks) > 0) {
1.563     banghart 5945:                 $current_permissions{$file} = \@new_locks;
                   5946:             } else {
                   5947:                 push(@del_keys, $file);
1.613     albertel 5948:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5949:                 delete($current_permissions{$file});
1.563     banghart 5950:             }
                   5951:         }
1.561     banghart 5952:     }
1.613     albertel 5953:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5954:     return;
                   5955: }
1.512     banghart 5956: 
1.17      www      5957: # ------------------------------------------------------------ Directory lister
                   5958: 
                   5959: sub dirlist {
1.253     stredwic 5960:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5961: 
1.18      www      5962:     $uri=~s/^\///;
                   5963:     $uri=~s/\/$//;
1.253     stredwic 5964:     my ($udom, $uname);
                   5965:     (undef,$udom,$uname)=split(/\//,$uri);
                   5966:     if(defined($userdomain)) {
                   5967:         $udom = $userdomain;
                   5968:     }
                   5969:     if(defined($username)) {
                   5970:         $uname = $username;
                   5971:     }
                   5972: 
                   5973:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5974:     if(defined($alternateDirectoryRoot)) {
                   5975:         $dirRoot = $alternateDirectoryRoot;
                   5976:         $dirRoot =~ s/\/$//;
1.751     banghart 5977:     }
1.253     stredwic 5978: 
                   5979:     if($udom) {
                   5980:         if($uname) {
1.800     albertel 5981:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5982: 				 &homeserver($uname,$udom));
1.605     matthew  5983:             my @listing_results;
                   5984:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5985:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5986: 				  &homeserver($uname,$udom));
1.605     matthew  5987:                 @listing_results = split(/:/,$listing);
                   5988:             } else {
                   5989:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5990:             }
                   5991:             return @listing_results;
1.253     stredwic 5992:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5993:             my %allusers;
1.841     albertel 5994: 	    my %servers = &get_servers($udom,'library');
                   5995: 	    foreach my $tryserver (keys(%servers)) {
                   5996: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5997: 				     $udom, $tryserver);
                   5998: 		my @listing_results;
                   5999: 		if ($listing eq 'unknown_cmd') {
                   6000: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6001: 				      $udom, $tryserver);
                   6002: 		    @listing_results = split(/:/,$listing);
                   6003: 		} else {
                   6004: 		    @listing_results =
                   6005: 			map { &unescape($_); } split(/:/,$listing);
                   6006: 		}
                   6007: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6008: 		    $listing_results[0] ne 'empty'       &&
                   6009: 		    $listing_results[0] ne 'con_lost') {
                   6010: 		    foreach my $line (@listing_results) {
                   6011: 			my ($entry) = split(/&/,$line,2);
                   6012: 			$allusers{$entry} = 1;
                   6013: 		    }
                   6014: 		}
1.253     stredwic 6015:             }
                   6016:             my $alluserstr='';
1.800     albertel 6017:             foreach my $user (sort(keys(%allusers))) {
                   6018:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6019:             }
                   6020:             $alluserstr=~s/:$//;
                   6021:             return split(/:/,$alluserstr);
                   6022:         } else {
1.800     albertel 6023:             return ('missing user name');
1.253     stredwic 6024:         }
                   6025:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6026:         my @all_domains = sort(&all_domains());
                   6027:          foreach my $domain (@all_domains) {
                   6028:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6029:          }
                   6030:          return @all_domains;
                   6031:      } else {
1.800     albertel 6032:         return ('missing domain');
1.275     stredwic 6033:     }
                   6034: }
                   6035: 
                   6036: # --------------------------------------------- GetFileTimestamp
                   6037: # This function utilizes dirlist and returns the date stamp for
                   6038: # when it was last modified.  It will also return an error of -1
                   6039: # if an error occurs
                   6040: 
1.410     matthew  6041: ##
                   6042: ## FIXME: This subroutine assumes its caller knows something about the
                   6043: ## directory structure of the home server for the student ($root).
                   6044: ## Not a good assumption to make.  Since this is for looking up files
                   6045: ## in user directories, the full path should be constructed by lond, not
                   6046: ## whatever machine we request data from.
                   6047: ##
1.275     stredwic 6048: sub GetFileTimestamp {
                   6049:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6050:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6051:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6052:     my $subdir=$studentName.'__';
                   6053:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6054:     my $proname="$studentDomain/$subdir/$studentName";
                   6055:     $proname .= '/'.$filename;
1.375     matthew  6056:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6057:                                               $studentName, $root);
1.275     stredwic 6058:     my @stats = split('&', $fileStat);
                   6059:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6060:         # @stats contains first the filename, then the stat output
                   6061:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6062:     } else {
                   6063:         return -1;
1.253     stredwic 6064:     }
1.26      www      6065: }
                   6066: 
1.712     albertel 6067: sub stat_file {
                   6068:     my ($uri) = @_;
1.787     albertel 6069:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6070: 
1.712     albertel 6071:     my ($udom,$uname,$file,$dir);
                   6072:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6073: 	($udom,$uname,$file) =
1.811     albertel 6074: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6075: 	$file = 'userfiles/'.$file;
1.740     www      6076: 	$dir = &propath($udom,$uname);
1.712     albertel 6077:     }
                   6078:     if ($uri =~ m-^/res/-) {
                   6079: 	($udom,$uname) = 
1.807     albertel 6080: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6081: 	$file = $uri;
                   6082:     }
                   6083: 
                   6084:     if (!$udom || !$uname || !$file) {
                   6085: 	# unable to handle the uri
                   6086: 	return ();
                   6087:     }
                   6088: 
                   6089:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6090:     my @stats = split('&', $result);
1.721     banghart 6091:     
1.712     albertel 6092:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6093: 	shift(@stats); #filename is first
                   6094: 	return @stats;
                   6095:     }
                   6096:     return ();
                   6097: }
                   6098: 
1.26      www      6099: # -------------------------------------------------------- Value of a Condition
                   6100: 
1.713     albertel 6101: # gets the value of a specific preevaluated condition
                   6102: #    stored in the string  $env{user.state.<cid>}
                   6103: # or looks up a condition reference in the bighash and if if hasn't
                   6104: # already been evaluated recurses into docondval to get the value of
                   6105: # the condition, then memoizing it to 
                   6106: #   $env{user.state.<cid>.<condition>}
1.40      www      6107: sub directcondval {
                   6108:     my $number=shift;
1.620     albertel 6109:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6110: 	&Apache::lonuserstate::evalstate();
                   6111:     }
1.713     albertel 6112:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6113: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6114:     } elsif ($number =~ /^_/) {
                   6115: 	my $sub_condition;
                   6116: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6117: 		&GDBM_READER(),0640)) {
                   6118: 	    $sub_condition=$bighash{'conditions'.$number};
                   6119: 	    untie(%bighash);
                   6120: 	}
                   6121: 	my $value = &docondval($sub_condition);
                   6122: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6123: 	return $value;
                   6124:     }
1.620     albertel 6125:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6126:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6127:     } else {
                   6128:        return 2;
                   6129:     }
                   6130: }
                   6131: 
1.713     albertel 6132: # get the collection of conditions for this resource
1.26      www      6133: sub condval {
                   6134:     my $condidx=shift;
1.54      www      6135:     my $allpathcond='';
1.713     albertel 6136:     foreach my $cond (split(/\|/,$condidx)) {
                   6137: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6138: 	    $allpathcond.=
                   6139: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6140: 	}
1.191     harris41 6141:     }
1.54      www      6142:     $allpathcond=~s/\|$//;
1.713     albertel 6143:     return &docondval($allpathcond);
                   6144: }
                   6145: 
                   6146: #evaluates an expression of conditions
                   6147: sub docondval {
                   6148:     my ($allpathcond) = @_;
                   6149:     my $result=0;
                   6150:     if ($env{'request.course.id'}
                   6151: 	&& defined($allpathcond)) {
                   6152: 	my $operand='|';
                   6153: 	my @stack;
                   6154: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6155: 	    if ($chunk eq '(') {
                   6156: 		push @stack,($operand,$result);
                   6157: 	    } elsif ($chunk eq ')') {
                   6158: 		my $before=pop @stack;
                   6159: 		if (pop @stack eq '&') {
                   6160: 		    $result=$result>$before?$before:$result;
                   6161: 		} else {
                   6162: 		    $result=$result>$before?$result:$before;
                   6163: 		}
                   6164: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6165: 		$operand=$chunk;
                   6166: 	    } else {
                   6167: 		my $new=directcondval($chunk);
                   6168: 		if ($operand eq '&') {
                   6169: 		    $result=$result>$new?$new:$result;
                   6170: 		} else {
                   6171: 		    $result=$result>$new?$result:$new;
                   6172: 		}
                   6173: 	    }
                   6174: 	}
1.26      www      6175:     }
                   6176:     return $result;
1.421     albertel 6177: }
                   6178: 
                   6179: # ---------------------------------------------------- Devalidate courseresdata
                   6180: 
                   6181: sub devalidatecourseresdata {
                   6182:     my ($coursenum,$coursedomain)=@_;
                   6183:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6184:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6185: }
                   6186: 
1.763     www      6187: 
1.200     www      6188: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6189: #
                   6190: #  Parameters:
                   6191: #      $coursenum    - Number of the course.
                   6192: #      $coursedomain - Domain at which the course was created.
                   6193: #  Returns:
                   6194: #     A hash of the course parameters along (I think) with timestamps
                   6195: #     and version info.
1.877     foxr     6196: 
1.624     albertel 6197: sub get_courseresdata {
                   6198:     my ($coursenum,$coursedomain)=@_;
1.200     www      6199:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6200:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6201:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6202:     my %dumpreply;
1.417     albertel 6203:     unless (defined($cached)) {
1.624     albertel 6204: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6205: 	$result=\%dumpreply;
1.251     albertel 6206: 	my ($tmp) = keys(%dumpreply);
                   6207: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6208: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6209: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6210: 	    return $tmp;
1.416     albertel 6211: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6212: 	    $result=undef;
1.599     albertel 6213: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6214: 	}
                   6215:     }
1.624     albertel 6216:     return $result;
                   6217: }
                   6218: 
1.633     albertel 6219: sub devalidateuserresdata {
                   6220:     my ($uname,$udom)=@_;
                   6221:     my $hashid="$udom:$uname";
                   6222:     &devalidate_cache_new('userres',$hashid);
                   6223: }
                   6224: 
1.624     albertel 6225: sub get_userresdata {
                   6226:     my ($uname,$udom)=@_;
                   6227:     #most student don\'t have any data set, check if there is some data
                   6228:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6229: 
                   6230:     my $hashid="$udom:$uname";
                   6231:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6232:     if (!defined($cached)) {
                   6233: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6234: 	$result=\%resourcedata;
                   6235: 	&do_cache_new('userres',$hashid,$result,600);
                   6236:     }
                   6237:     my ($tmp)=keys(%$result);
                   6238:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6239: 	return $result;
                   6240:     }
                   6241:     #error 2 occurs when the .db doesn't exist
                   6242:     if ($tmp!~/error: 2 /) {
1.672     albertel 6243: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6244: 		 " Trying to get resource data for ".
                   6245: 		 $uname." at ".$udom.": ".
                   6246: 		 $tmp."</font>");
                   6247:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6248: 	#&EXT_cache_set($udom,$uname);
                   6249: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6250: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6251:     }
                   6252:     return $tmp;
                   6253: }
1.879     foxr     6254: #----------------------------------------------- resdata - return resource data
                   6255: #  Purpose:
                   6256: #    Return resource data for either users or for a course.
                   6257: #  Parameters:
                   6258: #     $name      - Course/user name.
                   6259: #     $domain    - Name of the domain the user/course is registered on.
                   6260: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6261: #     @which     - Array of names of resources desired.
                   6262: #  Returns:
                   6263: #     The value of the first reasource in @which that is found in the
                   6264: #     resource hash.
                   6265: #  Exceptional Conditions:
                   6266: #     If the $type passed in is not valid (not the string 'course' or 
                   6267: #     'user', an undefined  reference is returned.
                   6268: #     If none of the resources are found, an undef is returned
1.624     albertel 6269: sub resdata {
                   6270:     my ($name,$domain,$type,@which)=@_;
                   6271:     my $result;
                   6272:     if ($type eq 'course') {
                   6273: 	$result=&get_courseresdata($name,$domain);
                   6274:     } elsif ($type eq 'user') {
                   6275: 	$result=&get_userresdata($name,$domain);
                   6276:     }
                   6277:     if (!ref($result)) { return $result; }    
1.251     albertel 6278:     foreach my $item (@which) {
1.417     albertel 6279: 	if (defined($result->{$item})) {
                   6280: 	    return $result->{$item};
1.251     albertel 6281: 	}
1.250     albertel 6282:     }
1.291     albertel 6283:     return undef;
1.200     www      6284: }
                   6285: 
1.379     matthew  6286: #
                   6287: # EXT resource caching routines
                   6288: #
                   6289: 
                   6290: sub clear_EXT_cache_status {
1.383     albertel 6291:     &delenv('cache.EXT.');
1.379     matthew  6292: }
                   6293: 
                   6294: sub EXT_cache_status {
                   6295:     my ($target_domain,$target_user) = @_;
1.383     albertel 6296:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6297:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6298:         # We know already the user has no data
                   6299:         return 1;
                   6300:     } else {
                   6301:         return 0;
                   6302:     }
                   6303: }
                   6304: 
                   6305: sub EXT_cache_set {
                   6306:     my ($target_domain,$target_user) = @_;
1.383     albertel 6307:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6308:     #&appenv($cachename => time);
1.379     matthew  6309: }
                   6310: 
1.28      www      6311: # --------------------------------------------------------- Value of a Variable
1.58      www      6312: sub EXT {
1.715     albertel 6313: 
1.395     albertel 6314:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6315:     unless ($varname) { return ''; }
1.218     albertel 6316:     #get real user name/domain, courseid and symb
                   6317:     my $courseid;
1.359     albertel 6318:     my $publicuser;
1.427     www      6319:     if ($symbparm) {
                   6320: 	$symbparm=&get_symb_from_alias($symbparm);
                   6321:     }
1.218     albertel 6322:     if (!($uname && $udom)) {
1.790     albertel 6323:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6324:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6325:     } else {
1.620     albertel 6326: 	$courseid=$env{'request.course.id'};
1.218     albertel 6327:     }
1.48      www      6328:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6329:     my $rest;
1.320     albertel 6330:     if (defined($therest[0])) {
1.48      www      6331:        $rest=join('.',@therest);
                   6332:     } else {
                   6333:        $rest='';
                   6334:     }
1.320     albertel 6335: 
1.57      www      6336:     my $qualifierrest=$qualifier;
                   6337:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6338:     my $spacequalifierrest=$space;
                   6339:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6340:     if ($realm eq 'user') {
1.48      www      6341: # --------------------------------------------------------------- user.resource
                   6342: 	if ($space eq 'resource') {
1.651     albertel 6343: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6344: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6345: 		 &&
1.744     albertel 6346: 		 ($symbparm eq &symbread()) ) {	
                   6347: 		# if we are in the middle of processing the resource the
                   6348: 		# get the value we are planning on committing
                   6349:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6350:                     return $Apache::lonhomework::results{$qualifierrest};
                   6351:                 } else {
                   6352:                     return $Apache::lonhomework::history{$qualifierrest};
                   6353:                 }
1.335     albertel 6354: 	    } else {
1.359     albertel 6355: 		my %restored;
1.620     albertel 6356: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6357: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6358: 		} else {
                   6359: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6360: 		}
1.335     albertel 6361: 		return $restored{$qualifierrest};
                   6362: 	    }
1.48      www      6363: # ----------------------------------------------------------------- user.access
                   6364:         } elsif ($space eq 'access') {
1.218     albertel 6365: 	    # FIXME - not supporting calls for a specific user
1.48      www      6366:             return &allowed($qualifier,$rest);
                   6367: # ------------------------------------------ user.preferences, user.environment
                   6368:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6369: 	    if (($uname eq $env{'user.name'}) &&
                   6370: 		($udom eq $env{'user.domain'})) {
                   6371: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6372: 	    } else {
1.359     albertel 6373: 		my %returnhash;
                   6374: 		if (!$publicuser) {
                   6375: 		    %returnhash=&userenvironment($udom,$uname,
                   6376: 						 $qualifierrest);
                   6377: 		}
1.218     albertel 6378: 		return $returnhash{$qualifierrest};
                   6379: 	    }
1.48      www      6380: # ----------------------------------------------------------------- user.course
                   6381:         } elsif ($space eq 'course') {
1.218     albertel 6382: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6383:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6384: # ------------------------------------------------------------------- user.role
                   6385:         } elsif ($space eq 'role') {
1.218     albertel 6386: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6387:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6388:             if ($qualifier eq 'value') {
                   6389: 		return $role;
                   6390:             } elsif ($qualifier eq 'extent') {
                   6391:                 return $where;
                   6392:             }
                   6393: # ----------------------------------------------------------------- user.domain
                   6394:         } elsif ($space eq 'domain') {
1.218     albertel 6395:             return $udom;
1.48      www      6396: # ------------------------------------------------------------------- user.name
                   6397:         } elsif ($space eq 'name') {
1.218     albertel 6398:             return $uname;
1.48      www      6399: # ---------------------------------------------------- Any other user namespace
1.29      www      6400:         } else {
1.359     albertel 6401: 	    my %reply;
                   6402: 	    if (!$publicuser) {
                   6403: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6404: 	    }
                   6405: 	    return $reply{$qualifierrest};
1.48      www      6406:         }
1.236     www      6407:     } elsif ($realm eq 'query') {
                   6408: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6409:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6410: 						[$spacequalifierrest]);
1.620     albertel 6411: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6412:    } elsif ($realm eq 'request') {
1.48      www      6413: # ------------------------------------------------------------- request.browser
                   6414:         if ($space eq 'browser') {
1.430     www      6415: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6416: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6417: 		    return 1;
                   6418: 		} else {
                   6419: 		    return 0;
                   6420: 		}
                   6421: 	    } else {
1.620     albertel 6422: 		return $env{'browser.'.$qualifier};
1.430     www      6423: 	    }
1.57      www      6424: # ------------------------------------------------------------ request.filename
                   6425:         } else {
1.620     albertel 6426:             return $env{'request.'.$spacequalifierrest};
1.29      www      6427:         }
1.28      www      6428:     } elsif ($realm eq 'course') {
1.48      www      6429: # ---------------------------------------------------------- course.description
1.620     albertel 6430:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6431:     } elsif ($realm eq 'resource') {
1.165     www      6432: 
1.620     albertel 6433: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6434: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6435: 	}
1.693     albertel 6436: 
                   6437: 	if ($space eq 'title') {
                   6438: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6439: 	    return &gettitle($symbparm);
                   6440: 	}
                   6441: 	
                   6442: 	if ($space eq 'map') {
                   6443: 	    my ($map) = &decode_symb($symbparm);
                   6444: 	    return &symbread($map);
                   6445: 	}
1.905     albertel 6446: 	if ($space eq 'filename') {
                   6447: 	    if ($symbparm) {
                   6448: 		return &clutter((&decode_symb($symbparm))[2]);
                   6449: 	    }
                   6450: 	    return &hreflocation('',$env{'request.filename'});
                   6451: 	}
1.693     albertel 6452: 
                   6453: 	my ($section, $group, @groups);
1.593     albertel 6454: 	my ($courselevelm,$courselevel);
1.539     albertel 6455: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6456: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6457: 
1.218     albertel 6458: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6459: 
1.60      www      6460: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6461: 	    my $symbp=$symbparm;
1.735     albertel 6462: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6463: 
                   6464: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6465: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6466: 
1.620     albertel 6467: 	    if (($env{'user.name'} eq $uname) &&
                   6468: 		($env{'user.domain'} eq $udom)) {
                   6469: 		$section=$env{'request.course.sec'};
1.733     raeburn  6470:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6471:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6472: 	    } else {
1.539     albertel 6473: 		if (! defined($usection)) {
1.551     albertel 6474: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6475: 		} else {
                   6476: 		    $section = $usection;
                   6477: 		}
1.733     raeburn  6478:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6479: 	    }
                   6480: 
                   6481: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6482: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6483: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6484: 
1.593     albertel 6485: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6486: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6487: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6488: 
1.60      www      6489: # ----------------------------------------------------------- first, check user
1.624     albertel 6490: 
                   6491: 	    my $userreply=&resdata($uname,$udom,'user',
                   6492: 				       ($courselevelr,$courselevelm,
                   6493: 					$courselevel));
                   6494: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6495: 
1.594     albertel 6496: # ------------------------------------------------ second, check some of course
1.684     raeburn  6497:             my $coursereply;
1.691     raeburn  6498:             if (@groups > 0) {
                   6499:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6500:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6501:                 if (defined($coursereply)) { return $coursereply; }
                   6502:             }
1.96      www      6503: 
1.684     raeburn  6504: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6505: 				     $env{'course.'.$courseid.'.domain'},
                   6506: 				     'course',
                   6507: 				     ($seclevelr,$seclevelm,$seclevel,
                   6508: 				      $courselevelr));
1.287     albertel 6509: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6510: 
1.60      www      6511: # ------------------------------------------------------ third, check map parms
1.218     albertel 6512: 	    my %parmhash=();
                   6513: 	    my $thisparm='';
                   6514: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6515: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6516: 		    &GDBM_READER(),0640)) {
1.218     albertel 6517: 		$thisparm=$parmhash{$symbparm};
                   6518: 		untie(%parmhash);
                   6519: 	    }
                   6520: 	    if ($thisparm) { return $thisparm; }
                   6521: 	}
1.594     albertel 6522: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6523: 
1.218     albertel 6524: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6525: 	my $filename;
                   6526: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6527: 	if ($symbparm) {
1.409     www      6528: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6529: 	} else {
1.620     albertel 6530: 	    $filename=$env{'request.filename'};
1.282     albertel 6531: 	}
                   6532: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6533: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6534: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6535: 	if (defined($metadata)) { return $metadata; }
1.142     www      6536: 
1.594     albertel 6537: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6538: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6539: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6540: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6541: 				     $env{'course.'.$courseid.'.domain'},
                   6542: 				     'course',
                   6543: 				     ($courselevelm,$courselevel));
1.593     albertel 6544: 	    if (defined($coursereply)) { return $coursereply; }
                   6545: 	}
1.145     www      6546: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6547: 	unless ($space eq '0') {
1.336     albertel 6548: 	    my @parts=split(/_/,$space);
                   6549: 	    my $id=pop(@parts);
                   6550: 	    my $part=join('_',@parts);
                   6551: 	    if ($part eq '') { $part='0'; }
                   6552: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6553: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6554: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6555: 	}
1.395     albertel 6556: 	if ($recurse) { return undef; }
                   6557: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6558: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6559: 
1.48      www      6560: # ---------------------------------------------------- Any other user namespace
                   6561:     } elsif ($realm eq 'environment') {
                   6562: # ----------------------------------------------------------------- environment
1.620     albertel 6563: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6564: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6565: 	} else {
1.770     albertel 6566: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6567: 		return '';
                   6568: 	    }
1.219     albertel 6569: 	    my %returnhash=&userenvironment($udom,$uname,
                   6570: 					    $spacequalifierrest);
                   6571: 	    return $returnhash{$spacequalifierrest};
                   6572: 	}
1.28      www      6573:     } elsif ($realm eq 'system') {
1.48      www      6574: # ----------------------------------------------------------------- system.time
                   6575: 	if ($space eq 'time') {
                   6576: 	    return time;
                   6577:         }
1.696     albertel 6578:     } elsif ($realm eq 'server') {
                   6579: # ----------------------------------------------------------------- system.time
                   6580: 	if ($space eq 'name') {
                   6581: 	    return $ENV{'SERVER_NAME'};
                   6582:         }
1.28      www      6583:     }
1.48      www      6584:     return '';
1.61      www      6585: }
                   6586: 
1.691     raeburn  6587: sub check_group_parms {
                   6588:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6589:     my @groupitems = ();
                   6590:     my $resultitem;
                   6591:     my @levels = ($symbparm,$mapparm,$what);
                   6592:     foreach my $group (@{$groups}) {
                   6593:         foreach my $level (@levels) {
                   6594:              my $item = $courseid.'.['.$group.'].'.$level;
                   6595:              push(@groupitems,$item);
                   6596:         }
                   6597:     }
                   6598:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6599:                             $env{'course.'.$courseid.'.domain'},
                   6600:                                      'course',@groupitems);
                   6601:     return $coursereply;
                   6602: }
                   6603: 
                   6604: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6605:     my ($courseid,@groups) = @_;
                   6606:     @groups = sort(@groups);
1.691     raeburn  6607:     return @groups;
                   6608: }
                   6609: 
1.395     albertel 6610: sub packages_tab_default {
                   6611:     my ($uri,$varname)=@_;
                   6612:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6613: 
                   6614:     my (@extension,@specifics,$do_default);
                   6615:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6616: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6617: 	if ($pack_type eq 'default') {
                   6618: 	    $do_default=1;
                   6619: 	} elsif ($pack_type eq 'extension') {
                   6620: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6621: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6622: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6623: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6624: 	}
                   6625:     }
                   6626:     # first look for a package that matches the requested part id
                   6627:     foreach my $package (@specifics) {
                   6628: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6629: 	next if ($pack_part ne $part);
                   6630: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6631: 	    return $packagetab{"$pack_type&$name&default"};
                   6632: 	}
                   6633:     }
                   6634:     # look for any possible matching non extension_ package
                   6635:     foreach my $package (@specifics) {
                   6636: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6637: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6638: 	    return $packagetab{"$pack_type&$name&default"};
                   6639: 	}
1.585     albertel 6640: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6641: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6642: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6643: 	}
                   6644:     }
1.738     albertel 6645:     # look for any posible extension_ match
                   6646:     foreach my $package (@extension) {
                   6647: 	my ($package,$pack_type)=@{$package};
                   6648: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6649: 	    return $packagetab{"$pack_type&$name&default"};
                   6650: 	}
                   6651: 	if (defined($packagetab{$package."&$name&default"})) {
                   6652: 	    return $packagetab{$package."&$name&default"};
                   6653: 	}
                   6654:     }
                   6655:     # look for a global default setting
                   6656:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6657: 	return $packagetab{"default&$name&default"};
                   6658:     }
1.395     albertel 6659:     return undef;
                   6660: }
                   6661: 
1.334     albertel 6662: sub add_prefix_and_part {
                   6663:     my ($prefix,$part)=@_;
                   6664:     my $keyroot;
                   6665:     if (defined($prefix) && $prefix !~ /^__/) {
                   6666: 	# prefix that has a part already
                   6667: 	$keyroot=$prefix;
                   6668:     } elsif (defined($prefix)) {
                   6669: 	# prefix that is missing a part
                   6670: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6671:     } else {
                   6672: 	# no prefix at all
                   6673: 	if (defined($part)) { $keyroot='_'.$part; }
                   6674:     }
                   6675:     return $keyroot;
                   6676: }
                   6677: 
1.71      www      6678: # ---------------------------------------------------------------- Get metadata
                   6679: 
1.599     albertel 6680: my %metaentry;
1.71      www      6681: sub metadata {
1.176     www      6682:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6683:     $uri=&declutter($uri);
1.288     albertel 6684:     # if it is a non metadata possible uri return quickly
1.529     albertel 6685:     if (($uri eq '') || 
                   6686: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6687: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6688:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6689: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6690: 	return undef;
1.288     albertel 6691:     }
1.73      www      6692:     my $filename=$uri;
                   6693:     $uri=~s/\.meta$//;
1.172     www      6694: #
                   6695: # Is the metadata already cached?
1.177     www      6696: # Look at timestamp of caching
1.172     www      6697: # Everything is cached by the main uri, libraries are never directly cached
                   6698: #
1.428     albertel 6699:     if (!defined($liburi)) {
1.599     albertel 6700: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6701: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6702:     }
                   6703:     {
1.172     www      6704: #
                   6705: # Is this a recursive call for a library?
                   6706: #
1.599     albertel 6707: #	if (! exists($metacache{$uri})) {
                   6708: #	    $metacache{$uri}={};
                   6709: #	}
1.171     www      6710:         if ($liburi) {
                   6711: 	    $liburi=&declutter($liburi);
                   6712:             $filename=$liburi;
1.401     bowersj2 6713:         } else {
1.599     albertel 6714: 	    &devalidate_cache_new('meta',$uri);
                   6715: 	    undef(%metaentry);
1.401     bowersj2 6716: 	}
1.140     www      6717:         my %metathesekeys=();
1.73      www      6718:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6719: 	my $metastring;
1.768     albertel 6720: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6721: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6722: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6723: 	    $metastring=&getfile($file);
1.489     albertel 6724: 	}
1.208     albertel 6725:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6726:         my $token;
1.140     www      6727:         undef %metathesekeys;
1.71      www      6728:         while ($token=$parser->get_token) {
1.339     albertel 6729: 	    if ($token->[0] eq 'S') {
                   6730: 		if (defined($token->[2]->{'package'})) {
1.172     www      6731: #
                   6732: # This is a package - get package info
                   6733: #
1.339     albertel 6734: 		    my $package=$token->[2]->{'package'};
                   6735: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6736: 		    if (defined($token->[2]->{'id'})) { 
                   6737: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6738: 		    }
1.599     albertel 6739: 		    if ($metaentry{':packages'}) {
                   6740: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6741: 		    } else {
1.599     albertel 6742: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6743: 		    }
1.736     albertel 6744: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6745: 			my $part=$keyroot;
                   6746: 			$part=~s/^\_//;
1.736     albertel 6747: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6748: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6749: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6750: 			    # ignore package.tab specified default values
                   6751:                             # here &package_tab_default() will fetch those
                   6752: 			    if ($subp eq 'default') { next; }
1.736     albertel 6753: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6754: 			    my $unikey;
                   6755: 			    if ($pack =~ /_0$/) {
                   6756: 				$unikey='parameter_0_'.$name;
                   6757: 				$part=0;
                   6758: 			    } else {
                   6759: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6760: 			    }
1.339     albertel 6761: 			    if ($subp eq 'display') {
                   6762: 				$value.=' [Part: '.$part.']';
                   6763: 			    }
1.599     albertel 6764: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6765: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6766: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6767: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6768: 			    }
1.599     albertel 6769: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6770: 				$metaentry{':'.$unikey}=
                   6771: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6772: 			    }
1.339     albertel 6773: 			}
                   6774: 		    }
                   6775: 		} else {
1.172     www      6776: #
                   6777: # This is not a package - some other kind of start tag
1.339     albertel 6778: #
                   6779: 		    my $entry=$token->[1];
                   6780: 		    my $unikey;
                   6781: 		    if ($entry eq 'import') {
                   6782: 			$unikey='';
                   6783: 		    } else {
                   6784: 			$unikey=$entry;
                   6785: 		    }
                   6786: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6787: 
                   6788: 		    if (defined($token->[2]->{'id'})) { 
                   6789: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6790: 		    }
1.175     www      6791: 
1.339     albertel 6792: 		    if ($entry eq 'import') {
1.175     www      6793: #
                   6794: # Importing a library here
1.339     albertel 6795: #
                   6796: 			if ($depthcount<20) {
                   6797: 			    my $location=$parser->get_text('/import');
                   6798: 			    my $dir=$filename;
                   6799: 			    $dir=~s|[^/]*$||;
                   6800: 			    $location=&filelocation($dir,$location);
1.736     albertel 6801: 			    my $metadata = 
                   6802: 				&metadata($uri,'keys', $location,$unikey,
                   6803: 					  $depthcount+1);
                   6804: 			    foreach my $meta (split(',',$metadata)) {
                   6805: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6806: 				$metathesekeys{$meta}=1;
1.339     albertel 6807: 			    }
                   6808: 			}
                   6809: 		    } else { 
                   6810: 			
                   6811: 			if (defined($token->[2]->{'name'})) { 
                   6812: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6813: 			}
                   6814: 			$metathesekeys{$unikey}=1;
1.736     albertel 6815: 			foreach my $param (@{$token->[3]}) {
                   6816: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6817: 				$token->[2]->{$param};
1.339     albertel 6818: 			}
                   6819: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6820: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6821: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6822: 		 # only ws inside the tag, and not in default, so use default
                   6823: 		 # as value
1.599     albertel 6824: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6825: 			} elsif ( $internaltext =~ /\S/ ) {
                   6826: 		  # something interesting inside the tag
                   6827: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6828: 			} else {
1.908     albertel 6829: 		  # no interesting values, don't set a default
1.339     albertel 6830: 			}
1.172     www      6831: # end of not-a-package not-a-library import
1.339     albertel 6832: 		    }
1.172     www      6833: # end of not-a-package start tag
1.339     albertel 6834: 		}
1.172     www      6835: # the next is the end of "start tag"
1.339     albertel 6836: 	    }
                   6837: 	}
1.483     albertel 6838: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6839: 	$extension = lc($extension);
                   6840: 	if ($extension eq 'htm') { $extension='html'; }
                   6841: 
1.737     albertel 6842: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6843: 	    #no specific packages #how's our extension
                   6844: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6845: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6846: 					 \%metathesekeys);
                   6847: 	}
1.883     albertel 6848: 
                   6849: 	if (!exists($metaentry{':packages'})
                   6850: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6851: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6852: 		#no specific packages well let's get default then
                   6853: 		if ($key!~/^default&/) { next; }
1.488     albertel 6854: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6855: 					     \%metathesekeys);
                   6856: 	    }
                   6857: 	}
1.338     www      6858: # are there custom rights to evaluate
1.599     albertel 6859: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6860: 
1.338     www      6861:     #
                   6862:     # Importing a rights file here
1.339     albertel 6863:     #
                   6864: 	    unless ($depthcount) {
1.599     albertel 6865: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6866: 		my $dir=$filename;
                   6867: 		$dir=~s|[^/]*$||;
                   6868: 		$location=&filelocation($dir,$location);
1.736     albertel 6869: 		my $rights_metadata =
                   6870: 		    &metadata($uri,'keys',$location,'_rights',
                   6871: 			      $depthcount+1);
                   6872: 		foreach my $rights (split(',',$rights_metadata)) {
                   6873: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6874: 		    $metathesekeys{$rights}=1;
1.339     albertel 6875: 		}
                   6876: 	    }
                   6877: 	}
1.737     albertel 6878: 	# uniqifiy package listing
                   6879: 	my %seen;
                   6880: 	my @uniq_packages =
                   6881: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6882: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6883: 
                   6884: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6885: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6886: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6887: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6888: # this is the end of "was not already recently cached
1.71      www      6889:     }
1.599     albertel 6890:     return $metaentry{':'.$what};
1.261     albertel 6891: }
                   6892: 
1.488     albertel 6893: sub metadata_create_package_def {
1.483     albertel 6894:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6895:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6896:     if ($subp eq 'default') { next; }
                   6897:     
1.599     albertel 6898:     if (defined($metaentry{':packages'})) {
                   6899: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6900:     } else {
1.599     albertel 6901: 	$metaentry{':packages'}=$package;
1.483     albertel 6902:     }
                   6903:     my $value=$packagetab{$key};
                   6904:     my $unikey;
                   6905:     $unikey='parameter_0_'.$name;
1.599     albertel 6906:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6907:     $$metathesekeys{$unikey}=1;
1.599     albertel 6908:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6909: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6910:     }
1.599     albertel 6911:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6912: 	$metaentry{':'.$unikey}=
                   6913: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6914:     }
                   6915: }
                   6916: 
1.261     albertel 6917: sub metadata_generate_part0 {
                   6918:     my ($metadata,$metacache,$uri) = @_;
                   6919:     my %allnames;
1.737     albertel 6920:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6921: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6922: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6923: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6924: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6925: 	    $allnames{$name}=$part;
                   6926: 	  }
                   6927: 	}
                   6928:     }
                   6929:     foreach my $name (keys(%allnames)) {
                   6930:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6931:       my $key=":parameter_0_$name";
1.261     albertel 6932:       $$metacache{"$key.part"}='0';
                   6933:       $$metacache{"$key.name"}=$name;
1.428     albertel 6934:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6935: 					   $allnames{$name}.'_'.$name.
                   6936: 					   '.type'};
1.428     albertel 6937:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6938: 			     '.display'};
1.644     www      6939:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6940:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6941:       $$metacache{"$key.display"}=$olddis;
                   6942:     }
1.71      www      6943: }
                   6944: 
1.764     albertel 6945: # ------------------------------------------------------ Devalidate title cache
                   6946: 
                   6947: sub devalidate_title_cache {
                   6948:     my ($url)=@_;
                   6949:     if (!$env{'request.course.id'}) { return; }
                   6950:     my $symb=&symbread($url);
                   6951:     if (!$symb) { return; }
                   6952:     my $key=$env{'request.course.id'}."\0".$symb;
                   6953:     &devalidate_cache_new('title',$key);
                   6954: }
                   6955: 
1.301     www      6956: # ------------------------------------------------- Get the title of a resource
                   6957: 
                   6958: sub gettitle {
                   6959:     my $urlsymb=shift;
                   6960:     my $symb=&symbread($urlsymb);
1.534     albertel 6961:     if ($symb) {
1.620     albertel 6962: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6963: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6964: 	if (defined($cached)) { 
                   6965: 	    return $result;
                   6966: 	}
1.534     albertel 6967: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6968: 	my $title='';
1.907     albertel 6969: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   6970: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   6971: 	} else {
                   6972: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6973: 		    &GDBM_READER(),0640)) {
                   6974: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6975: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   6976: 		untie(%bighash);
                   6977: 	    }
1.534     albertel 6978: 	}
                   6979: 	$title=~s/\&colon\;/\:/gs;
                   6980: 	if ($title) {
1.599     albertel 6981: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6982: 	}
                   6983: 	$urlsymb=$url;
                   6984:     }
                   6985:     my $title=&metadata($urlsymb,'title');
                   6986:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6987:     return $title;
1.301     www      6988: }
1.613     albertel 6989: 
1.614     albertel 6990: sub get_slot {
                   6991:     my ($which,$cnum,$cdom)=@_;
                   6992:     if (!$cnum || !$cdom) {
1.790     albertel 6993: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6994: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6995: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6996:     }
1.703     albertel 6997:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6998:     my %slotinfo;
                   6999:     if (exists($remembered{$key})) {
                   7000: 	$slotinfo{$which} = $remembered{$key};
                   7001:     } else {
                   7002: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7003: 	&Apache::lonhomework::showhash(%slotinfo);
                   7004: 	my ($tmp)=keys(%slotinfo);
                   7005: 	if ($tmp=~/^error:/) { return (); }
                   7006: 	$remembered{$key} = $slotinfo{$which};
                   7007:     }
1.616     albertel 7008:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7009: 	return %{$slotinfo{$which}};
                   7010:     }
                   7011:     return $slotinfo{$which};
1.614     albertel 7012: }
1.31      www      7013: # ------------------------------------------------- Update symbolic store links
                   7014: 
                   7015: sub symblist {
                   7016:     my ($mapname,%newhash)=@_;
1.438     www      7017:     $mapname=&deversion(&declutter($mapname));
1.31      www      7018:     my %hash;
1.620     albertel 7019:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7020:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7021:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7022: 	    foreach my $url (keys %newhash) {
                   7023: 		next if ($url eq 'last_known'
                   7024: 			 && $env{'form.no_update_last_known'});
                   7025: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7026: 						    $newhash{$url}->[1],
                   7027: 						    $newhash{$url}->[0]);
1.191     harris41 7028:             }
1.31      www      7029:             if (untie(%hash)) {
                   7030: 		return 'ok';
                   7031:             }
                   7032:         }
                   7033:     }
                   7034:     return 'error';
1.212     www      7035: }
                   7036: 
                   7037: # --------------------------------------------------------------- Verify a symb
                   7038: 
                   7039: sub symbverify {
1.510     www      7040:     my ($symb,$thisurl)=@_;
                   7041:     my $thisfn=$thisurl;
1.439     www      7042:     $thisfn=&declutter($thisfn);
1.215     www      7043: # direct jump to resource in page or to a sequence - will construct own symbs
                   7044:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7045: # check URL part
1.409     www      7046:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7047: 
1.431     www      7048:     unless ($url eq $thisfn) { return 0; }
1.213     www      7049: 
1.216     www      7050:     $symb=&symbclean($symb);
1.510     www      7051:     $thisurl=&deversion($thisurl);
1.439     www      7052:     $thisfn=&deversion($thisfn);
1.213     www      7053: 
                   7054:     my %bighash;
                   7055:     my $okay=0;
1.431     www      7056: 
1.620     albertel 7057:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7058:                             &GDBM_READER(),0640)) {
1.510     www      7059:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7060:         unless ($ids) { 
1.510     www      7061:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7062:         }
                   7063:         if ($ids) {
                   7064: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7065: 	    foreach my $id (split(/\,/,$ids)) {
                   7066: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7067:                if (
                   7068:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7069:    eq $symb) { 
1.620     albertel 7070: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7071: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7072: 		       $okay=1; 
                   7073: 		   }
                   7074: 	       }
1.216     www      7075: 	   }
                   7076:         }
1.213     www      7077: 	untie(%bighash);
                   7078:     }
                   7079:     return $okay;
1.31      www      7080: }
                   7081: 
1.210     www      7082: # --------------------------------------------------------------- Clean-up symb
                   7083: 
                   7084: sub symbclean {
                   7085:     my $symb=shift;
1.568     albertel 7086:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7087: # remove version from map
                   7088:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7089: 
1.210     www      7090: # remove version from URL
                   7091:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7092: 
1.507     www      7093: # remove wrapper
                   7094: 
1.510     www      7095:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7096:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7097:     return $symb;
1.409     www      7098: }
                   7099: 
                   7100: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7101: 
                   7102: sub encode_symb {
                   7103:     my ($map,$resid,$url)=@_;
                   7104:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7105: }
1.409     www      7106: 
                   7107: sub decode_symb {
1.568     albertel 7108:     my $symb=shift;
                   7109:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7110:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7111:     return (&fixversion($map),$resid,&fixversion($url));
                   7112: }
                   7113: 
                   7114: sub fixversion {
                   7115:     my $fn=shift;
1.609     banghart 7116:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7117:     my %bighash;
                   7118:     my $uri=&clutter($fn);
1.620     albertel 7119:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7120: # is this cached?
1.599     albertel 7121:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7122:     if (defined($cached)) { return $result; }
                   7123: # unfortunately not cached, or expired
1.620     albertel 7124:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7125: 	    &GDBM_READER(),0640)) {
                   7126:  	if ($bighash{'version_'.$uri}) {
                   7127:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7128:  	    unless (($version eq 'mostrecent') || 
                   7129: 		    ($version==&getversion($uri))) {
1.440     www      7130:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7131:  	    }
                   7132:  	}
                   7133:  	untie %bighash;
1.413     www      7134:     }
1.599     albertel 7135:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7136: }
                   7137: 
                   7138: sub deversion {
                   7139:     my $url=shift;
                   7140:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7141:     return $url;
1.210     www      7142: }
                   7143: 
1.31      www      7144: # ------------------------------------------------------ Return symb list entry
                   7145: 
                   7146: sub symbread {
1.249     www      7147:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7148:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7149:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7150: # no filename provided? try from environment
1.44      www      7151:     unless ($thisfn) {
1.620     albertel 7152:         if ($env{'request.symb'}) {
                   7153: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7154: 	}
1.620     albertel 7155: 	$thisfn=$env{'request.filename'};
1.44      www      7156:     }
1.569     albertel 7157:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7158: # is that filename actually a symb? Verify, clean, and return
                   7159:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7160: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7161: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7162: 	}
1.242     www      7163:     }
1.44      www      7164:     $thisfn=declutter($thisfn);
1.31      www      7165:     my %hash;
1.37      www      7166:     my %bighash;
                   7167:     my $syval='';
1.620     albertel 7168:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7169:         my $targetfn = $thisfn;
1.609     banghart 7170:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7171:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7172:         }
1.687     albertel 7173: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7174: 	    $targetfn=$1;
                   7175: 	}
1.620     albertel 7176:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7177:                       &GDBM_READER(),0640)) {
1.481     raeburn  7178: 	    $syval=$hash{$targetfn};
1.37      www      7179:             untie(%hash);
                   7180:         }
                   7181: # ---------------------------------------------------------- There was an entry
                   7182:         if ($syval) {
1.601     albertel 7183: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7184: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7185: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7186: 		    #return $env{$cache_str}='';
1.601     albertel 7187: 		#}    
                   7188: 		#$syval.=$1;
                   7189: 	    #}
1.37      www      7190:         } else {
                   7191: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7192:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7193:                             &GDBM_READER(),0640)) {
1.37      www      7194: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7195:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7196:               unless ($ids) { 
                   7197:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7198:               }
                   7199:               unless ($ids) {
                   7200: # alias?
                   7201: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7202:               }
1.37      www      7203:               if ($ids) {
                   7204: # ------------------------------------------------------------------- Has ID(s)
                   7205:                  my @possibilities=split(/\,/,$ids);
1.39      www      7206:                  if ($#possibilities==0) {
                   7207: # ----------------------------------------------- There is only one possibility
1.37      www      7208: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7209: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7210: 						    $resid,$thisfn);
1.249     www      7211:                  } elsif (!$donotrecurse) {
1.39      www      7212: # ------------------------------------------ There is more than one possibility
                   7213:                      my $realpossible=0;
1.800     albertel 7214:                      foreach my $id (@possibilities) {
                   7215: 			 my $file=$bighash{'src_'.$id};
1.39      www      7216:                          if (&allowed('bre',$file)) {
1.800     albertel 7217:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7218:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7219: 				$realpossible++;
1.626     albertel 7220:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7221: 						    $resid,$thisfn);
1.39      www      7222:                             }
                   7223: 			 }
1.191     harris41 7224:                      }
1.39      www      7225: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7226:                  } else {
                   7227:                      $syval='';
1.37      www      7228:                  }
                   7229: 	      }
                   7230:               untie(%bighash)
1.481     raeburn  7231:            }
1.31      www      7232:         }
1.62      www      7233:         if ($syval) {
1.620     albertel 7234: 	    return $env{$cache_str}=$syval;
1.62      www      7235:         }
1.31      www      7236:     }
1.44      www      7237:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7238:     return $env{$cache_str}='';
1.31      www      7239: }
                   7240: 
                   7241: # ---------------------------------------------------------- Return random seed
                   7242: 
1.32      www      7243: sub numval {
                   7244:     my $txt=shift;
                   7245:     $txt=~tr/A-J/0-9/;
                   7246:     $txt=~tr/a-j/0-9/;
                   7247:     $txt=~tr/K-T/0-9/;
                   7248:     $txt=~tr/k-t/0-9/;
                   7249:     $txt=~tr/U-Z/0-5/;
                   7250:     $txt=~tr/u-z/0-5/;
                   7251:     $txt=~s/\D//g;
1.564     albertel 7252:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7253:     return int($txt);
1.368     albertel 7254: }
                   7255: 
1.484     albertel 7256: sub numval2 {
                   7257:     my $txt=shift;
                   7258:     $txt=~tr/A-J/0-9/;
                   7259:     $txt=~tr/a-j/0-9/;
                   7260:     $txt=~tr/K-T/0-9/;
                   7261:     $txt=~tr/k-t/0-9/;
                   7262:     $txt=~tr/U-Z/0-5/;
                   7263:     $txt=~tr/u-z/0-5/;
                   7264:     $txt=~s/\D//g;
                   7265:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7266:     my $total;
                   7267:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7268:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7269:     return int($total);
                   7270: }
                   7271: 
1.575     albertel 7272: sub numval3 {
                   7273:     use integer;
                   7274:     my $txt=shift;
                   7275:     $txt=~tr/A-J/0-9/;
                   7276:     $txt=~tr/a-j/0-9/;
                   7277:     $txt=~tr/K-T/0-9/;
                   7278:     $txt=~tr/k-t/0-9/;
                   7279:     $txt=~tr/U-Z/0-5/;
                   7280:     $txt=~tr/u-z/0-5/;
                   7281:     $txt=~s/\D//g;
                   7282:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7283:     my $total;
                   7284:     foreach my $val (@txts) { $total+=$val; }
                   7285:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7286:     return $total;
                   7287: }
                   7288: 
1.675     albertel 7289: sub digest {
                   7290:     my ($data)=@_;
                   7291:     my $digest=&Digest::MD5::md5($data);
                   7292:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7293:     my ($e,$f);
                   7294:     {
                   7295:         use integer;
                   7296:         $e=($a+$b);
                   7297:         $f=($c+$d);
                   7298:         if ($_64bit) {
                   7299:             $e=(($e<<32)>>32);
                   7300:             $f=(($f<<32)>>32);
                   7301:         }
                   7302:     }
                   7303:     if (wantarray) {
                   7304: 	return ($e,$f);
                   7305:     } else {
                   7306: 	my $g;
                   7307: 	{
                   7308: 	    use integer;
                   7309: 	    $g=($e+$f);
                   7310: 	    if ($_64bit) {
                   7311: 		$g=(($g<<32)>>32);
                   7312: 	    }
                   7313: 	}
                   7314: 	return $g;
                   7315:     }
                   7316: }
                   7317: 
1.368     albertel 7318: sub latest_rnd_algorithm_id {
1.675     albertel 7319:     return '64bit5';
1.366     albertel 7320: }
1.32      www      7321: 
1.503     albertel 7322: sub get_rand_alg {
                   7323:     my ($courseid)=@_;
1.790     albertel 7324:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7325:     if ($courseid) {
1.620     albertel 7326: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7327:     }
                   7328:     return &latest_rnd_algorithm_id();
                   7329: }
                   7330: 
1.562     albertel 7331: sub validCODE {
                   7332:     my ($CODE)=@_;
                   7333:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7334:     return 0;
                   7335: }
                   7336: 
1.491     albertel 7337: sub getCODE {
1.620     albertel 7338:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7339:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7340: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7341: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7342: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7343:     }
                   7344:     return undef;
                   7345: }
                   7346: 
1.31      www      7347: sub rndseed {
1.155     albertel 7348:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7349:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7350:     if (!defined($symb)) {
1.366     albertel 7351: 	unless ($symb=$wsymb) { return time; }
                   7352:     }
                   7353:     if (!$courseid) { $courseid=$wcourseid; }
                   7354:     if (!$domain) { $domain=$wdomain; }
                   7355:     if (!$username) { $username=$wusername }
1.503     albertel 7356:     my $which=&get_rand_alg();
1.803     albertel 7357: 
1.491     albertel 7358:     if (defined(&getCODE())) {
1.675     albertel 7359: 	if ($which eq '64bit5') {
                   7360: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7361: 	} elsif ($which eq '64bit4') {
1.575     albertel 7362: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7363: 	} else {
                   7364: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7365: 	}
1.675     albertel 7366:     } elsif ($which eq '64bit5') {
                   7367: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7368:     } elsif ($which eq '64bit4') {
                   7369: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7370:     } elsif ($which eq '64bit3') {
                   7371: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7372:     } elsif ($which eq '64bit2') {
                   7373: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7374:     } elsif ($which eq '64bit') {
                   7375: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7376:     }
                   7377:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7378: }
                   7379: 
                   7380: sub rndseed_32bit {
                   7381:     my ($symb,$courseid,$domain,$username)=@_;
                   7382:     {
                   7383: 	use integer;
                   7384: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7385: 	my $symbseed=numval($symb) << 22;
                   7386: 	my $namechck=unpack("%32C*",$username) << 17;
                   7387: 	my $nameseed=numval($username) << 12;
                   7388: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7389: 	my $courseseed=unpack("%32C*",$courseid);
                   7390: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7391: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7392: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7393: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7394: 	return $num;
                   7395:     }
                   7396: }
                   7397: 
                   7398: sub rndseed_64bit {
                   7399:     my ($symb,$courseid,$domain,$username)=@_;
                   7400:     {
                   7401: 	use integer;
                   7402: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7403: 	my $symbseed=numval($symb) << 10;
                   7404: 	my $namechck=unpack("%32S*",$username);
                   7405: 	
                   7406: 	my $nameseed=numval($username) << 21;
                   7407: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7408: 	my $courseseed=unpack("%32S*",$courseid);
                   7409: 	
                   7410: 	my $num1=$symbchck+$symbseed+$namechck;
                   7411: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7412: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7413: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7414: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7415: 	return "$num1,$num2";
1.155     albertel 7416:     }
1.366     albertel 7417: }
                   7418: 
1.443     albertel 7419: sub rndseed_64bit2 {
                   7420:     my ($symb,$courseid,$domain,$username)=@_;
                   7421:     {
                   7422: 	use integer;
                   7423: 	# strings need to be an even # of cahracters long, it it is odd the
                   7424:         # last characters gets thrown away
                   7425: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7426: 	my $symbseed=numval($symb) << 10;
                   7427: 	my $namechck=unpack("%32S*",$username.' ');
                   7428: 	
                   7429: 	my $nameseed=numval($username) << 21;
1.501     albertel 7430: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7431: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7432: 	
                   7433: 	my $num1=$symbchck+$symbseed+$namechck;
                   7434: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7435: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7436: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7437: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7438: 	return "$num1,$num2";
                   7439:     }
                   7440: }
                   7441: 
                   7442: sub rndseed_64bit3 {
                   7443:     my ($symb,$courseid,$domain,$username)=@_;
                   7444:     {
                   7445: 	use integer;
                   7446: 	# strings need to be an even # of cahracters long, it it is odd the
                   7447:         # last characters gets thrown away
                   7448: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7449: 	my $symbseed=numval2($symb) << 10;
                   7450: 	my $namechck=unpack("%32S*",$username.' ');
                   7451: 	
                   7452: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7453: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7454: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7455: 	
                   7456: 	my $num1=$symbchck+$symbseed+$namechck;
                   7457: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7458: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7459: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7460: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7461: 	
1.503     albertel 7462: 	return "$num1:$num2";
1.443     albertel 7463:     }
                   7464: }
                   7465: 
1.575     albertel 7466: sub rndseed_64bit4 {
                   7467:     my ($symb,$courseid,$domain,$username)=@_;
                   7468:     {
                   7469: 	use integer;
                   7470: 	# strings need to be an even # of cahracters long, it it is odd the
                   7471:         # last characters gets thrown away
                   7472: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7473: 	my $symbseed=numval3($symb) << 10;
                   7474: 	my $namechck=unpack("%32S*",$username.' ');
                   7475: 	
                   7476: 	my $nameseed=numval3($username) << 21;
                   7477: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7478: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7479: 	
                   7480: 	my $num1=$symbchck+$symbseed+$namechck;
                   7481: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7482: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7483: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7484: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7485: 	
                   7486: 	return "$num1:$num2";
                   7487:     }
                   7488: }
                   7489: 
1.675     albertel 7490: sub rndseed_64bit5 {
                   7491:     my ($symb,$courseid,$domain,$username)=@_;
                   7492:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7493:     return "$num1:$num2";
                   7494: }
                   7495: 
1.366     albertel 7496: sub rndseed_CODE_64bit {
                   7497:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7498:     {
1.366     albertel 7499: 	use integer;
1.443     albertel 7500: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7501: 	my $symbseed=numval2($symb);
1.491     albertel 7502: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7503: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7504: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7505: 	my $num1=$symbseed+$CODEchck;
                   7506: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7507: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7508: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7509: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7510: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7511: 	return "$num1:$num2";
1.366     albertel 7512:     }
                   7513: }
                   7514: 
1.575     albertel 7515: sub rndseed_CODE_64bit4 {
                   7516:     my ($symb,$courseid,$domain,$username)=@_;
                   7517:     {
                   7518: 	use integer;
                   7519: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7520: 	my $symbseed=numval3($symb);
                   7521: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7522: 	my $CODEseed=numval3(&getCODE());
                   7523: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7524: 	my $num1=$symbseed+$CODEchck;
                   7525: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7526: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7527: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7528: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7529: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7530: 	return "$num1:$num2";
                   7531:     }
                   7532: }
                   7533: 
1.675     albertel 7534: sub rndseed_CODE_64bit5 {
                   7535:     my ($symb,$courseid,$domain,$username)=@_;
                   7536:     my $code = &getCODE();
                   7537:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7538:     return "$num1:$num2";
                   7539: }
                   7540: 
1.366     albertel 7541: sub setup_random_from_rndseed {
                   7542:     my ($rndseed)=@_;
1.503     albertel 7543:     if ($rndseed =~/([,:])/) {
                   7544: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7545: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7546:     } else {
                   7547: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7548:     }
1.36      albertel 7549: }
                   7550: 
1.474     albertel 7551: sub latest_receipt_algorithm_id {
1.835     albertel 7552:     return 'receipt3';
1.474     albertel 7553: }
                   7554: 
1.480     www      7555: sub recunique {
                   7556:     my $fucourseid=shift;
                   7557:     my $unique;
1.835     albertel 7558:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7559: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7560: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7561:     } else {
                   7562: 	$unique=$perlvar{'lonReceipt'};
                   7563:     }
                   7564:     return unpack("%32C*",$unique);
                   7565: }
                   7566: 
                   7567: sub recprefix {
                   7568:     my $fucourseid=shift;
                   7569:     my $prefix;
1.835     albertel 7570:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7571: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7572: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7573:     } else {
                   7574: 	$prefix=$perlvar{'lonHostID'};
                   7575:     }
                   7576:     return unpack("%32C*",$prefix);
                   7577: }
                   7578: 
1.76      www      7579: sub ireceipt {
1.474     albertel 7580:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7581: 
                   7582:     my $return =&recprefix($fucourseid).'-';
                   7583: 
                   7584:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7585: 	$env{'request.state'} eq 'construct') {
                   7586: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7587: 	return $return;
                   7588:     }
                   7589: 
1.76      www      7590:     my $cuname=unpack("%32C*",$funame);
                   7591:     my $cudom=unpack("%32C*",$fudom);
                   7592:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7593:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7594:     my $cunique=&recunique($fucourseid);
1.474     albertel 7595:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7596:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7597: 
1.790     albertel 7598: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7599: 			       
                   7600: 	$return.= ($cunique%$cuname+
                   7601: 		   $cunique%$cudom+
                   7602: 		   $cusymb%$cuname+
                   7603: 		   $cusymb%$cudom+
                   7604: 		   $cucourseid%$cuname+
                   7605: 		   $cucourseid%$cudom+
                   7606: 		   $cpart%$cuname+
                   7607: 		   $cpart%$cudom);
                   7608:     } else {
                   7609: 	$return.= ($cunique%$cuname+
                   7610: 		   $cunique%$cudom+
                   7611: 		   $cusymb%$cuname+
                   7612: 		   $cusymb%$cudom+
                   7613: 		   $cucourseid%$cuname+
                   7614: 		   $cucourseid%$cudom);
                   7615:     }
                   7616:     return $return;
1.76      www      7617: }
                   7618: 
                   7619: sub receipt {
1.474     albertel 7620:     my ($part)=@_;
1.790     albertel 7621:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7622:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7623: }
1.260     ng       7624: 
1.790     albertel 7625: sub whichuser {
                   7626:     my ($passedsymb)=@_;
                   7627:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7628:     if (defined($env{'form.grade_symb'})) {
                   7629: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7630: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7631: 	if (!$allowed &&
                   7632: 	    exists($env{'request.course.sec'}) &&
                   7633: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7634: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7635: 			      '/'.$env{'request.course.sec'});
                   7636: 	}
                   7637: 	if ($allowed) {
                   7638: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7639: 	    $courseid=$tmp_courseid;
                   7640: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7641: 	    ($name)=&get_env_multiple('form.grade_username');
                   7642: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7643: 	}
                   7644:     }
                   7645:     if (!$passedsymb) {
                   7646: 	$symb=&symbread();
                   7647:     } else {
                   7648: 	$symb=$passedsymb;
                   7649:     }
                   7650:     $courseid=$env{'request.course.id'};
                   7651:     $domain=$env{'user.domain'};
                   7652:     $name=$env{'user.name'};
                   7653:     if ($name eq 'public' && $domain eq 'public') {
                   7654: 	if (!defined($env{'form.username'})) {
                   7655: 	    $env{'form.username'}.=time.rand(10000000);
                   7656: 	}
                   7657: 	$name.=$env{'form.username'};
                   7658:     }
                   7659:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7660: 
                   7661: }
                   7662: 
1.36      albertel 7663: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7664: # returns either the contents of the file or 
                   7665: # -1 if the file doesn't exist
1.481     raeburn  7666: #
                   7667: # if the target is a file that was uploaded via DOCS, 
                   7668: # a check will be made to see if a current copy exists on the local server,
                   7669: # if it does this will be served, otherwise a copy will be retrieved from
                   7670: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7671: # the local server.   
1.472     albertel 7672: 
1.36      albertel 7673: sub getfile {
1.538     albertel 7674:     my ($file) = @_;
1.609     banghart 7675:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7676:     &repcopy($file);
                   7677:     return &readfile($file);
                   7678: }
                   7679: 
                   7680: sub repcopy_userfile {
                   7681:     my ($file)=@_;
1.609     banghart 7682:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7683:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7684:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7685: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7686:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7687:     if (-e "$file") {
1.828     www      7688: # we already have a local copy, check it out
1.538     albertel 7689: 	my @fileinfo = stat($file);
1.828     www      7690: 	my $rtncode;
                   7691: 	my $info;
1.538     albertel 7692: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7693: 	if ($lwpresp ne 'ok') {
1.828     www      7694: # there is no such file anymore, even though we had a local copy
1.482     albertel 7695: 	    if ($rtncode eq '404') {
1.538     albertel 7696: 		unlink($file);
1.482     albertel 7697: 	    }
                   7698: 	    return -1;
                   7699: 	}
                   7700: 	if ($info < $fileinfo[9]) {
1.828     www      7701: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7702: 	    return 'ok';
1.828     www      7703: 	} else {
                   7704: # the file is outdated, get rid of it
                   7705: 	    unlink($file);
1.482     albertel 7706: 	}
1.828     www      7707:     }
                   7708: # one way or the other, at this point, we don't have the file
                   7709: # construct the correct path for the file
                   7710:     my @parts = ($cdom,$cnum); 
                   7711:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7712: 	push @parts, split(/\//,$1);
                   7713:     }
                   7714:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7715:     foreach my $part (@parts) {
                   7716: 	$path .= '/'.$part;
                   7717: 	if (!-e $path) {
                   7718: 	    mkdir($path,0770);
1.482     albertel 7719: 	}
                   7720:     }
1.828     www      7721: # now the path exists for sure
                   7722: # get a user agent
                   7723:     my $ua=new LWP::UserAgent;
                   7724:     my $transferfile=$file.'.in.transfer';
                   7725: # FIXME: this should flock
                   7726:     if (-e $transferfile) { return 'ok'; }
                   7727:     my $request;
                   7728:     $uri=~s/^\///;
1.838     albertel 7729:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7730:     my $response=$ua->request($request,$transferfile);
                   7731: # did it work?
                   7732:     if ($response->is_error()) {
                   7733: 	unlink($transferfile);
                   7734: 	&logthis("Userfile repcopy failed for $uri");
                   7735: 	return -1;
                   7736:     }
                   7737: # worked, rename the transfer file
                   7738:     rename($transferfile,$file);
1.607     raeburn  7739:     return 'ok';
1.481     raeburn  7740: }
                   7741: 
1.517     albertel 7742: sub tokenwrapper {
                   7743:     my $uri=shift;
1.552     albertel 7744:     $uri=~s|^http\://([^/]+)||;
                   7745:     $uri=~s|^/||;
1.620     albertel 7746:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7747:     my $token=$1;
1.552     albertel 7748:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7749:     if ($udom && $uname && $file) {
                   7750: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7751:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7752:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7753:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7754:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7755:     } else {
                   7756:         return '/adm/notfound.html';
                   7757:     }
                   7758: }
                   7759: 
1.828     www      7760: # call with reqtype HEAD: get last modification time
                   7761: # call with reqtype GET: get the file contents
                   7762: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7763: #
1.481     raeburn  7764: sub getuploaded {
                   7765:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7766:     $uri=~s/^\///;
1.838     albertel 7767:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7768:     my $ua=new LWP::UserAgent;
                   7769:     my $request=new HTTP::Request($reqtype,$uri);
                   7770:     my $response=$ua->request($request);
                   7771:     $$rtncode = $response->code;
1.482     albertel 7772:     if (! $response->is_success()) {
                   7773: 	return 'failed';
                   7774:     }      
                   7775:     if ($reqtype eq 'HEAD') {
1.486     www      7776: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7777:     } elsif ($reqtype eq 'GET') {
                   7778: 	$$info = $response->content;
1.472     albertel 7779:     }
1.482     albertel 7780:     return 'ok';
1.36      albertel 7781: }
                   7782: 
1.481     raeburn  7783: sub readfile {
                   7784:     my $file = shift;
                   7785:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7786:     my $fh;
                   7787:     open($fh,"<$file");
                   7788:     my $a='';
1.800     albertel 7789:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7790:     return $a;
                   7791: }
                   7792: 
1.36      albertel 7793: sub filelocation {
1.590     banghart 7794:     my ($dir,$file) = @_;
                   7795:     my $location;
                   7796:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7797: 
                   7798:     if ($file =~ m-^/adm/-) {
                   7799: 	$file=~s-^/adm/wrapper/-/-;
                   7800: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7801:     }
1.882     albertel 7802: 
1.590     banghart 7803:     if ($file=~m:^/~:) { # is a contruction space reference
                   7804:         $location = $file;
                   7805:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7806:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7807: 	# is a correct contruction space reference
                   7808:         $location = $file;
1.609     banghart 7809:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7810:         my ($udom,$uname,$filename)=
1.811     albertel 7811:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7812:         my $home=&homeserver($uname,$udom);
                   7813:         my $is_me=0;
                   7814:         my @ids=&current_machine_ids();
                   7815:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7816:         if ($is_me) {
1.740     www      7817:   	    $location=&propath($udom,$uname).
1.590     banghart 7818:   	      '/userfiles/'.$filename;
                   7819:         } else {
                   7820:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7821:   	      $udom.'/'.$uname.'/'.$filename;
                   7822:         }
1.882     albertel 7823:     } elsif ($file =~ m-^/adm/-) {
                   7824: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7825:     } else {
                   7826:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7827:         $file=~s:^/res/:/:;
                   7828:         if ( !( $file =~ m:^/:) ) {
                   7829:             $location = $dir. '/'.$file;
                   7830:         } else {
                   7831:             $location = '/home/httpd/html/res'.$file;
                   7832:         }
1.59      albertel 7833:     }
1.590     banghart 7834:     $location=~s://+:/:g; # remove duplicate /
                   7835:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7836:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7837:     return $location;
1.46      www      7838: }
1.36      albertel 7839: 
1.46      www      7840: sub hreflocation {
                   7841:     my ($dir,$file)=@_;
1.460     albertel 7842:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7843: 	$file=filelocation($dir,$file);
1.700     albertel 7844:     } elsif ($file=~m-^/adm/-) {
                   7845: 	$file=~s-^/adm/wrapper/-/-;
                   7846: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7847:     }
                   7848:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7849: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7850:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7851: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7852:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7853: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7854: 	    -/uploaded/$1/$2/-x;
1.46      www      7855:     }
1.913     albertel 7856:     if ($file=~ m{^/userfiles/}) {
                   7857: 	$file =~ s{^/userfiles/}{/uploaded/};
                   7858:     }
1.462     albertel 7859:     return $file;
1.465     albertel 7860: }
                   7861: 
                   7862: sub current_machine_domains {
1.853     albertel 7863:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7864: }
                   7865: 
                   7866: sub machine_domains {
                   7867:     my ($hostname) = @_;
1.465     albertel 7868:     my @domains;
1.838     albertel 7869:     my %hostname = &all_hostnames();
1.465     albertel 7870:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7871: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7872: 	if ($hostname eq $name) {
1.844     albertel 7873: 	    push(@domains,&host_domain($id));
1.465     albertel 7874: 	}
                   7875:     }
                   7876:     return @domains;
                   7877: }
                   7878: 
                   7879: sub current_machine_ids {
1.853     albertel 7880:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7881: }
                   7882: 
                   7883: sub machine_ids {
                   7884:     my ($hostname) = @_;
                   7885:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7886:     my @ids;
1.888     albertel 7887:     my %name_to_host = &all_names();
1.889     albertel 7888:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7889: 	return @{ $name_to_host{$hostname} };
                   7890:     }
                   7891:     return;
1.31      www      7892: }
                   7893: 
1.824     raeburn  7894: sub additional_machine_domains {
                   7895:     my @domains;
                   7896:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7897:     while( my $line = <$fh>) {
                   7898:         $line =~ s/\s//g;
                   7899:         push(@domains,$line);
                   7900:     }
                   7901:     return @domains;
                   7902: }
                   7903: 
                   7904: sub default_login_domain {
                   7905:     my $domain = $perlvar{'lonDefDomain'};
                   7906:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7907:     foreach my $posdom (&current_machine_domains(),
                   7908:                         &additional_machine_domains()) {
                   7909:         if (lc($posdom) eq lc($testdomain)) {
                   7910:             $domain=$posdom;
                   7911:             last;
                   7912:         }
                   7913:     }
                   7914:     return $domain;
                   7915: }
                   7916: 
1.31      www      7917: # ------------------------------------------------------------- Declutters URLs
                   7918: 
                   7919: sub declutter {
                   7920:     my $thisfn=shift;
1.569     albertel 7921:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7922:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7923:     $thisfn=~s/^\///;
1.697     albertel 7924:     $thisfn=~s|^adm/wrapper/||;
                   7925:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7926:     $thisfn=~s/^res\///;
1.235     www      7927:     $thisfn=~s/\?.+$//;
1.268     www      7928:     return $thisfn;
                   7929: }
                   7930: 
                   7931: # ------------------------------------------------------------- Clutter up URLs
                   7932: 
                   7933: sub clutter {
                   7934:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7935:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7936: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7937:        $thisfn='/res'.$thisfn; 
                   7938:     }
1.694     albertel 7939:     if ($thisfn !~m|/adm|) {
1.695     albertel 7940: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7941: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7942: 	} else {
                   7943: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7944: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7945: 	    if ($embstyle eq 'ssi'
                   7946: 		|| ($embstyle eq 'hdn')
                   7947: 		|| ($embstyle eq 'rat')
                   7948: 		|| ($embstyle eq 'prv')
                   7949: 		|| ($embstyle eq 'ign')) {
                   7950: 		#do nothing with these
                   7951: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7952: 		|| ($embstyle eq 'emb')
                   7953: 		|| ($embstyle eq 'wrp')) {
                   7954: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7955: 	    } elsif ($embstyle eq 'unk'
                   7956: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7957: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7958: 	    } else {
1.718     www      7959: #		&logthis("Got a blank emb style");
1.695     albertel 7960: 	    }
1.694     albertel 7961: 	}
                   7962:     }
1.31      www      7963:     return $thisfn;
1.12      www      7964: }
                   7965: 
1.787     albertel 7966: sub clutter_with_no_wrapper {
                   7967:     my $uri = &clutter(shift);
                   7968:     if ($uri =~ m-^/adm/-) {
                   7969: 	$uri =~ s-^/adm/wrapper/-/-;
                   7970: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7971:     }
                   7972:     return $uri;
                   7973: }
                   7974: 
1.557     albertel 7975: sub freeze_escape {
                   7976:     my ($value)=@_;
                   7977:     if (ref($value)) {
                   7978: 	$value=&nfreeze($value);
                   7979: 	return '__FROZEN__'.&escape($value);
                   7980:     }
                   7981:     return &escape($value);
                   7982: }
                   7983: 
1.11      www      7984: 
1.557     albertel 7985: sub thaw_unescape {
                   7986:     my ($value)=@_;
                   7987:     if ($value =~ /^__FROZEN__/) {
                   7988: 	substr($value,0,10,undef);
                   7989: 	$value=&unescape($value);
                   7990: 	return &thaw($value);
                   7991:     }
                   7992:     return &unescape($value);
                   7993: }
                   7994: 
1.436     albertel 7995: sub correct_line_ends {
                   7996:     my ($result)=@_;
                   7997:     $$result =~s/\r\n/\n/mg;
                   7998:     $$result =~s/\r/\n/mg;
1.415     albertel 7999: }
1.1       albertel 8000: # ================================================================ Main Program
                   8001: 
1.184     www      8002: sub goodbye {
1.204     albertel 8003:    &logthis("Starting Shut down");
1.443     albertel 8004: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8005:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8006: #converted
1.599     albertel 8007: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8008:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8009: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8010: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8011: #1.1 only
1.870     albertel 8012: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8013: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8014: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8015: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8016:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8017:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8018:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8019:    &flushcourselogs();
                   8020:    &logthis("Shutting down");
                   8021: }
                   8022: 
1.852     albertel 8023: sub get_dns {
1.869     albertel 8024:     my ($url,$func,$ignore_cache) = @_;
                   8025:     if (!$ignore_cache) {
                   8026: 	my ($content,$cached)=
                   8027: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8028: 	if ($cached) {
                   8029: 	    &$func($content);
                   8030: 	    return;
                   8031: 	}
                   8032:     }
                   8033: 
                   8034:     my %alldns;
1.852     albertel 8035:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8036:     foreach my $dns (<$config>) {
                   8037: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8038: 	$alldns{$1} = 1;
                   8039:     }
                   8040:     while (%alldns) {
                   8041: 	my ($dns) = keys(%alldns);
                   8042: 	delete($alldns{$dns});
1.852     albertel 8043: 	my $ua=new LWP::UserAgent;
                   8044: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8045: 	my $response=$ua->request($request);
                   8046: 	next if ($response->is_error());
                   8047: 	my @content = split("\n",$response->content);
1.869     albertel 8048: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8049: 	&$func(\@content);
1.869     albertel 8050: 	return;
1.852     albertel 8051:     }
                   8052:     close($config);
1.871     albertel 8053:     my $which = (split('/',$url))[3];
                   8054:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8055:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8056:     my @content = <$config>;
                   8057:     &$func(\@content);
                   8058:     return;
1.852     albertel 8059: }
1.327     albertel 8060: # ------------------------------------------------------------ Read domain file
                   8061: {
1.852     albertel 8062:     my $loaded;
1.846     albertel 8063:     my %domain;
                   8064: 
1.852     albertel 8065:     sub parse_domain_tab {
                   8066: 	my ($lines) = @_;
                   8067: 	foreach my $line (@$lines) {
                   8068: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8069: 
1.846     albertel 8070: 	    chomp($line);
1.852     albertel 8071: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8072: 	    my %this_domain;
                   8073: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8074: 			       'lang_def', 'city', 'longi', 'lati',
                   8075: 			       'primary') {
                   8076: 		$this_domain{$field} = shift(@elements);
                   8077: 	    }
                   8078: 	    $domain{$name} = \%this_domain;
1.852     albertel 8079: 	}
                   8080:     }
1.864     albertel 8081: 
                   8082:     sub reset_domain_info {
                   8083: 	undef($loaded);
                   8084: 	undef(%domain);
                   8085:     }
                   8086: 
1.852     albertel 8087:     sub load_domain_tab {
1.869     albertel 8088: 	my ($ignore_cache) = @_;
                   8089: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8090: 	my $fh;
                   8091: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8092: 	    my @lines = <$fh>;
                   8093: 	    &parse_domain_tab(\@lines);
1.448     albertel 8094: 	}
1.852     albertel 8095: 	close($fh);
                   8096: 	$loaded = 1;
1.327     albertel 8097:     }
1.846     albertel 8098: 
                   8099:     sub domain {
1.852     albertel 8100: 	&load_domain_tab() if (!$loaded);
                   8101: 
1.846     albertel 8102: 	my ($name,$what) = @_;
                   8103: 	return if ( !exists($domain{$name}) );
                   8104: 
                   8105: 	if (!$what) {
                   8106: 	    return $domain{$name}{'description'};
                   8107: 	}
                   8108: 	return $domain{$name}{$what};
                   8109:     }
1.327     albertel 8110: }
                   8111: 
                   8112: 
1.1       albertel 8113: # ------------------------------------------------------------- Read hosts file
                   8114: {
1.838     albertel 8115:     my %hostname;
1.844     albertel 8116:     my %hostdom;
1.845     albertel 8117:     my %libserv;
1.852     albertel 8118:     my $loaded;
1.888     albertel 8119:     my %name_to_host;
1.852     albertel 8120: 
                   8121:     sub parse_hosts_tab {
                   8122: 	my ($file) = @_;
                   8123: 	foreach my $configline (@$file) {
                   8124: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8125: 	    next if ($configline =~ /^\^/);
                   8126: 	    chomp($configline);
                   8127: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8128: 	    $name=~s/\s//g;
                   8129: 	    if ($id && $domain && $role && $name) {
                   8130: 		$hostname{$id}=$name;
1.888     albertel 8131: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8132: 		$hostdom{$id}=$domain;
                   8133: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8134: 	    }
                   8135: 	}
                   8136:     }
1.864     albertel 8137:     
                   8138:     sub reset_hosts_info {
1.897     albertel 8139: 	&purge_remembered();
1.864     albertel 8140: 	&reset_domain_info();
                   8141: 	&reset_hosts_ip_info();
1.892     albertel 8142: 	undef(%name_to_host);
1.864     albertel 8143: 	undef(%hostname);
                   8144: 	undef(%hostdom);
                   8145: 	undef(%libserv);
                   8146: 	undef($loaded);
                   8147:     }
1.1       albertel 8148: 
1.852     albertel 8149:     sub load_hosts_tab {
1.869     albertel 8150: 	my ($ignore_cache) = @_;
                   8151: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8152: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8153: 	my @config = <$config>;
                   8154: 	&parse_hosts_tab(\@config);
                   8155: 	close($config);
                   8156: 	$loaded=1;
1.1       albertel 8157:     }
1.852     albertel 8158: 
1.838     albertel 8159:     sub hostname {
1.852     albertel 8160: 	&load_hosts_tab() if (!$loaded);
                   8161: 
1.838     albertel 8162: 	my ($lonid) = @_;
                   8163: 	return $hostname{$lonid};
                   8164:     }
1.845     albertel 8165: 
1.838     albertel 8166:     sub all_hostnames {
1.852     albertel 8167: 	&load_hosts_tab() if (!$loaded);
                   8168: 
1.838     albertel 8169: 	return %hostname;
                   8170:     }
1.845     albertel 8171: 
1.888     albertel 8172:     sub all_names {
                   8173: 	&load_hosts_tab() if (!$loaded);
                   8174: 
                   8175: 	return %name_to_host;
                   8176:     }
                   8177: 
1.845     albertel 8178:     sub is_library {
1.852     albertel 8179: 	&load_hosts_tab() if (!$loaded);
                   8180: 
1.845     albertel 8181: 	return exists($libserv{$_[0]});
                   8182:     }
                   8183: 
                   8184:     sub all_library {
1.852     albertel 8185: 	&load_hosts_tab() if (!$loaded);
                   8186: 
1.845     albertel 8187: 	return %libserv;
                   8188:     }
                   8189: 
1.841     albertel 8190:     sub get_servers {
1.852     albertel 8191: 	&load_hosts_tab() if (!$loaded);
                   8192: 
1.841     albertel 8193: 	my ($domain,$type) = @_;
                   8194: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8195: 	                                          : %hostname;
                   8196: 	my %result;
1.842     albertel 8197: 	if (ref($domain) eq 'ARRAY') {
                   8198: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8199: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8200: 		    $result{$host} = $hostname;
                   8201: 		}
                   8202: 	    }
                   8203: 	} else {
                   8204: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8205: 		if ($hostdom{$host} eq $domain) {
                   8206: 		    $result{$host} = $hostname;
                   8207: 		}
1.841     albertel 8208: 	    }
                   8209: 	}
                   8210: 	return %result;
                   8211:     }
1.845     albertel 8212: 
1.844     albertel 8213:     sub host_domain {
1.852     albertel 8214: 	&load_hosts_tab() if (!$loaded);
                   8215: 
1.844     albertel 8216: 	my ($lonid) = @_;
                   8217: 	return $hostdom{$lonid};
                   8218:     }
                   8219: 
1.841     albertel 8220:     sub all_domains {
1.852     albertel 8221: 	&load_hosts_tab() if (!$loaded);
                   8222: 
1.841     albertel 8223: 	my %seen;
                   8224: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8225: 	return @uniq;
                   8226:     }
1.1       albertel 8227: }
                   8228: 
1.847     albertel 8229: { 
                   8230:     my %iphost;
1.856     albertel 8231:     my %name_to_ip;
                   8232:     my %lonid_to_ip;
1.869     albertel 8233: 
1.847     albertel 8234:     sub get_hosts_from_ip {
                   8235: 	my ($ip) = @_;
                   8236: 	my %iphosts = &get_iphost();
                   8237: 	if (ref($iphosts{$ip})) {
                   8238: 	    return @{$iphosts{$ip}};
                   8239: 	}
                   8240: 	return;
1.839     albertel 8241:     }
1.864     albertel 8242:     
                   8243:     sub reset_hosts_ip_info {
                   8244: 	undef(%iphost);
                   8245: 	undef(%name_to_ip);
                   8246: 	undef(%lonid_to_ip);
                   8247:     }
1.856     albertel 8248: 
                   8249:     sub get_host_ip {
                   8250: 	my ($lonid) = @_;
                   8251: 	if (exists($lonid_to_ip{$lonid})) {
                   8252: 	    return $lonid_to_ip{$lonid};
                   8253: 	}
                   8254: 	my $name=&hostname($lonid);
                   8255:    	my $ip = gethostbyname($name);
                   8256: 	return if (!$ip || length($ip) ne 4);
                   8257: 	$ip=inet_ntoa($ip);
                   8258: 	$name_to_ip{$name}   = $ip;
                   8259: 	$lonid_to_ip{$lonid} = $ip;
                   8260: 	return $ip;
                   8261:     }
1.847     albertel 8262:     
                   8263:     sub get_iphost {
1.869     albertel 8264: 	my ($ignore_cache) = @_;
1.894     albertel 8265: 
1.869     albertel 8266: 	if (!$ignore_cache) {
                   8267: 	    if (%iphost) {
                   8268: 		return %iphost;
                   8269: 	    }
                   8270: 	    my ($ip_info,$cached)=
                   8271: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8272: 	    if ($cached) {
                   8273: 		%iphost      = %{$ip_info->[0]};
                   8274: 		%name_to_ip  = %{$ip_info->[1]};
                   8275: 		%lonid_to_ip = %{$ip_info->[2]};
                   8276: 		return %iphost;
                   8277: 	    }
                   8278: 	}
1.894     albertel 8279: 
                   8280: 	# get yesterday's info for fallback
                   8281: 	my %old_name_to_ip;
                   8282: 	my ($ip_info,$cached)=
                   8283: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8284: 	if ($cached) {
                   8285: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8286: 	}
                   8287: 
1.888     albertel 8288: 	my %name_to_host = &all_names();
                   8289: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8290: 	    my $ip;
                   8291: 	    if (!exists($name_to_ip{$name})) {
                   8292: 		$ip = gethostbyname($name);
                   8293: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8294: 		    if (defined($old_name_to_ip{$name})) {
                   8295: 			$ip = $old_name_to_ip{$name};
                   8296: 			&logthis("Can't find $name defaulting to old $ip");
                   8297: 		    } else {
                   8298: 			&logthis("Name $name no IP found");
                   8299: 			next;
                   8300: 		    }
                   8301: 		} else {
                   8302: 		    $ip=inet_ntoa($ip);
1.847     albertel 8303: 		}
                   8304: 		$name_to_ip{$name} = $ip;
                   8305: 	    } else {
                   8306: 		$ip = $name_to_ip{$name};
1.653     albertel 8307: 	    }
1.888     albertel 8308: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8309: 		$lonid_to_ip{$id} = $ip;
                   8310: 	    }
                   8311: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8312: 	}
1.869     albertel 8313: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8314: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8315: 				      48*60*60);
1.869     albertel 8316: 
1.847     albertel 8317: 	return %iphost;
1.598     albertel 8318:     }
                   8319: }
                   8320: 
1.862     albertel 8321: BEGIN {
                   8322: 
                   8323: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8324:     unless ($readit) {
                   8325: {
                   8326:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8327:     %perlvar = (%perlvar,%{$configvars});
                   8328: }
                   8329: 
                   8330: 
1.1       albertel 8331: # ------------------------------------------------------ Read spare server file
                   8332: {
1.448     albertel 8333:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8334: 
                   8335:     while (my $configline=<$config>) {
                   8336:        chomp($configline);
1.284     matthew  8337:        if ($configline) {
1.784     albertel 8338: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8339: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8340: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8341:        }
                   8342:     }
1.448     albertel 8343:     close($config);
1.1       albertel 8344: }
1.11      www      8345: # ------------------------------------------------------------ Read permissions
                   8346: {
1.448     albertel 8347:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8348: 
                   8349:     while (my $configline=<$config>) {
1.448     albertel 8350: 	chomp($configline);
                   8351: 	if ($configline) {
                   8352: 	    my ($role,$perm)=split(/ /,$configline);
                   8353: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8354: 	}
1.11      www      8355:     }
1.448     albertel 8356:     close($config);
1.11      www      8357: }
                   8358: 
                   8359: # -------------------------------------------- Read plain texts for permissions
                   8360: {
1.448     albertel 8361:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8362: 
                   8363:     while (my $configline=<$config>) {
1.448     albertel 8364: 	chomp($configline);
                   8365: 	if ($configline) {
1.742     raeburn  8366: 	    my ($short,@plain)=split(/:/,$configline);
                   8367:             %{$prp{$short}} = ();
                   8368: 	    if (@plain > 0) {
                   8369:                 $prp{$short}{'std'} = $plain[0];
                   8370:                 for (my $i=1; $i<@plain; $i++) {
                   8371:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8372:                 }
                   8373:             }
1.448     albertel 8374: 	}
1.135     www      8375:     }
1.448     albertel 8376:     close($config);
1.135     www      8377: }
                   8378: 
                   8379: # ---------------------------------------------------------- Read package table
                   8380: {
1.448     albertel 8381:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8382: 
                   8383:     while (my $configline=<$config>) {
1.483     albertel 8384: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8385: 	chomp($configline);
                   8386: 	my ($short,$plain)=split(/:/,$configline);
                   8387: 	my ($pack,$name)=split(/\&/,$short);
                   8388: 	if ($plain ne '') {
                   8389: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8390: 	    $packagetab{$short}=$plain; 
                   8391: 	}
1.11      www      8392:     }
1.448     albertel 8393:     close($config);
1.329     matthew  8394: }
                   8395: 
                   8396: # ------------- set up temporary directory
                   8397: {
                   8398:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8399: 
1.11      www      8400: }
                   8401: 
1.794     albertel 8402: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8403: 				'compress_threshold'=> 20_000,
                   8404:  			        });
1.185     www      8405: 
1.281     www      8406: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8407: $dumpcount=0;
1.22      www      8408: 
1.163     harris41 8409: &logtouch();
1.672     albertel 8410: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8411: $readit=1;
1.564     albertel 8412:     {
                   8413: 	use integer;
                   8414: 	my $test=(2**32)+1;
1.568     albertel 8415: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8416: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8417:     }
1.195     www      8418: }
1.1       albertel 8419: }
1.179     www      8420: 
1.1       albertel 8421: 1;
1.191     harris41 8422: __END__
                   8423: 
1.243     albertel 8424: =pod
                   8425: 
1.191     harris41 8426: =head1 NAME
                   8427: 
1.243     albertel 8428: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8429: 
                   8430: =head1 SYNOPSIS
                   8431: 
1.243     albertel 8432: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8433: 
                   8434:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8435: 
1.243     albertel 8436: Common parameters:
                   8437: 
                   8438: =over 4
                   8439: 
                   8440: =item *
                   8441: 
                   8442: $uname : an internal username (if $cname expecting a course Id specifically)
                   8443: 
                   8444: =item *
                   8445: 
                   8446: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8447: 
                   8448: =item *
                   8449: 
                   8450: $symb : a resource instance identifier
                   8451: 
                   8452: =item *
                   8453: 
                   8454: $namespace : the name of a .db file that contains the data needed or
                   8455: being set.
                   8456: 
                   8457: =back
                   8458: 
1.394     bowersj2 8459: =head1 OVERVIEW
1.191     harris41 8460: 
1.394     bowersj2 8461: lonnet provides subroutines which interact with the
                   8462: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8463: about classes, users, and resources.
1.243     albertel 8464: 
                   8465: For many of these objects you can also use this to store data about
                   8466: them or modify them in various ways.
1.191     harris41 8467: 
1.394     bowersj2 8468: =head2 Symbs
1.191     harris41 8469: 
1.394     bowersj2 8470: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8471: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8472: map, the resource number of the resource in the map, and the URL of
                   8473: the resource itself. The latter is somewhat redundant, but might help
                   8474: if maps change.
                   8475: 
                   8476: An example is
                   8477: 
                   8478:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8479: 
                   8480: The respective map entry is
                   8481: 
                   8482:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8483:   title="Problem 2">
                   8484:  </resource>
                   8485: 
                   8486: Symbs are used by the random number generator, as well as to store and
                   8487: restore data specific to a certain instance of for example a problem.
                   8488: 
                   8489: =head2 Storing And Retrieving Data
                   8490: 
                   8491: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8492: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8493: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8494: is is the non-critical message twin of cstore. These functions are for
                   8495: handlers to store a perl hash to a user's permanent data space in an
                   8496: easy manner, and to retrieve it again on another call. It is expected
                   8497: that a handler would use this once at the beginning to retrieve data,
                   8498: and then again once at the end to send only the new data back.
                   8499: 
                   8500: The data is stored in the user's data directory on the user's
                   8501: homeserver under the ID of the course.
                   8502: 
                   8503: The hash that is returned by restore will have all of the previous
                   8504: value for all of the elements of the hash.
                   8505: 
                   8506: Example:
                   8507: 
                   8508:  #creating a hash
                   8509:  my %hash;
                   8510:  $hash{'foo'}='bar';
                   8511: 
                   8512:  #storing it
                   8513:  &Apache::lonnet::cstore(\%hash);
                   8514: 
                   8515:  #changing a value
                   8516:  $hash{'foo'}='notbar';
                   8517: 
                   8518:  #adding a new value
                   8519:  $hash{'bar'}='foo';
                   8520:  &Apache::lonnet::cstore(\%hash);
                   8521: 
                   8522:  #retrieving the hash
                   8523:  my %history=&Apache::lonnet::restore();
                   8524: 
                   8525:  #print the hash
                   8526:  foreach my $key (sort(keys(%history))) {
                   8527:    print("\%history{$key} = $history{$key}");
                   8528:  }
                   8529: 
                   8530: Will print out:
1.191     harris41 8531: 
1.394     bowersj2 8532:  %history{1:foo} = bar
                   8533:  %history{1:keys} = foo:timestamp
                   8534:  %history{1:timestamp} = 990455579
                   8535:  %history{2:bar} = foo
                   8536:  %history{2:foo} = notbar
                   8537:  %history{2:keys} = foo:bar:timestamp
                   8538:  %history{2:timestamp} = 990455580
                   8539:  %history{bar} = foo
                   8540:  %history{foo} = notbar
                   8541:  %history{timestamp} = 990455580
                   8542:  %history{version} = 2
                   8543: 
                   8544: Note that the special hash entries C<keys>, C<version> and
                   8545: C<timestamp> were added to the hash. C<version> will be equal to the
                   8546: total number of versions of the data that have been stored. The
                   8547: C<timestamp> attribute will be the UNIX time the hash was
                   8548: stored. C<keys> is available in every historical section to list which
                   8549: keys were added or changed at a specific historical revision of a
                   8550: hash.
                   8551: 
                   8552: B<Warning>: do not store the hash that restore returns directly. This
                   8553: will cause a mess since it will restore the historical keys as if the
                   8554: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8555: 
1.394     bowersj2 8556: Calling convention:
1.191     harris41 8557: 
1.394     bowersj2 8558:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8559:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8560: 
1.394     bowersj2 8561: For more detailed information, see lonnet specific documentation.
1.191     harris41 8562: 
1.394     bowersj2 8563: =head1 RETURN MESSAGES
1.191     harris41 8564: 
1.394     bowersj2 8565: =over 4
1.191     harris41 8566: 
1.394     bowersj2 8567: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8568: 
1.394     bowersj2 8569: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8570: when the connection is brought back up
1.191     harris41 8571: 
1.394     bowersj2 8572: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8573: for later delivery
1.191     harris41 8574: 
1.394     bowersj2 8575: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8576: 
1.394     bowersj2 8577: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8578: that was requested
1.191     harris41 8579: 
1.243     albertel 8580: =back
1.191     harris41 8581: 
1.243     albertel 8582: =head1 PUBLIC SUBROUTINES
1.191     harris41 8583: 
1.243     albertel 8584: =head2 Session Environment Functions
1.191     harris41 8585: 
1.243     albertel 8586: =over 4
1.191     harris41 8587: 
1.394     bowersj2 8588: =item * 
                   8589: X<appenv()>
                   8590: B<appenv(%hash)>: the value of %hash is written to
                   8591: the user envirnoment file, and will be restored for each access this
1.620     albertel 8592: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8593: process
1.191     harris41 8594: 
                   8595: =item *
1.394     bowersj2 8596: X<delenv()>
                   8597: B<delenv($regexp)>: removes all items from the session
                   8598: environment file that matches the regular expression in $regexp. The
1.620     albertel 8599: values are also delted from the current processes %env.
1.191     harris41 8600: 
1.795     albertel 8601: =item * get_env_multiple($name) 
                   8602: 
                   8603: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8604: values may be defined and end up as an array ref.
                   8605: 
                   8606: returns an array of values
                   8607: 
1.243     albertel 8608: =back
                   8609: 
                   8610: =head2 User Information
1.191     harris41 8611: 
1.243     albertel 8612: =over 4
1.191     harris41 8613: 
                   8614: =item *
1.394     bowersj2 8615: X<queryauthenticate()>
                   8616: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8617: authentication scheme
                   8618: 
                   8619: =item *
1.394     bowersj2 8620: X<authenticate()>
                   8621: B<authenticate($uname,$upass,$udom)>: try to
                   8622: authenticate user from domain's lib servers (first use the current
                   8623: one). C<$upass> should be the users password.
1.191     harris41 8624: 
                   8625: =item *
1.394     bowersj2 8626: X<homeserver()>
                   8627: B<homeserver($uname,$udom)>: find the server which has
                   8628: the user's directory and files (there must be only one), this caches
                   8629: the answer, and also caches if there is a borken connection.
1.191     harris41 8630: 
                   8631: =item *
1.394     bowersj2 8632: X<idget()>
                   8633: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8634: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8635: username, and only 1 username per ID in a specific domain) (returns
                   8636: hash: id=>name,id=>name)
1.191     harris41 8637: 
                   8638: =item *
1.394     bowersj2 8639: X<idrget()>
                   8640: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8641: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8642: 
                   8643: =item *
1.394     bowersj2 8644: X<idput()>
                   8645: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8646: 
                   8647: =item *
1.394     bowersj2 8648: X<rolesinit()>
                   8649: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8650: 
                   8651: =item *
1.551     albertel 8652: X<getsection()>
                   8653: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8654: course $cname, return section name/number or '' for "not in course"
                   8655: and '-1' for "no section"
                   8656: 
                   8657: =item *
1.394     bowersj2 8658: X<userenvironment()>
                   8659: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8660: passed in @what from the requested user's environment, returns a hash
                   8661: 
1.858     raeburn  8662: =item * 
                   8663: X<userlog_query()>
1.859     albertel 8664: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8665: activity.log file. %filters defines filters applied when parsing the
                   8666: log file. These can be start or end timestamps, or the type of action
                   8667: - log to look for Login or Logout events, check for Checkin or
                   8668: Checkout, role for role selection. The response is in the form
                   8669: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8670: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8671: 
1.243     albertel 8672: =back
                   8673: 
                   8674: =head2 User Roles
                   8675: 
                   8676: =over 4
                   8677: 
                   8678: =item *
                   8679: 
1.810     raeburn  8680: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8681:  F: full access
                   8682:  U,I,K: authentication modes (cxx only)
                   8683:  '': forbidden
                   8684:  1: user needs to choose course
                   8685:  2: browse allowed
1.766     albertel 8686:  A: passphrase authentication needed
1.243     albertel 8687: 
                   8688: =item *
                   8689: 
                   8690: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8691: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8692: and course level
                   8693: 
                   8694: =item *
                   8695: 
                   8696: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8697: explanation of a user role term
                   8698: 
1.832     raeburn  8699: =item *
                   8700: 
1.858     raeburn  8701: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8702: All arguments are optional. Returns a hash of a roles, either for
                   8703: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8704: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8705: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8706: and value is set to colon-separated start and end times for the role.
                   8707: If no username and domain are specified, will default to current
                   8708: user/domain. Types, roles, and roledoms are references to arrays,
                   8709: of role statuses (active, future or previous), roles 
                   8710: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8711: to restrict the list of roles reported. If no array ref is 
                   8712: provided for types, will default to return only active roles.
1.834     albertel 8713: 
1.243     albertel 8714: =back
                   8715: 
                   8716: =head2 User Modification
                   8717: 
                   8718: =over 4
                   8719: 
                   8720: =item *
                   8721: 
                   8722: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8723: user for the level given by URL.  Optional start and end dates (leave empty
                   8724: string or zero for "no date")
1.191     harris41 8725: 
                   8726: =item *
                   8727: 
1.243     albertel 8728: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8729: change a users, password, possible return values are: ok,
                   8730: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8731: refused
1.191     harris41 8732: 
                   8733: =item *
                   8734: 
1.243     albertel 8735: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8736: 
                   8737: =item *
                   8738: 
1.243     albertel 8739: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8740: modify user
1.191     harris41 8741: 
                   8742: =item *
                   8743: 
1.286     matthew  8744: modifystudent
                   8745: 
                   8746: modify a students enrollment and identification information.
                   8747: The course id is resolved based on the current users environment.  
                   8748: This means the envoking user must be a course coordinator or otherwise
                   8749: associated with a course.
                   8750: 
1.297     matthew  8751: This call is essentially a wrapper for lonnet::modifyuser and
                   8752: lonnet::modify_student_enrollment
1.286     matthew  8753: 
                   8754: Inputs: 
                   8755: 
                   8756: =over 4
                   8757: 
                   8758: =item B<$udom> Students loncapa domain
                   8759: 
                   8760: =item B<$uname> Students loncapa login name
                   8761: 
                   8762: =item B<$uid> Students id/student number
                   8763: 
                   8764: =item B<$umode> Students authentication mode
                   8765: 
                   8766: =item B<$upass> Students password
                   8767: 
                   8768: =item B<$first> Students first name
                   8769: 
                   8770: =item B<$middle> Students middle name
                   8771: 
                   8772: =item B<$last> Students last name
                   8773: 
                   8774: =item B<$gene> Students generation
                   8775: 
                   8776: =item B<$usec> Students section in course
                   8777: 
                   8778: =item B<$end> Unix time of the roles expiration
                   8779: 
                   8780: =item B<$start> Unix time of the roles start date
                   8781: 
                   8782: =item B<$forceid> If defined, allow $uid to be changed
                   8783: 
                   8784: =item B<$desiredhome> server to use as home server for student
                   8785: 
                   8786: =back
1.297     matthew  8787: 
                   8788: =item *
                   8789: 
                   8790: modify_student_enrollment
                   8791: 
                   8792: Change a students enrollment status in a class.  The environment variable
                   8793: 'role.request.course' must be defined for this function to proceed.
                   8794: 
                   8795: Inputs:
                   8796: 
                   8797: =over 4
                   8798: 
                   8799: =item $udom, students domain
                   8800: 
                   8801: =item $uname, students name
                   8802: 
                   8803: =item $uid, students user id
                   8804: 
                   8805: =item $first, students first name
                   8806: 
                   8807: =item $middle
                   8808: 
                   8809: =item $last
                   8810: 
                   8811: =item $gene
                   8812: 
                   8813: =item $usec
                   8814: 
                   8815: =item $end
                   8816: 
                   8817: =item $start
                   8818: 
                   8819: =back
                   8820: 
1.191     harris41 8821: 
                   8822: =item *
                   8823: 
1.243     albertel 8824: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8825: custom role; give a custom role to a user for the level given by URL.  Specify
                   8826: name and domain of role author, and role name
1.191     harris41 8827: 
                   8828: =item *
                   8829: 
1.243     albertel 8830: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8831: 
                   8832: =item *
                   8833: 
1.243     albertel 8834: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8835: 
                   8836: =back
                   8837: 
                   8838: =head2 Course Infomation
                   8839: 
                   8840: =over 4
1.191     harris41 8841: 
                   8842: =item *
                   8843: 
1.631     albertel 8844: coursedescription($courseid) : returns a hash of information about the
                   8845: specified course id, including all environment settings for the
                   8846: course, the description of the course will be in the hash under the
                   8847: key 'description'
1.191     harris41 8848: 
                   8849: =item *
                   8850: 
1.624     albertel 8851: resdata($name,$domain,$type,@which) : request for current parameter
                   8852: setting for a specific $type, where $type is either 'course' or 'user',
                   8853: @what should be a list of parameters to ask about. This routine caches
                   8854: answers for 5 minutes.
1.243     albertel 8855: 
1.877     foxr     8856: =item *
                   8857: 
                   8858: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8859: data base, returning a hash that is keyed by the resource name and has
                   8860: values that are the resource value.  I believe that the timestamps and
                   8861: versions are also returned.
                   8862: 
                   8863: 
1.243     albertel 8864: =back
                   8865: 
                   8866: =head2 Course Modification
                   8867: 
                   8868: =over 4
1.191     harris41 8869: 
                   8870: =item *
                   8871: 
1.243     albertel 8872: writecoursepref($courseid,%prefs) : write preferences (environment
                   8873: database) for a course
1.191     harris41 8874: 
                   8875: =item *
                   8876: 
1.243     albertel 8877: createcourse($udom,$description,$url) : make/modify course
                   8878: 
                   8879: =back
                   8880: 
                   8881: =head2 Resource Subroutines
                   8882: 
                   8883: =over 4
1.191     harris41 8884: 
                   8885: =item *
                   8886: 
1.243     albertel 8887: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8888: 
                   8889: =item *
                   8890: 
1.243     albertel 8891: repcopy($filename) : subscribes to the requested file, and attempts to
                   8892: replicate from the owning library server, Might return
1.607     raeburn  8893: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8894: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8895: resource. Expects the local filesystem pathname
                   8896: (/home/httpd/html/res/....)
                   8897: 
                   8898: =back
                   8899: 
                   8900: =head2 Resource Information
                   8901: 
                   8902: =over 4
1.191     harris41 8903: 
                   8904: =item *
                   8905: 
1.243     albertel 8906: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8907: a vairety of different possible values, $varname should be a request
                   8908: string, and the other parameters can be used to specify who and what
                   8909: one is asking about.
                   8910: 
                   8911: Possible values for $varname are environment.lastname (or other item
                   8912: from the envirnment hash), user.name (or someother aspect about the
                   8913: user), resource.0.maxtries (or some other part and parameter of a
                   8914: resource)
1.204     albertel 8915: 
                   8916: =item *
                   8917: 
1.243     albertel 8918: directcondval($number) : get current value of a condition; reads from a state
                   8919: string
1.204     albertel 8920: 
                   8921: =item *
                   8922: 
1.243     albertel 8923: condval($condidx) : value of condition index based on state
1.204     albertel 8924: 
                   8925: =item *
                   8926: 
1.243     albertel 8927: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8928: resource's metadata, $what should be either a specific key, or either
                   8929: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8930: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8931: 
                   8932: this function automatically caches all requests
1.191     harris41 8933: 
                   8934: =item *
                   8935: 
1.243     albertel 8936: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8937: network of library servers; returns file handle of where SQL and regex results
                   8938: will be stored for query
1.191     harris41 8939: 
                   8940: =item *
                   8941: 
1.243     albertel 8942: symbread($filename) : return symbolic list entry (filename argument optional);
                   8943: returns the data handle
1.191     harris41 8944: 
                   8945: =item *
                   8946: 
1.243     albertel 8947: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8948: a possible symb for the URL in $thisfn, and if is an encryypted
                   8949: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8950: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8951: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8952: 
1.191     harris41 8953: 
                   8954: =item *
                   8955: 
1.243     albertel 8956: symbclean($symb) : removes versions numbers from a symb, returns the
                   8957: cleaned symb
1.191     harris41 8958: 
                   8959: =item *
                   8960: 
1.243     albertel 8961: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8962: course map, user must be in a course for it to work.
1.191     harris41 8963: 
                   8964: =item *
                   8965: 
1.243     albertel 8966: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8967: 
                   8968: =item *
                   8969: 
1.243     albertel 8970: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8971: a random seed, all arguments are optional, if they aren't sent it uses the
                   8972: environment to derive them. Note: if symb isn't sent and it can't get one
                   8973: from &symbread it will use the current time as its return value
1.191     harris41 8974: 
                   8975: =item *
                   8976: 
1.243     albertel 8977: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8978: unfakeable, receipt
1.191     harris41 8979: 
                   8980: =item *
                   8981: 
1.620     albertel 8982: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8983: 
                   8984: =item *
                   8985: 
1.243     albertel 8986: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8987: 
                   8988: =item *
                   8989: 
1.243     albertel 8990: 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 8991: 
                   8992: =item *
                   8993: 
1.243     albertel 8994: 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 8995: 
                   8996: =item *
                   8997: 
1.243     albertel 8998: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8999: 
                   9000: =item *
                   9001: 
1.243     albertel 9002: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9003: forcing spreadsheet to reevaluate the resource scores next time.
                   9004: 
                   9005: =back
                   9006: 
                   9007: =head2 Storing/Retreiving Data
                   9008: 
                   9009: =over 4
1.191     harris41 9010: 
                   9011: =item *
                   9012: 
1.243     albertel 9013: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9014: for this url; hashref needs to be given and should be a \%hashname; the
                   9015: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9016: be derived from the env
1.191     harris41 9017: 
                   9018: =item *
                   9019: 
1.243     albertel 9020: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9021: uses critical subroutine
1.191     harris41 9022: 
                   9023: =item *
                   9024: 
1.243     albertel 9025: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9026: all args are optional
1.191     harris41 9027: 
                   9028: =item *
                   9029: 
1.717     albertel 9030: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9031: dumps the complete (or key matching regexp) namespace into a hash
                   9032: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9033: normally &store()ed into
                   9034: 
                   9035: $range should be either an integer '100' (give me the first 100
                   9036:                                            matching records)
                   9037:               or be  two integers sperated by a - with no spaces
                   9038:                  '30-50' (give me the 30th through the 50th matching
                   9039:                           records)
                   9040: 
                   9041: 
                   9042: =item *
                   9043: 
                   9044: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9045: replaces a &store() version of data with a replacement set of data
                   9046: for a particular resource in a namespace passed in the $storehash hash 
                   9047: reference
                   9048: 
                   9049: =item *
                   9050: 
1.243     albertel 9051: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9052: works very similar to store/cstore, but all data is stored in a
                   9053: temporary location and can be reset using tmpreset, $storehash should
                   9054: be a hash reference, returns nothing on success
1.191     harris41 9055: 
                   9056: =item *
                   9057: 
1.243     albertel 9058: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9059: similar to restore, but all data is stored in a temporary location and
                   9060: can be reset using tmpreset. Returns a hash of values on success,
                   9061: error string otherwise.
1.191     harris41 9062: 
                   9063: =item *
                   9064: 
1.243     albertel 9065: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9066: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9067: 
                   9068: =item *
                   9069: 
1.243     albertel 9070: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9071: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9072: 
                   9073: =item *
                   9074: 
1.243     albertel 9075: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9076: namesp ($udom and $uname are optional)
1.191     harris41 9077: 
                   9078: =item *
                   9079: 
1.702     albertel 9080: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9081: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9082: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9083: 
1.702     albertel 9084: $range should be either an integer '100' (give me the first 100
                   9085:                                            matching records)
                   9086:               or be  two integers sperated by a - with no spaces
                   9087:                  '30-50' (give me the 30th through the 50th matching
                   9088:                           records)
1.449     matthew  9089: =item *
                   9090: 
                   9091: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9092: $store can be a scalar, an array reference, or if the amount to be 
                   9093: incremented is > 1, a hash reference.
                   9094: 
                   9095: ($udom and $uname are optional)
1.191     harris41 9096: 
                   9097: =item *
                   9098: 
1.243     albertel 9099: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9100: ($udom and $uname are optional)
1.191     harris41 9101: 
                   9102: =item *
                   9103: 
1.243     albertel 9104: cput($namespace,$storehash,$udom,$uname) : critical put
                   9105: ($udom and $uname are optional)
1.191     harris41 9106: 
                   9107: =item *
                   9108: 
1.748     albertel 9109: newput($namespace,$storehash,$udom,$uname) :
                   9110: 
                   9111: Attempts to store the items in the $storehash, but only if they don't
                   9112: currently exist, if this succeeds you can be certain that you have 
                   9113: successfully created a new key value pair in the $namespace db.
                   9114: 
                   9115: 
                   9116: Args:
                   9117:  $namespace: name of database to store values to
                   9118:  $storehash: hashref to store to the db
                   9119:  $udom: (optional) domain of user containing the db
                   9120:  $uname: (optional) name of user caontaining the db
                   9121: 
                   9122: Returns:
                   9123:  'ok' -> succeeded in storing all keys of $storehash
                   9124:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9125:                         least <key> already existed in the db (other
                   9126:                         requested keys may also already exist)
                   9127:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9128:  'con_lost' -> unable to contact request server
                   9129:  'refused' -> action was not allowed by remote machine
                   9130: 
                   9131: 
                   9132: =item *
                   9133: 
1.243     albertel 9134: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9135: reference filled in from namesp (encrypts the return communication)
                   9136: ($udom and $uname are optional)
1.191     harris41 9137: 
                   9138: =item *
                   9139: 
1.243     albertel 9140: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9141: critical subroutine
                   9142: 
1.806     raeburn  9143: =item *
                   9144: 
1.860     raeburn  9145: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9146: array reference filled in from namespace found in domain level on either
                   9147: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9148: 
                   9149: =item *
                   9150: 
1.860     raeburn  9151: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9152: domain level either on specified domain server ($uhome) or primary domain 
                   9153: server ($udom and $uhome are optional)
1.806     raeburn  9154: 
1.243     albertel 9155: =back
                   9156: 
                   9157: =head2 Network Status Functions
                   9158: 
                   9159: =over 4
1.191     harris41 9160: 
                   9161: =item *
                   9162: 
                   9163: dirlist($uri) : return directory list based on URI
                   9164: 
                   9165: =item *
                   9166: 
1.243     albertel 9167: spareserver() : find server with least workload from spare.tab
                   9168: 
                   9169: =back
                   9170: 
                   9171: =head2 Apache Request
                   9172: 
                   9173: =over 4
1.191     harris41 9174: 
                   9175: =item *
                   9176: 
1.243     albertel 9177: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9178: localhost, posts hash
                   9179: 
                   9180: =back
                   9181: 
                   9182: =head2 Data to String to Data
                   9183: 
                   9184: =over 4
1.191     harris41 9185: 
                   9186: =item *
                   9187: 
1.243     albertel 9188: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9189: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9190: 
                   9191: =item *
                   9192: 
1.243     albertel 9193: hashref2str($hashref) : convert a hashref into a string complete with
                   9194: escaping and '=' and '&' separators, supports elements that are
                   9195: arrayrefs and hashrefs
1.191     harris41 9196: 
                   9197: =item *
                   9198: 
1.243     albertel 9199: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9200: with escaping and '&' separators, supports elements that are arrayrefs
                   9201: and hashrefs
1.191     harris41 9202: 
                   9203: =item *
                   9204: 
1.243     albertel 9205: str2hash($string) : convert string to hash using unescaping and
                   9206: splitting on '=' and '&', supports elements that are arrayrefs and
                   9207: hashrefs
1.191     harris41 9208: 
                   9209: =item *
                   9210: 
1.243     albertel 9211: str2array($string) : convert string to hash using unescaping and
                   9212: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9213: 
                   9214: =back
                   9215: 
                   9216: =head2 Logging Routines
                   9217: 
                   9218: =over 4
                   9219: 
                   9220: These routines allow one to make log messages in the lonnet.log and
                   9221: lonnet.perm logfiles.
1.191     harris41 9222: 
                   9223: =item *
                   9224: 
1.243     albertel 9225: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9226: 
                   9227: =item *
                   9228: 
1.243     albertel 9229: logthis() : append message to the normal lonnet.log file, it gets
                   9230: preiodically rolled over and deleted.
1.191     harris41 9231: 
                   9232: =item *
                   9233: 
1.243     albertel 9234: logperm() : append a permanent message to lonnet.perm.log, this log
                   9235: file never gets deleted by any automated portion of the system, only
                   9236: messages of critical importance should go in here.
                   9237: 
                   9238: =back
                   9239: 
                   9240: =head2 General File Helper Routines
                   9241: 
                   9242: =over 4
1.191     harris41 9243: 
                   9244: =item *
                   9245: 
1.481     raeburn  9246: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9247: (a) files in /uploaded
                   9248:   (i) If a local copy of the file exists - 
                   9249:       compares modification date of local copy with last-modified date for 
                   9250:       definitive version stored on home server for course. If local copy is 
                   9251:       stale, requests a new version from the home server and stores it. 
                   9252:       If the original has been removed from the home server, then local copy 
                   9253:       is unlinked.
                   9254:   (ii) If local copy does not exist -
                   9255:       requests the file from the home server and stores it. 
                   9256:   
                   9257:   If $caller is 'uploadrep':  
                   9258:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9259:     for request for files originally uploaded via DOCS. 
                   9260:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9261:   
                   9262:   Otherwise:
                   9263:      This indicates a call from the content generation phase of the request.
                   9264:      -  returns the entire contents of the file or -1.
                   9265:      
                   9266: (b) files in /res
                   9267:    - returns the entire contents of a file or -1; 
                   9268:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9269: 
1.712     albertel 9270: 
                   9271: =item *
                   9272: 
                   9273: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9274:                   reference
                   9275: 
                   9276: returns either a stat() list of data about the file or an empty list
                   9277: if the file doesn't exist or couldn't find out about it (connection
                   9278: problems or user unknown)
                   9279: 
1.191     harris41 9280: =item *
                   9281: 
1.243     albertel 9282: filelocation($dir,$file) : returns file system location of a file
                   9283: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9284: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9285: and a file of ../bob will become /a/bob)
1.191     harris41 9286: 
                   9287: =item *
                   9288: 
                   9289: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9290: filelocation except for hrefs
                   9291: 
                   9292: =item *
                   9293: 
                   9294: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9295: 
1.243     albertel 9296: =back
                   9297: 
1.608     albertel 9298: =head2 Usererfile file routines (/uploaded*)
                   9299: 
                   9300: =over 4
                   9301: 
                   9302: =item *
                   9303: 
                   9304: userfileupload(): main rotine for putting a file in a user or course's
                   9305:                   filespace, arguments are,
                   9306: 
1.620     albertel 9307:  formname - required - this is the name of the element in $env where the
1.608     albertel 9308:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9309:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9310:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9311:  coursedoc - if true, store the file in the course of the active role
                   9312:              of the current user
                   9313:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9314:          if undefined, it will be placed in "unknown"
                   9315: 
                   9316:  (This routine calls clean_filename() to remove any dangerous
                   9317:  characters from the filename, and then calls finuserfileupload() to
                   9318:  complete the transaction)
                   9319: 
                   9320:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9321:  and /adm/notfound.html if unsuccessful
                   9322: 
                   9323: =item *
                   9324: 
                   9325: clean_filename(): routine for cleaing a filename up for storage in
                   9326:                  userfile space, argument is:
                   9327: 
                   9328:  filename - proposed filename
                   9329: 
                   9330: returns: the new clean filename
                   9331: 
                   9332: =item *
                   9333: 
                   9334: finishuserfileupload(): routine that creaes and sends the file to
                   9335: userspace, probably shouldn't be called directly
                   9336: 
                   9337:   docuname: username or courseid of destination for the file
                   9338:   docudom: domain of user/course of destination for the file
                   9339:   formname: same as for userfileupload()
                   9340:   fname: filename (inculding subdirectories) for the file
                   9341: 
                   9342:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9343:  and /adm/notfound.html if unsuccessful
                   9344: 
                   9345: =item *
                   9346: 
                   9347: renameuserfile(): renames an existing userfile to a new name
                   9348: 
                   9349:   Args:
                   9350:    docuname: username or courseid of destination for the file
                   9351:    docudom: domain of user/course of destination for the file
                   9352:    old: current file name (including any subdirs under userfiles)
                   9353:    new: desired file name (including any subdirs under userfiles)
                   9354: 
                   9355: =item *
                   9356: 
                   9357: mkdiruserfile(): creates a directory is a userfiles dir
                   9358: 
                   9359:   Args:
                   9360:    docuname: username or courseid of destination for the file
                   9361:    docudom: domain of user/course of destination for the file
                   9362:    dir: dir to create (including any subdirs under userfiles)
                   9363: 
                   9364: =item *
                   9365: 
                   9366: removeuserfile(): removes a file that exists in userfiles
                   9367: 
                   9368:   Args:
                   9369:    docuname: username or courseid of destination for the file
                   9370:    docudom: domain of user/course of destination for the file
                   9371:    fname: filname to delete (including any subdirs under userfiles)
                   9372: 
                   9373: =item *
                   9374: 
                   9375: removeuploadedurl(): convience function for removeuserfile()
                   9376: 
                   9377:   Args:
                   9378:    url:  a full /uploaded/... url to delete
                   9379: 
1.747     albertel 9380: =item * 
                   9381: 
                   9382: get_portfile_permissions():
                   9383:   Args:
                   9384:     domain: domain of user or course contain the portfolio files
                   9385:     user: name of user or num of course contain the portfolio files
                   9386:   Returns:
                   9387:     hashref of a dump of the proper file_permissions.db
                   9388:    
                   9389: 
                   9390: =item * 
                   9391: 
                   9392: get_access_controls():
                   9393: 
                   9394: Args:
                   9395:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9396:   group: (optional) the group you want the files associated with
                   9397:   file: (optional) the file you want access info on
                   9398: 
                   9399: Returns:
1.749     raeburn  9400:     a hash (keys are file names) of hashes containing
                   9401:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9402:         values are XML containing access control settings (see below) 
1.747     albertel 9403: 
                   9404: Internal notes:
                   9405: 
1.749     raeburn  9406:  access controls are stored in file_permissions.db as key=value pairs.
                   9407:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9408:         where scope -> public,guest,course,group,domains or users.
                   9409:               end -> UNIX time for end of access (0 -> no end date)
                   9410:               start -> UNIX time for start of access
                   9411: 
                   9412:     value -> XML description of access control
                   9413:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9414:             <start></start>
                   9415:             <end></end>
                   9416: 
                   9417:             <password></password>  for scope type = guest
                   9418: 
                   9419:             <domain></domain>     for scope type = course or group
                   9420:             <number></number>
                   9421:             <roles id="">
                   9422:              <role></role>
                   9423:              <access></access>
                   9424:              <section></section>
                   9425:              <group></group>
                   9426:             </roles>
                   9427: 
                   9428:             <dom></dom>         for scope type = domains
                   9429: 
                   9430:             <users>             for scope type = users
                   9431:              <user>
                   9432:               <uname></uname>
                   9433:               <udom></udom>
                   9434:              </user>
                   9435:             </users>
                   9436:            </scope> 
                   9437:               
                   9438:  Access data is also aggregated for each file in an additional key=value pair:
                   9439:  key -> path to file/file_name\0accesscontrol 
                   9440:  value -> reference to hash
                   9441:           hash contains key = value pairs
                   9442:           where key = uniqueID:scope_end_start
                   9443:                 value = UNIX time record was last updated
                   9444: 
                   9445:           Used to improve speed of look-ups of access controls for each file.  
                   9446:  
                   9447:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9448: 
                   9449: modify_access_controls():
                   9450: 
                   9451: Modifies access controls for a portfolio file
                   9452: Args
                   9453: 1. file name
                   9454: 2. reference to hash of required changes,
                   9455: 3. domain
                   9456: 4. username
                   9457:   where domain,username are the domain of the portfolio owner 
                   9458:   (either a user or a course) 
                   9459: 
                   9460: Returns:
                   9461: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9462: 2. result of deletions ('ok' or 'error', with error message).
                   9463: 3. reference to hash of any new or updated access controls.
                   9464: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9465:    key = integer (inbound ID)
                   9466:    value = uniqueID  
1.747     albertel 9467: 
1.608     albertel 9468: =back
                   9469: 
1.243     albertel 9470: =head2 HTTP Helper Routines
                   9471: 
                   9472: =over 4
                   9473: 
1.191     harris41 9474: =item *
                   9475: 
                   9476: escape() : unpack non-word characters into CGI-compatible hex codes
                   9477: 
                   9478: =item *
                   9479: 
                   9480: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9481: 
1.243     albertel 9482: =back
                   9483: 
                   9484: =head1 PRIVATE SUBROUTINES
                   9485: 
                   9486: =head2 Underlying communication routines (Shouldn't call)
                   9487: 
                   9488: =over 4
                   9489: 
                   9490: =item *
                   9491: 
                   9492: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9493: 
                   9494: =item *
                   9495: 
                   9496: reply() : uses subreply to send a message to remote machine, logs all failures
                   9497: 
                   9498: =item *
                   9499: 
                   9500: critical() : passes a critical message to another server; if cannot
                   9501: get through then place message in connection buffer directory and
                   9502: returns con_delayed, if incapable of saving message, returns
                   9503: con_failed
                   9504: 
                   9505: =item *
                   9506: 
                   9507: reconlonc() : tries to reconnect lonc client processes.
                   9508: 
                   9509: =back
                   9510: 
                   9511: =head2 Resource Access Logging
                   9512: 
                   9513: =over 4
                   9514: 
                   9515: =item *
                   9516: 
                   9517: flushcourselogs() : flush (save) buffer logs and access logs
                   9518: 
                   9519: =item *
                   9520: 
                   9521: courselog($what) : save message for course in hash
                   9522: 
                   9523: =item *
                   9524: 
                   9525: courseacclog($what) : save message for course using &courselog().  Perform
                   9526: special processing for specific resource types (problems, exams, quizzes, etc).
                   9527: 
1.191     harris41 9528: =item *
                   9529: 
                   9530: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9531: as a PerlChildExitHandler
1.243     albertel 9532: 
                   9533: =back
                   9534: 
                   9535: =head2 Other
                   9536: 
                   9537: =over 4
                   9538: 
                   9539: =item *
                   9540: 
                   9541: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9542: 
                   9543: =back
                   9544: 
                   9545: =cut
1.877     foxr     9546: 

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