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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.921   ! raeburn     4: # $Id: lonnet.pm,v 1.920 2007/10/04 19:59:16 raeburn 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:     {
1.917     albertel  323: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    324: 	if (!$opened) {
1.915     albertel  325: 	    return 0;
                    326: 	}
1.783     albertel  327: 	flock($idf,LOCK_SH);
                    328: 	@profile=<$idf>;
                    329: 	close($idf);
                    330:     }
                    331:     my %temp_env;
                    332:     foreach my $line (@profile) {
1.786     albertel  333: 	if ($line !~ m/=/) {
                    334: 	    return 0;
                    335: 	}
1.783     albertel  336: 	chomp($line);
                    337: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    338: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    339:     }
                    340:     unlink("$lonidsdir/$handle.id");
                    341:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    342: 	    0640)) {
                    343: 	%disk_env = %temp_env;
                    344: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    345: 	untie(%disk_env);
                    346:     }
1.786     albertel  347:     return 1;
1.783     albertel  348: }
                    349: 
1.374     www       350: # ------------------------------------------- Transfer profile into environment
1.780     albertel  351: my $env_loaded;
                    352: sub transfer_profile_to_env {
1.788     albertel  353:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    354:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       355: 
1.720     albertel  356:     if (!defined($lonidsdir)) {
                    357: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    358:     }
                    359:     if (!defined($handle)) {
                    360:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    361:     }
                    362: 
1.786     albertel  363:     my $convert;
                    364:     {
1.917     albertel  365:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    366: 	if (!$opened) {
1.915     albertel  367: 	    return;
                    368: 	}
1.786     albertel  369: 	flock($idf,LOCK_SH);
                    370: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    371: 		&GDBM_READER(),0640)) {
                    372: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    373: 	    untie(%disk_env);
                    374: 	} else {
                    375: 	    $convert = 1;
                    376: 	}
                    377:     }
                    378:     if ($convert) {
                    379: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    380: 	    &logthis("Failed to load session, or convert session.");
                    381: 	}
1.374     www       382:     }
1.783     albertel  383: 
1.786     albertel  384:     my %remove;
1.783     albertel  385:     while ( my $envname = each(%env) ) {
1.433     matthew   386:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    387:             if ($time < time-300) {
1.783     albertel  388:                 $remove{$key}++;
1.433     matthew   389:             }
                    390:         }
                    391:     }
1.783     albertel  392: 
1.619     albertel  393:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  394:     $env_loaded=1;
1.783     albertel  395:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   396:         &delenv($expired_key);
1.374     www       397:     }
1.1       albertel  398: }
                    399: 
1.916     albertel  400: # ---------------------------------------------------- Check for valid session 
                    401: sub check_for_valid_session {
                    402:     my ($r) = @_;
                    403:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    404:     my $lonid=$cookies{'lonID'};
                    405:     return undef if (!$lonid);
                    406: 
                    407:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    408:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    409:     return undef if (!-e "$lonidsdir/$handle.id");
                    410: 
1.917     albertel  411:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    412:     return undef if (!$opened);
1.916     albertel  413: 
                    414:     flock($idf,LOCK_SH);
                    415:     my %disk_env;
                    416:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    417: 	    &GDBM_READER(),0640)) {
                    418: 	return undef;	
                    419:     }
                    420: 
                    421:     if (!defined($disk_env{'user.name'})
                    422: 	|| !defined($disk_env{'user.domain'})) {
                    423: 	return undef;
                    424:     }
                    425:     return $handle;
                    426: }
                    427: 
1.830     albertel  428: sub timed_flock {
                    429:     my ($file,$lock_type) = @_;
                    430:     my $failed=0;
                    431:     eval {
                    432: 	local $SIG{__DIE__}='DEFAULT';
                    433: 	local $SIG{ALRM}=sub {
                    434: 	    $failed=1;
                    435: 	    die("failed lock");
                    436: 	};
                    437: 	alarm(13);
                    438: 	flock($file,$lock_type);
                    439: 	alarm(0);
                    440:     };
                    441:     if ($failed) {
                    442: 	return undef;
                    443:     } else {
                    444: 	return 1;
                    445:     }
                    446: }
                    447: 
1.5       www       448: # ---------------------------------------------------------- Append Environment
                    449: 
                    450: sub appenv {
1.6       www       451:     my %newenv=@_;
1.692     albertel  452:     foreach my $key (keys(%newenv)) {
                    453: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  454:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  455:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       456:                 .'</font>');
1.692     albertel  457: 	    delete($newenv{$key});
1.35      www       458:         } else {
1.692     albertel  459:             $env{$key}=$newenv{$key};
1.35      www       460:         }
1.191     harris41  461:     }
1.917     albertel  462:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    463:     if ($opened
1.915     albertel  464: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  465: 	&&
                    466: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    467: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  468: 	while (my ($key,$value) = each(%newenv)) {
                    469: 	    $disk_env{$key} = $value;
1.448     albertel  470: 	}
1.783     albertel  471: 	untie(%disk_env);
1.56      www       472:     }
                    473:     return 'ok';
                    474: }
                    475: # ----------------------------------------------------- Delete from Environment
                    476: 
                    477: sub delenv {
                    478:     my $delthis=shift;
                    479:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  480:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       481:                 "Attempt to delete from environment ".$delthis);
                    482:         return 'error';
                    483:     }
1.917     albertel  484:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    485:     if ($opened
1.915     albertel  486: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  487: 	&&
                    488: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    489: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  490: 	foreach my $key (keys(%disk_env)) {
                    491: 	    if ($key=~/^$delthis/) { 
1.915     albertel  492: 		delete($env{$key});
                    493: 		delete($disk_env{$key});
                    494: 	    }
1.448     albertel  495: 	}
1.783     albertel  496: 	untie(%disk_env);
1.5       www       497:     }
                    498:     return 'ok';
1.369     albertel  499: }
                    500: 
1.790     albertel  501: sub get_env_multiple {
                    502:     my ($name) = @_;
                    503:     my @values;
                    504:     if (defined($env{$name})) {
                    505:         # exists is it an array
                    506:         if (ref($env{$name})) {
                    507:             @values=@{ $env{$name} };
                    508:         } else {
                    509:             $values[0]=$env{$name};
                    510:         }
                    511:     }
                    512:     return(@values);
                    513: }
                    514: 
1.369     albertel  515: # ------------------------------------------ Find out current server userload
                    516: # there is a copy in lond
                    517: sub userload {
                    518:     my $numusers=0;
                    519:     {
                    520: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    521: 	my $filename;
                    522: 	my $curtime=time;
                    523: 	while ($filename=readdir(LONIDS)) {
                    524: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  525: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  526: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  527: 	}
                    528: 	closedir(LONIDS);
                    529:     }
                    530:     my $userloadpercent=0;
                    531:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    532:     if ($maxuserload) {
1.371     albertel  533: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  534:     }
1.372     albertel  535:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  536:     return $userloadpercent;
1.283     www       537: }
                    538: 
                    539: # ------------------------------------------ Fight off request when overloaded
                    540: 
                    541: sub overloaderror {
                    542:     my ($r,$checkserver)=@_;
                    543:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    544:     my $loadavg;
                    545:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  546:        open(my $loadfile,'/proc/loadavg');
1.283     www       547:        $loadavg=<$loadfile>;
                    548:        $loadavg =~ s/\s.*//g;
1.285     matthew   549:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  550:        close($loadfile);
1.283     www       551:     } else {
                    552:        $loadavg=&reply('load',$checkserver);
                    553:     }
1.285     matthew   554:     my $overload=$loadavg-100;
1.283     www       555:     if ($overload>0) {
1.285     matthew   556: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       557:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       558:         return 413;
1.283     www       559:     }    
                    560:     return '';
1.5       www       561: }
1.1       albertel  562: 
                    563: # ------------------------------ Find server with least workload from spare.tab
1.11      www       564: 
1.1       albertel  565: sub spareserver {
1.670     albertel  566:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  567:     my $spare_server;
1.370     albertel  568:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  569:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    570:                                                      :  $userloadpercent;
                    571:     
                    572:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    573: 	($spare_server, $lowest_load) =
                    574: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    575:     }
                    576: 
                    577:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    578: 
                    579:     if (!$found_server) {
                    580: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    581: 	    ($spare_server, $lowest_load) =
                    582: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    583: 	}
                    584:     }
                    585: 
                    586:     if (!$want_server_name) {
1.838     albertel  587: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  588:     }
                    589:     return $spare_server;
                    590: }
                    591: 
                    592: sub compare_server_load {
                    593:     my ($try_server, $spare_server, $lowest_load) = @_;
                    594: 
                    595:     my $loadans     = &reply('load',    $try_server);
                    596:     my $userloadans = &reply('userload',$try_server);
                    597: 
                    598:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    599: 	next; #didn't get a number from the server
                    600:     }
                    601: 
                    602:     my $load;
                    603:     if ($loadans =~ /\d/) {
                    604: 	if ($userloadans =~ /\d/) {
                    605: 	    #both are numbers, pick the bigger one
                    606: 	    $load = ($loadans > $userloadans) ? $loadans 
                    607: 		                              : $userloadans;
1.411     albertel  608: 	} else {
1.784     albertel  609: 	    $load = $loadans;
1.411     albertel  610: 	}
1.784     albertel  611:     } else {
                    612: 	$load = $userloadans;
                    613:     }
                    614: 
                    615:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    616: 	$spare_server = $try_server;
                    617: 	$lowest_load  = $load;
1.370     albertel  618:     }
1.784     albertel  619:     return ($spare_server,$lowest_load);
1.202     matthew   620: }
1.914     albertel  621: 
                    622: # --------------------------- ask offload servers if user already has a session
                    623: sub find_existing_session {
                    624:     my ($udom,$uname) = @_;
                    625:     foreach my $try_server (@{ $spareid{'primary'} },
                    626: 			    @{ $spareid{'default'} }) {
                    627: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    628:     }
                    629:     return;
                    630: }
                    631: 
                    632: # -------------------------------- ask if server already has a session for user
                    633: sub has_user_session {
                    634:     my ($lonid,$udom,$uname) = @_;
                    635:     my $result = &reply(join(':','userhassession',
                    636: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    637:     return 1 if ($result eq 'ok');
                    638: 
                    639:     return 0;
                    640: }
                    641: 
1.202     matthew   642: # --------------------------------------------- Try to change a user's password
                    643: 
                    644: sub changepass {
1.799     raeburn   645:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   646:     $currentpass = &escape($currentpass);
                    647:     $newpass     = &escape($newpass);
1.799     raeburn   648:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   649: 		       $server);
                    650:     if (! $answer) {
                    651: 	&logthis("No reply on password change request to $server ".
                    652: 		 "by $uname in domain $udom.");
                    653:     } elsif ($answer =~ "^ok") {
                    654:         &logthis("$uname in $udom successfully changed their password ".
                    655: 		 "on $server.");
                    656:     } elsif ($answer =~ "^pwchange_failure") {
                    657: 	&logthis("$uname in $udom was unable to change their password ".
                    658: 		 "on $server.  The action was blocked by either lcpasswd ".
                    659: 		 "or pwchange");
                    660:     } elsif ($answer =~ "^non_authorized") {
                    661:         &logthis("$uname in $udom did not get their password correct when ".
                    662: 		 "attempting to change it on $server.");
                    663:     } elsif ($answer =~ "^auth_mode_error") {
                    664:         &logthis("$uname in $udom attempted to change their password despite ".
                    665: 		 "not being locally or internally authenticated on $server.");
                    666:     } elsif ($answer =~ "^unknown_user") {
                    667:         &logthis("$uname in $udom attempted to change their password ".
                    668: 		 "on $server but were unable to because $server is not ".
                    669: 		 "their home server.");
                    670:     } elsif ($answer =~ "^refused") {
                    671: 	&logthis("$server refused to change $uname in $udom password because ".
                    672: 		 "it was sent an unencrypted request to change the password.");
                    673:     }
                    674:     return $answer;
1.1       albertel  675: }
                    676: 
1.169     harris41  677: # ----------------------- Try to determine user's current authentication scheme
                    678: 
                    679: sub queryauthenticate {
                    680:     my ($uname,$udom)=@_;
1.456     albertel  681:     my $uhome=&homeserver($uname,$udom);
                    682:     if (!$uhome) {
                    683: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    684: 	return 'no_host';
                    685:     }
                    686:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    687:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    688: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  689:     }
1.456     albertel  690:     return $answer;
1.169     harris41  691: }
                    692: 
1.1       albertel  693: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       694: 
1.1       albertel  695: sub authenticate {
                    696:     my ($uname,$upass,$udom)=@_;
1.807     albertel  697:     $upass=&escape($upass);
                    698:     $uname= &LONCAPA::clean_username($uname);
1.836     www       699:     my $uhome=&homeserver($uname,$udom,1);
                    700:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    701: # Maybe the machine was offline and only re-appeared again recently?
                    702:         &reconlonc();
                    703: # One more
                    704: 	my $uhome=&homeserver($uname,$udom,1);
                    705: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    706: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    707: 	}
1.471     albertel  708: 	return 'no_host';
1.1       albertel  709:     }
1.471     albertel  710:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    711:     if ($answer eq 'authorized') {
                    712: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    713: 	return $uhome; 
                    714:     }
                    715:     if ($answer eq 'non_authorized') {
                    716: 	&logthis("User $uname at $udom rejected by $uhome");
                    717: 	return 'no_host'; 
1.9       www       718:     }
1.471     albertel  719:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  720:     return 'no_host';
                    721: }
                    722: 
                    723: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       724: 
1.599     albertel  725: my %homecache;
1.1       albertel  726: sub homeserver {
1.230     stredwic  727:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  728:     my $index="$uname:$udom";
1.426     albertel  729: 
1.599     albertel  730:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  731: 
                    732:     my %servers = &get_servers($udom,'library');
                    733:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  734:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  735: 		 exists($badServerCache{$tryserver}));
1.841     albertel  736: 
                    737: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    738: 	if ($answer eq 'found') {
                    739: 	    delete($badServerCache{$tryserver}); 
                    740: 	    return $homecache{$index}=$tryserver;
                    741: 	} elsif ($answer eq 'no_host') {
                    742: 	    $badServerCache{$tryserver}=1;
                    743: 	}
1.1       albertel  744:     }    
                    745:     return 'no_host';
1.70      www       746: }
                    747: 
                    748: # ------------------------------------- Find the usernames behind a list of IDs
                    749: 
                    750: sub idget {
                    751:     my ($udom,@ids)=@_;
                    752:     my %returnhash=();
                    753:     
1.841     albertel  754:     my %servers = &get_servers($udom,'library');
                    755:     foreach my $tryserver (keys(%servers)) {
                    756: 	my $idlist=join('&',@ids);
                    757: 	$idlist=~tr/A-Z/a-z/; 
                    758: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    759: 	my @answer=();
                    760: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    761: 	    @answer=split(/\&/,$reply);
                    762: 	}                    ;
                    763: 	my $i;
                    764: 	for ($i=0;$i<=$#ids;$i++) {
                    765: 	    if ($answer[$i]) {
                    766: 		$returnhash{$ids[$i]}=$answer[$i];
                    767: 	    } 
                    768: 	}
                    769:     } 
1.70      www       770:     return %returnhash;
                    771: }
                    772: 
                    773: # ------------------------------------- Find the IDs behind a list of usernames
                    774: 
                    775: sub idrget {
                    776:     my ($udom,@unames)=@_;
                    777:     my %returnhash=();
1.800     albertel  778:     foreach my $uname (@unames) {
                    779:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  780:     }
1.70      www       781:     return %returnhash;
                    782: }
                    783: 
                    784: # ------------------------------- Store away a list of names and associated IDs
                    785: 
                    786: sub idput {
                    787:     my ($udom,%ids)=@_;
                    788:     my %servers=();
1.800     albertel  789:     foreach my $uname (keys(%ids)) {
                    790: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    791:         my $uhom=&homeserver($uname,$udom);
1.70      www       792:         if ($uhom ne 'no_host') {
1.800     albertel  793:             my $id=&escape($ids{$uname});
1.70      www       794:             $id=~tr/A-Z/a-z/;
1.800     albertel  795:             my $esc_unam=&escape($uname);
1.70      www       796: 	    if ($servers{$uhom}) {
1.800     albertel  797: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       798:             } else {
1.800     albertel  799:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       800:             }
                    801:         }
1.191     harris41  802:     }
1.800     albertel  803:     foreach my $server (keys(%servers)) {
                    804:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  805:     }
1.344     www       806: }
                    807: 
1.806     raeburn   808: # ------------------------------------------- get items from domain db files   
                    809: 
                    810: sub get_dom {
1.860     raeburn   811:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   812:     my $items='';
                    813:     foreach my $item (@$storearr) {
                    814:         $items.=&escape($item).'&';
                    815:     }
                    816:     $items=~s/\&$//;
1.860     raeburn   817:     if (!$udom) {
                    818:         $udom=$env{'user.domain'};
                    819:         if (defined(&domain($udom,'primary'))) {
                    820:             $uhome=&domain($udom,'primary');
                    821:         } else {
1.874     albertel  822:             undef($uhome);
1.860     raeburn   823:         }
                    824:     } else {
                    825:         if (!$uhome) {
                    826:             if (defined(&domain($udom,'primary'))) {
                    827:                 $uhome=&domain($udom,'primary');
                    828:             }
                    829:         }
                    830:     }
                    831:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   832:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   833:         my %returnhash;
1.875     albertel  834:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   835:             return %returnhash;
                    836:         }
1.806     raeburn   837:         my @pairs=split(/\&/,$rep);
                    838:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    839:             return @pairs;
                    840:         }
                    841:         my $i=0;
                    842:         foreach my $item (@$storearr) {
                    843:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    844:             $i++;
                    845:         }
                    846:         return %returnhash;
                    847:     } else {
1.880     banghart  848:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   849:     }
                    850: }
                    851: 
                    852: # -------------------------------------------- put items in domain db files 
                    853: 
                    854: sub put_dom {
1.860     raeburn   855:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    856:     if (!$udom) {
                    857:         $udom=$env{'user.domain'};
                    858:         if (defined(&domain($udom,'primary'))) {
                    859:             $uhome=&domain($udom,'primary');
                    860:         } else {
1.874     albertel  861:             undef($uhome);
1.860     raeburn   862:         }
                    863:     } else {
                    864:         if (!$uhome) {
                    865:             if (defined(&domain($udom,'primary'))) {
                    866:                 $uhome=&domain($udom,'primary');
                    867:             }
                    868:         }
                    869:     } 
                    870:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   871:         my $items='';
                    872:         foreach my $item (keys(%$storehash)) {
                    873:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    874:         }
                    875:         $items=~s/\&$//;
                    876:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    877:     } else {
1.860     raeburn   878:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   879:     }
                    880: }
                    881: 
1.837     raeburn   882: sub retrieve_inst_usertypes {
                    883:     my ($udom) = @_;
                    884:     my (%returnhash,@order);
1.846     albertel  885:     if (defined(&domain($udom,'primary'))) {
                    886:         my $uhome=&domain($udom,'primary');
1.837     raeburn   887:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    888:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    889:         my @pairs=split(/\&/,$hashitems);
                    890:         foreach my $item (@pairs) {
                    891:             my ($key,$value)=split(/=/,$item,2);
                    892:             $key = &unescape($key);
                    893:             next if ($key =~ /^error: 2 /);
                    894:             $returnhash{$key}=&thaw_unescape($value);
                    895:         }
                    896:         my @esc_order = split(/\&/,$orderitems);
                    897:         foreach my $item (@esc_order) {
                    898:             push(@order,&unescape($item));
                    899:         }
                    900:     } else {
                    901:         &logthis("get_dom failed - no primary domain server for $udom");
                    902:     }
                    903:     return (\%returnhash,\@order);
                    904: }
                    905: 
1.868     raeburn   906: sub is_domainimage {
                    907:     my ($url) = @_;
                    908:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    909:         if (&domain($1) ne '') {
                    910:             return '1';
                    911:         }
                    912:     }
                    913:     return;
                    914: }
                    915: 
1.899     raeburn   916: sub inst_directory_query {
                    917:     my ($srch) = @_;
                    918:     my $udom = $srch->{'srchdomain'};
                    919:     my %results;
                    920:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   921:     my $outcome;
1.899     raeburn   922:     if ($homeserver ne '') {
1.904     albertel  923: 	my $queryid=&reply("querysend:instdirsearch:".
                    924: 			   &escape($srch->{'srchby'}).':'.
                    925: 			   &escape($srch->{'srchterm'}).':'.
                    926: 			   &escape($srch->{'srchtype'}),$homeserver);
                    927: 	my $host=&hostname($homeserver);
                    928: 	if ($queryid !~/^\Q$host\E\_/) {
                    929: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    930: 	    return;
                    931: 	}
                    932: 	my $response = &get_query_reply($queryid);
                    933: 	my $maxtries = 5;
                    934: 	my $tries = 1;
                    935: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    936: 	    $response = &get_query_reply($queryid);
                    937: 	    $tries ++;
                    938: 	}
                    939: 
                    940:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn   941:             if ($response eq 'unavailable') {
                    942:                 $outcome = $response;
                    943:             } else {
                    944:                 $outcome = 'ok';
                    945:                 my @matches = split(/\n/,$response);
                    946:                 foreach my $match (@matches) {
                    947:                     my ($key,$value) = split(/=/,$match);
                    948:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                    949:                 }
1.899     raeburn   950:             }
                    951:         }
                    952:     }
1.909     raeburn   953:     return ($outcome,%results);
1.899     raeburn   954: }
                    955: 
                    956: sub usersearch {
                    957:     my ($srch) = @_;
                    958:     my $dom = $srch->{'srchdomain'};
                    959:     my %results;
                    960:     my %libserv = &all_library();
                    961:     my $query = 'usersearch';
                    962:     foreach my $tryserver (keys(%libserv)) {
                    963:         if (&host_domain($tryserver) eq $dom) {
                    964:             my $host=&hostname($tryserver);
                    965:             my $queryid=
1.911     raeburn   966:                 &reply("querysend:".&escape($query).':'.
                    967:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn   968:                        &escape($srch->{'srchtype'}).':'.
                    969:                        &escape($srch->{'srchterm'}),$tryserver);
                    970:             if ($queryid !~/^\Q$host\E\_/) {
                    971:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   972:                 next;
1.899     raeburn   973:             }
                    974:             my $reply = &get_query_reply($queryid);
                    975:             my $maxtries = 1;
                    976:             my $tries = 1;
                    977:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    978:                 $reply = &get_query_reply($queryid);
                    979:                 $tries ++;
                    980:             }
                    981:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    982:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    983:             } else {
1.911     raeburn   984:                 my @matches;
                    985:                 if ($reply =~ /\n/) {
                    986:                     @matches = split(/\n/,$reply);
                    987:                 } else {
                    988:                     @matches = split(/\&/,$reply);
                    989:                 }
1.899     raeburn   990:                 foreach my $match (@matches) {
                    991:                     my ($uname,$udom,%userhash);
1.911     raeburn   992:                     foreach my $entry (split(/:/,$match)) {
                    993:                         my ($key,$value) =
                    994:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn   995:                         $userhash{$key} = $value;
                    996:                         if ($key eq 'username') {
                    997:                             $uname = $value;
                    998:                         } elsif ($key eq 'domain') {
                    999:                             $udom = $value;
1.911     raeburn  1000:                         }
1.899     raeburn  1001:                     }
                   1002:                     $results{$uname.':'.$udom} = \%userhash;
                   1003:                 }
                   1004:             }
                   1005:         }
                   1006:     }
                   1007:     return %results;
                   1008: }
                   1009: 
1.912     raeburn  1010: sub get_instuser {
                   1011:     my ($udom,$uname,$id) = @_;
                   1012:     my $homeserver = &domain($udom,'primary');
                   1013:     my ($outcome,%results);
                   1014:     if ($homeserver ne '') {
                   1015:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1016:                            &escape($id).':'.&escape($udom),$homeserver);
                   1017:         my $host=&hostname($homeserver);
                   1018:         if ($queryid !~/^\Q$host\E\_/) {
                   1019:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1020:             return;
                   1021:         }
                   1022:         my $response = &get_query_reply($queryid);
                   1023:         my $maxtries = 5;
                   1024:         my $tries = 1;
                   1025:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1026:             $response = &get_query_reply($queryid);
                   1027:             $tries ++;
                   1028:         }
                   1029:         if (!&error($response) && $response ne 'refused') {
                   1030:             if ($response eq 'unavailable') {
                   1031:                 $outcome = $response;
                   1032:             } else {
                   1033:                 $outcome = 'ok';
                   1034:                 my @matches = split(/\n/,$response);
                   1035:                 foreach my $match (@matches) {
                   1036:                     my ($key,$value) = split(/=/,$match);
                   1037:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1038:                 }
                   1039:             }
                   1040:         }
                   1041:     }
                   1042:     my %userinfo;
                   1043:     if (ref($results{$uname}) eq 'HASH') {
                   1044:         %userinfo = %{$results{$uname}};
                   1045:     } 
                   1046:     return ($outcome,%userinfo);
                   1047: }
                   1048: 
                   1049: sub inst_rulecheck {
                   1050:     my ($udom,$uname,$rules) = @_;
                   1051:     my %returnhash;
                   1052:     if ($udom ne '') {
                   1053:         if (ref($rules) eq 'ARRAY') {
                   1054:             @{$rules} = map {&escape($_);} (@{$rules});
                   1055:             my $rulestr = join(':',@{$rules});
                   1056:             my $homeserver=&domain($udom,'primary');
                   1057:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
                   1058:                 my $response=&unescape(&reply('instrulecheck:'.&escape($udom).':'.
                   1059:                                               &escape($uname).':'.$rulestr,
                   1060:                                               $homeserver));
                   1061:                 if ($response ne 'refused') {
                   1062:                     my @pairs=split(/\&/,$response);
                   1063:                     foreach my $item (@pairs) {
                   1064:                         my ($key,$value)=split(/=/,$item,2);
                   1065:                         $key = &unescape($key);
                   1066:                         next if ($key =~ /^error: 2 /);
                   1067:                         $returnhash{$key}=&thaw_unescape($value);
                   1068:                     }
                   1069:                 }
                   1070:             }
                   1071:         }
                   1072:     }
                   1073:     return %returnhash;
                   1074: }
                   1075: 
                   1076: sub inst_userrules {
                   1077:     my ($udom) = @_;
                   1078:     my (%ruleshash,@ruleorder);
                   1079:     if ($udom ne '') {
                   1080:         my $homeserver=&domain($udom,'primary');
                   1081:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
                   1082:             my $response=&reply('instuserrules:'.&escape($udom),
                   1083:                                  $homeserver);
                   1084:             if (($response ne 'refused') && ($response ne 'error') && 
                   1085:                 ($response ne 'no_such_host')) {
                   1086:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1087:                 my @pairs=split(/\&/,$hashitems);
                   1088:                 foreach my $item (@pairs) {
                   1089:                     my ($key,$value)=split(/=/,$item,2);
                   1090:                     $key = &unescape($key);
                   1091:                     next if ($key =~ /^error: 2 /);
                   1092:                     $ruleshash{$key}=&thaw_unescape($value);
                   1093:                 }
                   1094:                 my @esc_order = split(/\&/,$orderitems);
                   1095:                 foreach my $item (@esc_order) {
                   1096:                     push(@ruleorder,&unescape($item));
                   1097:                 }
                   1098:             }
                   1099:         }
                   1100:     }
                   1101:     return (\%ruleshash,\@ruleorder);
                   1102: }
                   1103: 
1.344     www      1104: # --------------------------------------------------- Assign a key to a student
                   1105: 
                   1106: sub assign_access_key {
1.364     www      1107: #
                   1108: # a valid key looks like uname:udom#comments
                   1109: # comments are being appended
                   1110: #
1.498     www      1111:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1112:     $kdom=
1.620     albertel 1113:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1114:     $knum=
1.620     albertel 1115:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1116:     $cdom=
1.620     albertel 1117:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1118:     $cnum=
1.620     albertel 1119:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1120:     $udom=$env{'user.name'} unless (defined($udom));
                   1121:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1122:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1123:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1124:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1125:                                                   # assigned to this person
                   1126:                                                   # - this should not happen,
1.345     www      1127:                                                   # unless something went wrong
                   1128:                                                   # the first time around
                   1129: # ready to assign
1.364     www      1130:         $logentry=$1.'; '.$logentry;
1.496     www      1131:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1132:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1133: # key now belongs to user
1.346     www      1134: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1135:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                   1136:                 &appenv('environment.'.$envkey => $ckey);
                   1137:                 return 'ok';
                   1138:             } else {
                   1139:                 return 
                   1140:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1141: 	    }
                   1142:         } else {
                   1143:             return 'error: Could not assign key, try again later.';
                   1144:         }
1.364     www      1145:     } elsif (!$existing{$ckey}) {
1.345     www      1146: # the key does not exist
                   1147: 	return 'error: The key does not exist';
                   1148:     } else {
                   1149: # the key is somebody else's
                   1150: 	return 'error: The key is already in use';
                   1151:     }
1.344     www      1152: }
                   1153: 
1.364     www      1154: # ------------------------------------------ put an additional comment on a key
                   1155: 
                   1156: sub comment_access_key {
                   1157: #
                   1158: # a valid key looks like uname:udom#comments
                   1159: # comments are being appended
                   1160: #
                   1161:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1162:     $cdom=
1.620     albertel 1163:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1164:     $cnum=
1.620     albertel 1165:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1166:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1167:     if ($existing{$ckey}) {
                   1168:         $existing{$ckey}.='; '.$logentry;
                   1169: # ready to assign
1.367     www      1170:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1171:                                                  $cdom,$cnum) eq 'ok') {
                   1172: 	    return 'ok';
                   1173:         } else {
                   1174: 	    return 'error: Count not store comment.';
                   1175:         }
                   1176:     } else {
                   1177: # the key does not exist
                   1178: 	return 'error: The key does not exist';
                   1179:     }
                   1180: }
                   1181: 
1.344     www      1182: # ------------------------------------------------------ Generate a set of keys
                   1183: 
                   1184: sub generate_access_keys {
1.364     www      1185:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1186:     $cdom=
1.620     albertel 1187:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1188:     $cnum=
1.620     albertel 1189:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1190:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1191:     unless (($cdom) && ($cnum)) { return 0; }
                   1192:     if ($number>10000) { return 0; }
                   1193:     sleep(2); # make sure don't get same seed twice
                   1194:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1195:     my $total=0;
                   1196:     for (my $i=1;$i<=$number;$i++) {
                   1197:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1198:                   sprintf("%lx",int(100000*rand)).'-'.
                   1199:                   sprintf("%lx",int(100000*rand));
                   1200:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1201:        $newkey=~s/0/h/g; # and also 0 and O
                   1202:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1203:        if ($existing{$newkey}) {
                   1204:            $i--;
                   1205:        } else {
1.364     www      1206: 	  if (&put('accesskeys',
                   1207:               { $newkey => '# generated '.localtime().
1.620     albertel 1208:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1209:                            '; '.$logentry },
                   1210: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1211:               $total++;
                   1212: 	  }
                   1213:        }
                   1214:     }
1.620     albertel 1215:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1216:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1217:     return $total;
                   1218: }
                   1219: 
                   1220: # ------------------------------------------------------- Validate an accesskey
                   1221: 
                   1222: sub validate_access_key {
                   1223:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1224:     $cdom=
1.620     albertel 1225:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1226:     $cnum=
1.620     albertel 1227:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1228:     $udom=$env{'user.domain'} unless (defined($udom));
                   1229:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1230:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1231:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1232: }
                   1233: 
                   1234: # ------------------------------------- Find the section of student in a course
1.652     albertel 1235: sub devalidate_getsection_cache {
                   1236:     my ($udom,$unam,$courseid)=@_;
                   1237:     my $hashid="$udom:$unam:$courseid";
                   1238:     &devalidate_cache_new('getsection',$hashid);
                   1239: }
1.298     matthew  1240: 
1.815     albertel 1241: sub courseid_to_courseurl {
                   1242:     my ($courseid) = @_;
                   1243:     #already url style courseid
                   1244:     return $courseid if ($courseid =~ m{^/});
                   1245: 
                   1246:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1247: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1248: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1249: 	return "/$cdom/$cnum";
                   1250:     }
                   1251: 
                   1252:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1253:     if (exists($courseinfo{'num'})) {
                   1254: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1255:     }
                   1256: 
                   1257:     return undef;
                   1258: }
                   1259: 
1.298     matthew  1260: sub getsection {
                   1261:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1262:     my $cachetime=1800;
1.551     albertel 1263: 
                   1264:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1265:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1266:     if (defined($cached)) { return $result; }
                   1267: 
1.298     matthew  1268:     my %Pending; 
                   1269:     my %Expired;
                   1270:     #
                   1271:     # Each role can either have not started yet (pending), be active, 
                   1272:     #    or have expired.
                   1273:     #
                   1274:     # If there is an active role, we are done.
                   1275:     #
                   1276:     # If there is more than one role which has not started yet, 
                   1277:     #     choose the one which will start sooner
                   1278:     # If there is one role which has not started yet, return it.
                   1279:     #
                   1280:     # If there is more than one expired role, choose the one which ended last.
                   1281:     # If there is a role which has expired, return it.
                   1282:     #
1.815     albertel 1283:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1284:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1285:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1286:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1287:         my $section=$1;
                   1288:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1289:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1290:         my $now=time;
1.548     albertel 1291:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1292:             $Expired{$end}=$section;
                   1293:             next;
                   1294:         }
1.548     albertel 1295:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1296:             $Pending{$start}=$section;
                   1297:             next;
                   1298:         }
1.599     albertel 1299:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1300:     }
                   1301:     #
                   1302:     # Presumedly there will be few matching roles from the above
                   1303:     # loop and the sorting time will be negligible.
                   1304:     if (scalar(keys(%Pending))) {
                   1305:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1306:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1307:     } 
                   1308:     if (scalar(keys(%Expired))) {
                   1309:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1310:         my $time = pop(@sorted);
1.599     albertel 1311:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1312:     }
1.599     albertel 1313:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1314: }
1.70      www      1315: 
1.599     albertel 1316: sub save_cache {
                   1317:     &purge_remembered();
1.722     albertel 1318:     #&Apache::loncommon::validate_page();
1.620     albertel 1319:     undef(%env);
1.780     albertel 1320:     undef($env_loaded);
1.599     albertel 1321: }
1.452     albertel 1322: 
1.599     albertel 1323: my $to_remember=-1;
                   1324: my %remembered;
                   1325: my %accessed;
                   1326: my $kicks=0;
                   1327: my $hits=0;
1.849     albertel 1328: sub make_key {
                   1329:     my ($name,$id) = @_;
1.872     albertel 1330:     if (length($id) > 65 
                   1331: 	&& length(&escape($id)) > 200) {
                   1332: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1333:     }
1.849     albertel 1334:     return &escape($name.':'.$id);
                   1335: }
                   1336: 
1.599     albertel 1337: sub devalidate_cache_new {
                   1338:     my ($name,$id,$debug) = @_;
                   1339:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1340:     $id=&make_key($name,$id);
1.599     albertel 1341:     $memcache->delete($id);
                   1342:     delete($remembered{$id});
                   1343:     delete($accessed{$id});
                   1344: }
                   1345: 
                   1346: sub is_cached_new {
                   1347:     my ($name,$id,$debug) = @_;
1.849     albertel 1348:     $id=&make_key($name,$id);
1.599     albertel 1349:     if (exists($remembered{$id})) {
                   1350: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1351: 	$accessed{$id}=[&gettimeofday()];
                   1352: 	$hits++;
                   1353: 	return ($remembered{$id},1);
                   1354:     }
                   1355:     my $value = $memcache->get($id);
                   1356:     if (!(defined($value))) {
                   1357: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1358: 	return (undef,undef);
1.416     albertel 1359:     }
1.599     albertel 1360:     if ($value eq '__undef__') {
                   1361: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1362: 	$value=undef;
                   1363:     }
                   1364:     &make_room($id,$value,$debug);
                   1365:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1366:     return ($value,1);
                   1367: }
                   1368: 
                   1369: sub do_cache_new {
                   1370:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1371:     $id=&make_key($name,$id);
1.599     albertel 1372:     my $setvalue=$value;
                   1373:     if (!defined($setvalue)) {
                   1374: 	$setvalue='__undef__';
                   1375:     }
1.623     albertel 1376:     if (!defined($time) ) {
                   1377: 	$time=600;
                   1378:     }
1.599     albertel 1379:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1380:     my $result = $memcache->set($id,$setvalue,$time);
                   1381:     if (! $result) {
1.872     albertel 1382: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1383: 	$memcache->disconnect_all();
1.872     albertel 1384:     }
1.600     albertel 1385:     # need to make a copy of $value
1.919     albertel 1386:     &make_room($id,$value,$debug);
1.599     albertel 1387:     return $value;
                   1388: }
                   1389: 
                   1390: sub make_room {
                   1391:     my ($id,$value,$debug)=@_;
1.919     albertel 1392: 
                   1393:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1394:                                     : $value;
1.599     albertel 1395:     if ($to_remember<0) { return; }
                   1396:     $accessed{$id}=[&gettimeofday()];
                   1397:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1398:     my $to_kick;
                   1399:     my $max_time=0;
                   1400:     foreach my $other (keys(%accessed)) {
                   1401: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1402: 	    $to_kick=$other;
                   1403: 	    $max_time=&tv_interval($accessed{$other});
                   1404: 	}
                   1405:     }
                   1406:     delete($remembered{$to_kick});
                   1407:     delete($accessed{$to_kick});
                   1408:     $kicks++;
                   1409:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1410:     return;
                   1411: }
                   1412: 
1.599     albertel 1413: sub purge_remembered {
1.604     albertel 1414:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1415:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1416:     undef(%remembered);
                   1417:     undef(%accessed);
1.428     albertel 1418: }
1.70      www      1419: # ------------------------------------- Read an entry from a user's environment
                   1420: 
                   1421: sub userenvironment {
                   1422:     my ($udom,$unam,@what)=@_;
                   1423:     my %returnhash=();
                   1424:     my @answer=split(/\&/,
                   1425:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1426:                       &homeserver($unam,$udom)));
                   1427:     my $i;
                   1428:     for ($i=0;$i<=$#what;$i++) {
                   1429: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1430:     }
                   1431:     return %returnhash;
1.1       albertel 1432: }
                   1433: 
1.617     albertel 1434: # ---------------------------------------------------------- Get a studentphoto
                   1435: sub studentphoto {
                   1436:     my ($udom,$unam,$ext) = @_;
                   1437:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1438:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1439:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1440:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1441:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1442:             } else {
                   1443:                 my ($result,$perm_reqd)=
1.707     albertel 1444: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1445:                 if ($result eq 'ok') {
                   1446:                     if (!($perm_reqd eq 'yes')) {
                   1447:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1448:                     }
                   1449:                 }
                   1450:             }
                   1451:         }
                   1452:     } else {
                   1453:         my ($result,$perm_reqd) = 
1.707     albertel 1454: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1455:         if ($result eq 'ok') {
                   1456:             if (!($perm_reqd eq 'yes')) {
                   1457:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1458:             }
                   1459:         }
                   1460:     }
                   1461:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1462: }
                   1463: 
                   1464: sub retrievestudentphoto {
                   1465:     my ($udom,$unam,$ext,$type) = @_;
                   1466:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1467:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1468:     if ($ret eq 'ok') {
                   1469:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1470:         if ($type eq 'thumbnail') {
                   1471:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1472:         }
                   1473:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1474:         return $tokenurl;
                   1475:     } else {
                   1476:         if ($type eq 'thumbnail') {
                   1477:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1478:         } else { 
                   1479:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1480:         }
1.617     albertel 1481:     }
                   1482: }
                   1483: 
1.263     www      1484: # -------------------------------------------------------------------- New chat
                   1485: 
                   1486: sub chatsend {
1.724     raeburn  1487:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1488:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1489:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1490:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1491:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1492: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1493: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1494: }
                   1495: 
                   1496: # ------------------------------------------ Find current version of a resource
                   1497: 
                   1498: sub getversion {
                   1499:     my $fname=&clutter(shift);
                   1500:     unless ($fname=~/^\/res\//) { return -1; }
                   1501:     return &currentversion(&filelocation('',$fname));
                   1502: }
                   1503: 
                   1504: sub currentversion {
                   1505:     my $fname=shift;
1.599     albertel 1506:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1507:     if (defined($cached)) { return $result; }
1.292     www      1508:     my $author=$fname;
                   1509:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1510:     my ($udom,$uname)=split(/\//,$author);
                   1511:     my $home=homeserver($uname,$udom);
                   1512:     if ($home eq 'no_host') { 
                   1513:         return -1; 
                   1514:     }
                   1515:     my $answer=reply("currentversion:$fname",$home);
                   1516:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1517: 	return -1;
                   1518:     }
1.599     albertel 1519:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1520: }
                   1521: 
1.1       albertel 1522: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1523: 
1.1       albertel 1524: sub subscribe {
                   1525:     my $fname=shift;
1.761     raeburn  1526:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1527:     $fname=~s/[\n\r]//g;
1.1       albertel 1528:     my $author=$fname;
                   1529:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1530:     my ($udom,$uname)=split(/\//,$author);
                   1531:     my $home=homeserver($uname,$udom);
1.335     albertel 1532:     if ($home eq 'no_host') {
                   1533:         return 'not_found';
1.1       albertel 1534:     }
                   1535:     my $answer=reply("sub:$fname",$home);
1.64      www      1536:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1537: 	$answer.=' by '.$home;
                   1538:     }
1.1       albertel 1539:     return $answer;
                   1540: }
                   1541:     
1.8       www      1542: # -------------------------------------------------------------- Replicate file
                   1543: 
                   1544: sub repcopy {
                   1545:     my $filename=shift;
1.23      www      1546:     $filename=~s/\/+/\//g;
1.607     raeburn  1547:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1548:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1549:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1550: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1551: 	return &repcopy_userfile($filename);
                   1552:     }
1.532     albertel 1553:     $filename=~s/[\n\r]//g;
1.8       www      1554:     my $transname="$filename.in.transfer";
1.828     www      1555: # FIXME: this should flock
1.607     raeburn  1556:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1557:     my $remoteurl=subscribe($filename);
1.64      www      1558:     if ($remoteurl =~ /^con_lost by/) {
                   1559: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1560:            return 'unavailable';
1.8       www      1561:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1562: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1563: 	   return 'not_found';
1.64      www      1564:     } elsif ($remoteurl =~ /^rejected by/) {
                   1565: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1566:            return 'forbidden';
1.20      www      1567:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1568:            return 'ok';
1.8       www      1569:     } else {
1.290     www      1570:         my $author=$filename;
                   1571:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1572:         my ($udom,$uname)=split(/\//,$author);
                   1573:         my $home=homeserver($uname,$udom);
                   1574:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1575:            my @parts=split(/\//,$filename);
                   1576:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1577:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1578:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1579: 	       return 'bad_request';
1.8       www      1580:            }
                   1581:            my $count;
                   1582:            for ($count=5;$count<$#parts;$count++) {
                   1583:                $path.="/$parts[$count]";
                   1584:                if ((-e $path)!=1) {
                   1585: 		   mkdir($path,0777);
                   1586:                }
                   1587:            }
                   1588:            my $ua=new LWP::UserAgent;
                   1589:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1590:            my $response=$ua->request($request,$transname);
                   1591:            if ($response->is_error()) {
                   1592: 	       unlink($transname);
                   1593:                my $message=$response->status_line;
1.672     albertel 1594:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1595:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1596:                return 'unavailable';
1.8       www      1597:            } else {
1.16      www      1598: 	       if ($remoteurl!~/\.meta$/) {
                   1599:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1600:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1601:                   if ($mresponse->is_error()) {
                   1602: 		      unlink($filename.'.meta');
                   1603:                       &logthis(
1.672     albertel 1604:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1605:                   }
                   1606: 	       }
1.8       www      1607:                rename($transname,$filename);
1.607     raeburn  1608:                return 'ok';
1.8       www      1609:            }
1.290     www      1610:        }
1.8       www      1611:     }
1.330     www      1612: }
                   1613: 
                   1614: # ------------------------------------------------ Get server side include body
                   1615: sub ssi_body {
1.381     albertel 1616:     my ($filelink,%form)=@_;
1.606     matthew  1617:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1618:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1619:     }
1.330     www      1620:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1621:                                      &ssi($filelink,%form));
1.778     albertel 1622:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1623:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1624:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1625:     return $output;
1.8       www      1626: }
                   1627: 
1.15      www      1628: # --------------------------------------------------------- Server Side Include
                   1629: 
1.782     albertel 1630: sub absolute_url {
                   1631:     my ($host_name) = @_;
                   1632:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1633:     if ($host_name eq '') {
                   1634: 	$host_name = $ENV{'SERVER_NAME'};
                   1635:     }
                   1636:     return $protocol.$host_name;
                   1637: }
                   1638: 
1.15      www      1639: sub ssi {
                   1640: 
1.23      www      1641:     my ($fn,%form)=@_;
1.15      www      1642: 
                   1643:     my $ua=new LWP::UserAgent;
1.23      www      1644:     
                   1645:     my $request;
1.711     albertel 1646: 
                   1647:     $form{'no_update_last_known'}=1;
1.895     albertel 1648:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1649:     if (%form) {
1.782     albertel 1650:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1651:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1652:     } else {
1.782     albertel 1653:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1654:     }
                   1655: 
1.15      www      1656:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1657:     my $response=$ua->request($request);
                   1658: 
1.324     www      1659:     return $response->content;
                   1660: }
                   1661: 
                   1662: sub externalssi {
                   1663:     my ($url)=@_;
                   1664:     my $ua=new LWP::UserAgent;
                   1665:     my $request=new HTTP::Request('GET',$url);
                   1666:     my $response=$ua->request($request);
1.15      www      1667:     return $response->content;
                   1668: }
1.254     www      1669: 
1.492     albertel 1670: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1671: 
                   1672: sub allowuploaded {
                   1673:     my ($srcurl,$url)=@_;
                   1674:     $url=&clutter(&declutter($url));
                   1675:     my $dir=$url;
                   1676:     $dir=~s/\/[^\/]+$//;
                   1677:     my %httpref=();
                   1678:     my $httpurl=&hreflocation('',$url);
                   1679:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1680:     &Apache::lonnet::appenv(%httpref);
1.254     www      1681: }
1.477     raeburn  1682: 
1.478     albertel 1683: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1684: # input: action, courseID, current domain, intended
1.637     raeburn  1685: #        path to file, source of file, instruction to parse file for objects,
                   1686: #        ref to hash for embedded objects,
                   1687: #        ref to hash for codebase of java objects.
                   1688: #
1.485     raeburn  1689: # output: url to file (if action was uploaddoc), 
                   1690: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1691: #
1.478     albertel 1692: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1693: # course.
1.477     raeburn  1694: #
1.478     albertel 1695: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1696: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1697: #          course's home server.
1.477     raeburn  1698: #
1.478     albertel 1699: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1700: #          be copied from $source (current location) to 
                   1701: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1702: #         and will then be copied to
                   1703: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1704: #         course's home server.
1.485     raeburn  1705: #
1.481     raeburn  1706: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1707: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1708: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1709: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1710: #         in course's home server.
1.637     raeburn  1711: #
1.477     raeburn  1712: 
                   1713: sub process_coursefile {
1.638     albertel 1714:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1715:     my $fetchresult;
1.638     albertel 1716:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1717:     if ($action eq 'propagate') {
1.638     albertel 1718:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1719: 			     $home);
1.481     raeburn  1720:     } else {
1.477     raeburn  1721:         my $fpath = '';
                   1722:         my $fname = $file;
1.478     albertel 1723:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1724:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1725:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1726:         if ($action eq 'copy') {
                   1727:             if ($source eq '') {
                   1728:                 $fetchresult = 'no source file';
                   1729:                 return $fetchresult;
                   1730:             } else {
                   1731:                 my $destination = $filepath.'/'.$fname;
                   1732:                 rename($source,$destination);
                   1733:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1734:                                  $home);
1.481     raeburn  1735:             }
                   1736:         } elsif ($action eq 'uploaddoc') {
                   1737:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1738:             print $fh $env{'form.'.$source};
1.481     raeburn  1739:             close($fh);
1.637     raeburn  1740:             if ($parser eq 'parse') {
                   1741:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1742:                 unless ($parse_result eq 'ok') {
                   1743:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1744:                 }
                   1745:             }
1.477     raeburn  1746:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1747:                                  $home);
1.481     raeburn  1748:             if ($fetchresult eq 'ok') {
                   1749:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1750:             } else {
                   1751:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1752:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1753:                 return '/adm/notfound.html';
                   1754:             }
1.477     raeburn  1755:         }
                   1756:     }
1.485     raeburn  1757:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1758:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1759:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1760:     }
                   1761:     return $fetchresult;
                   1762: }
                   1763: 
1.637     raeburn  1764: sub build_filepath {
                   1765:     my ($fpath) = @_;
                   1766:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1767:     unless ($fpath eq '') {
                   1768:         my @parts=split('/',$fpath);
                   1769:         foreach my $part (@parts) {
                   1770:             $filepath.= '/'.$part;
                   1771:             if ((-e $filepath)!=1) {
                   1772:                 mkdir($filepath,0777);
                   1773:             }
                   1774:         }
                   1775:     }
                   1776:     return $filepath;
                   1777: }
                   1778: 
                   1779: sub store_edited_file {
1.638     albertel 1780:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1781:     my $file = $primary_url;
                   1782:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1783:     my $fpath = '';
                   1784:     my $fname = $file;
                   1785:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1786:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1787:     my $filepath = &build_filepath($fpath);
                   1788:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1789:     print $fh $content;
                   1790:     close($fh);
1.638     albertel 1791:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1792:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1793: 			  $home);
1.637     raeburn  1794:     if ($$fetchresult eq 'ok') {
                   1795:         return '/uploaded/'.$fpath.'/'.$fname;
                   1796:     } else {
1.638     albertel 1797:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1798: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1799:         return '/adm/notfound.html';
                   1800:     }
                   1801: }
                   1802: 
1.531     albertel 1803: sub clean_filename {
1.831     albertel 1804:     my ($fname,$args)=@_;
1.315     www      1805: # Replace Windows backslashes by forward slashes
1.257     www      1806:     $fname=~s/\\/\//g;
1.831     albertel 1807:     if (!$args->{'keep_path'}) {
                   1808:         # Get rid of everything but the actual filename
                   1809: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1810:     }
1.315     www      1811: # Replace spaces by underscores
                   1812:     $fname=~s/\s+/\_/g;
                   1813: # Replace all other weird characters by nothing
1.831     albertel 1814:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1815: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1816: # numbers
                   1817:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1818:     return $fname;
                   1819: }
                   1820: 
1.608     albertel 1821: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1822: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1823: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1824: #        $coursedoc - if true up to the current course
                   1825: #                     if false
                   1826: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1827: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1828: #        $allfiles - reference to hash for embedded objects
                   1829: #        $codebase - reference to hash for codebase of java objects
                   1830: #        $desuname - username for permanent storage of uploaded file
                   1831: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1832: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1833: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1834: # 
1.686     albertel 1835: # output: url of file in userspace, or error: <message> 
                   1836: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1837: 
                   1838: 
1.531     albertel 1839: sub userfileupload {
1.860     raeburn  1840:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1841:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1842:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1843:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1844:     $fname=&clean_filename($fname);
1.315     www      1845: # See if there is anything left
1.257     www      1846:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1847:     chop($env{'form.'.$formname});
1.523     raeburn  1848:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1849:         my $now = time;
                   1850:         my $filepath = 'tmp/helprequests/'.$now;
                   1851:         my @parts=split(/\//,$filepath);
                   1852:         my $fullpath = $perlvar{'lonDaemons'};
                   1853:         for (my $i=0;$i<@parts;$i++) {
                   1854:             $fullpath .= '/'.$parts[$i];
                   1855:             if ((-e $fullpath)!=1) {
                   1856:                 mkdir($fullpath,0777);
                   1857:             }
                   1858:         }
                   1859:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1860:         print $fh $env{'form.'.$formname};
1.523     raeburn  1861:         close($fh);
1.741     raeburn  1862:         return $fullpath.'/'.$fname;
                   1863:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1864:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1865:                        '_'.$env{'user.domain'}.'/pending';
                   1866:         my @parts=split(/\//,$filepath);
                   1867:         my $fullpath = $perlvar{'lonDaemons'};
                   1868:         for (my $i=0;$i<@parts;$i++) {
                   1869:             $fullpath .= '/'.$parts[$i];
                   1870:             if ((-e $fullpath)!=1) {
                   1871:                 mkdir($fullpath,0777);
                   1872:             }
                   1873:         }
                   1874:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1875:         print $fh $env{'form.'.$formname};
                   1876:         close($fh);
                   1877:         return $fullpath.'/'.$fname;
1.523     raeburn  1878:     }
1.719     banghart 1879:     
1.258     www      1880: # Create the directory if not present
1.493     albertel 1881:     $fname="$subdir/$fname";
1.259     www      1882:     if ($coursedoc) {
1.638     albertel 1883: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1884: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1885:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1886:             return &finishuserfileupload($docuname,$docudom,
                   1887: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1888: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1889:         } else {
1.620     albertel 1890:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1891:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1892: 				       $fname,$formname,$parser,
                   1893: 				       $allfiles,$codebase);
1.481     raeburn  1894:         }
1.719     banghart 1895:     } elsif (defined($destuname)) {
                   1896:         my $docuname=$destuname;
                   1897:         my $docudom=$destudom;
1.860     raeburn  1898: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1899: 				     $parser,$allfiles,$codebase,
                   1900:                                      $thumbwidth,$thumbheight);
1.719     banghart 1901:         
1.259     www      1902:     } else {
1.638     albertel 1903:         my $docuname=$env{'user.name'};
                   1904:         my $docudom=$env{'user.domain'};
1.714     raeburn  1905:         if (exists($env{'form.group'})) {
                   1906:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1907:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1908:         }
1.860     raeburn  1909: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1910: 				     $parser,$allfiles,$codebase,
                   1911:                                      $thumbwidth,$thumbheight);
1.259     www      1912:     }
1.271     www      1913: }
                   1914: 
                   1915: sub finishuserfileupload {
1.860     raeburn  1916:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1917:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1918:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1919:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1920:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1921:     $file=$fname;
                   1922:     if ($fname=~m|/|) {
                   1923:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1924: 	$path.=$fnamepath.'/';
                   1925:     }
1.259     www      1926:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1927:     my $count;
                   1928:     for ($count=4;$count<=$#parts;$count++) {
                   1929:         $filepath.="/$parts[$count]";
                   1930:         if ((-e $filepath)!=1) {
                   1931: 	    mkdir($filepath,0777);
                   1932:         }
                   1933:     }
                   1934: # Save the file
                   1935:     {
1.701     albertel 1936: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1937: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1938: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1939: 	    return '/adm/notfound.html';
                   1940: 	}
                   1941: 	if (!print FH ($env{'form.'.$formname})) {
                   1942: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1943: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1944: 	    return '/adm/notfound.html';
                   1945: 	}
1.570     albertel 1946: 	close(FH);
1.258     www      1947:     }
1.637     raeburn  1948:     if ($parser eq 'parse') {
1.638     albertel 1949:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1950: 						   $codebase);
1.637     raeburn  1951:         unless ($parse_result eq 'ok') {
1.638     albertel 1952:             &logthis('Failed to parse '.$filepath.$file.
                   1953: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1954:         }
                   1955:     }
1.860     raeburn  1956:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1957:         my $input = $filepath.'/'.$file;
                   1958:         my $output = $filepath.'/'.'tn-'.$file;
                   1959:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1960:         system("convert -sample $thumbsize $input $output");
                   1961:         if (-e $filepath.'/'.'tn-'.$file) {
                   1962:             $fetchthumb  = 1; 
                   1963:         }
                   1964:     }
1.858     raeburn  1965:  
1.259     www      1966: # Notify homeserver to grep it
                   1967: #
1.638     albertel 1968:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1969:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1970:     if ($fetchresult eq 'ok') {
1.860     raeburn  1971:         if ($fetchthumb) {
                   1972:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1973:             if ($thumbresult ne 'ok') {
                   1974:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1975:                          $docuhome.': '.$thumbresult);
                   1976:             }
                   1977:         }
1.259     www      1978: #
1.258     www      1979: # Return the URL to it
1.494     albertel 1980:         return '/uploaded/'.$path.$file;
1.263     www      1981:     } else {
1.494     albertel 1982:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1983: 		 ': '.$fetchresult);
1.263     www      1984:         return '/adm/notfound.html';
1.858     raeburn  1985:     }
1.493     albertel 1986: }
                   1987: 
1.637     raeburn  1988: sub extract_embedded_items {
1.648     raeburn  1989:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1990:     my @state = ();
                   1991:     my %javafiles = (
                   1992:                       codebase => '',
                   1993:                       code => '',
                   1994:                       archive => ''
                   1995:                     );
                   1996:     my %mediafiles = (
                   1997:                       src => '',
                   1998:                       movie => '',
                   1999:                      );
1.648     raeburn  2000:     my $p;
                   2001:     if ($content) {
                   2002:         $p = HTML::LCParser->new($content);
                   2003:     } else {
                   2004:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2005:     }
1.641     albertel 2006:     while (my $t=$p->get_token()) {
1.640     albertel 2007: 	if ($t->[0] eq 'S') {
                   2008: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2009: 	    push(@state, $tagname);
1.648     raeburn  2010:             if (lc($tagname) eq 'allow') {
                   2011:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2012:             }
1.640     albertel 2013: 	    if (lc($tagname) eq 'img') {
                   2014: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2015: 	    }
1.886     albertel 2016: 	    if (lc($tagname) eq 'a') {
                   2017: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2018: 	    }
1.645     raeburn  2019:             if (lc($tagname) eq 'script') {
                   2020:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2021:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2022:                 } else {
                   2023:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2024:                 }
                   2025:             }
                   2026:             if (lc($tagname) eq 'link') {
                   2027:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2028:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2029:                 }
                   2030:             }
1.640     albertel 2031: 	    if (lc($tagname) eq 'object' ||
                   2032: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2033: 		foreach my $item (keys(%javafiles)) {
                   2034: 		    $javafiles{$item} = '';
                   2035: 		}
                   2036: 	    }
                   2037: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2038: 		my $name = lc($attr->{'name'});
                   2039: 		foreach my $item (keys(%javafiles)) {
                   2040: 		    if ($name eq $item) {
                   2041: 			$javafiles{$item} = $attr->{'value'};
                   2042: 			last;
                   2043: 		    }
                   2044: 		}
                   2045: 		foreach my $item (keys(%mediafiles)) {
                   2046: 		    if ($name eq $item) {
                   2047: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2048: 			last;
                   2049: 		    }
                   2050: 		}
                   2051: 	    }
                   2052: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2053: 		foreach my $item (keys(%javafiles)) {
                   2054: 		    if ($attr->{$item}) {
                   2055: 			$javafiles{$item} = $attr->{$item};
                   2056: 			last;
                   2057: 		    }
                   2058: 		}
                   2059: 		foreach my $item (keys(%mediafiles)) {
                   2060: 		    if ($attr->{$item}) {
                   2061: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2062: 			last;
                   2063: 		    }
                   2064: 		}
                   2065: 	    }
                   2066: 	} elsif ($t->[0] eq 'E') {
                   2067: 	    my ($tagname) = ($t->[1]);
                   2068: 	    if ($javafiles{'codebase'} ne '') {
                   2069: 		$javafiles{'codebase'} .= '/';
                   2070: 	    }  
                   2071: 	    if (lc($tagname) eq 'applet' ||
                   2072: 		lc($tagname) eq 'object' ||
                   2073: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2074: 		) {
                   2075: 		foreach my $item (keys(%javafiles)) {
                   2076: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2077: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2078: 			&add_filetype($allfiles,$file,$item);
                   2079: 		    }
                   2080: 		}
                   2081: 	    } 
                   2082: 	    pop @state;
                   2083: 	}
                   2084:     }
1.637     raeburn  2085:     return 'ok';
                   2086: }
                   2087: 
1.639     albertel 2088: sub add_filetype {
                   2089:     my ($allfiles,$file,$type)=@_;
                   2090:     if (exists($allfiles->{$file})) {
                   2091: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2092: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2093: 	}
                   2094:     } else {
                   2095: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2096:     }
                   2097: }
                   2098: 
1.493     albertel 2099: sub removeuploadedurl {
                   2100:     my ($url)=@_;
                   2101:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2102:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2103: }
                   2104: 
                   2105: sub removeuserfile {
                   2106:     my ($docuname,$docudom,$fname)=@_;
                   2107:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2108:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2109:     if ($result eq 'ok') {
                   2110:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2111:             my $metafile = $fname.'.meta';
                   2112:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2113: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2114:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2115:             my $sqlresult = 
1.823     albertel 2116:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2117:                                         'portfolio_metadata',$group,
                   2118:                                         'delete');
1.798     raeburn  2119:         }
                   2120:     }
                   2121:     return $result;
1.257     www      2122: }
1.15      www      2123: 
1.530     albertel 2124: sub mkdiruserfile {
                   2125:     my ($docuname,$docudom,$dir)=@_;
                   2126:     my $home=&homeserver($docuname,$docudom);
                   2127:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2128: }
                   2129: 
1.531     albertel 2130: sub renameuserfile {
                   2131:     my ($docuname,$docudom,$old,$new)=@_;
                   2132:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2133:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2134:                         &escape("$old").':'.&escape("$new"),$home);
                   2135:     if ($result eq 'ok') {
                   2136:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2137:             my $oldmeta = $old.'.meta';
                   2138:             my $newmeta = $new.'.meta';
                   2139:             my $metaresult = 
                   2140:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2141: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2142:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2143:             my $sqlresult = 
1.823     albertel 2144:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2145:                                         'portfolio_metadata',$group,
                   2146:                                         'delete');
1.798     raeburn  2147:         }
                   2148:     }
                   2149:     return $result;
1.531     albertel 2150: }
                   2151: 
1.14      www      2152: # ------------------------------------------------------------------------- Log
                   2153: 
                   2154: sub log {
                   2155:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2156:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2157: }
                   2158: 
                   2159: # ------------------------------------------------------------------ Course Log
1.352     www      2160: #
                   2161: # This routine flushes several buffers of non-mission-critical nature
                   2162: #
1.157     www      2163: 
                   2164: sub flushcourselogs {
1.352     www      2165:     &logthis('Flushing log buffers');
                   2166: #
                   2167: # course logs
                   2168: # This is a log of all transactions in a course, which can be used
                   2169: # for data mining purposes
                   2170: #
                   2171: # It also collects the courseid database, which lists last transaction
                   2172: # times and course titles for all courseids
                   2173: #
                   2174:     my %courseidbuffer=();
1.921   ! raeburn  2175:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2176:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2177: 		          &escape($courselogs{$crsid}),
                   2178: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2179: 	    delete $courselogs{$crsid};
                   2180:         } else {
                   2181:             &logthis('Failed to flush log buffer for '.$crsid);
                   2182:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2183:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2184:                         " exceeded maximum size, deleting.</font>");
                   2185:                delete $courselogs{$crsid};
                   2186:             }
1.352     www      2187:         }
1.920     raeburn  2188:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.918     raeburn  2189:             'description' => &escape($coursedescrbuf{$crsid}),
1.921   ! raeburn  2190:             'inst_code'    => &escape($courseinstcodebuf{$crsid}),
1.918     raeburn  2191:             'type'        => &escape($coursetypebuf{$crsid}),
                   2192:             'owner'       => &escape($courseownerbuf{$crsid}),
1.920     raeburn  2193:         };
1.191     harris41 2194:     }
1.352     www      2195: #
                   2196: # Write course id database (reverse lookup) to homeserver of courses 
                   2197: # Is used in pickcourse
                   2198: #
1.840     albertel 2199:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2200:         my $response = &courseidput(&host_domain($crs_home),
1.921   ! raeburn  2201:                                     $courseidbuffer{$crs_home},
        !          2202:                                     $crs_home,'timeonly');
1.352     www      2203:     }
                   2204: #
                   2205: # File accesses
                   2206: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2207: #
1.449     matthew  2208:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2209:         if ($entry =~ /___count$/) {
                   2210:             my ($dom,$name);
1.807     albertel 2211:             ($dom,$name,undef)=
1.811     albertel 2212: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2213:             if (! defined($dom) || $dom eq '' || 
                   2214:                 ! defined($name) || $name eq '') {
1.620     albertel 2215:                 my $cid = $env{'request.course.id'};
                   2216:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2217:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2218:             }
1.450     matthew  2219:             my $value = $accesshash{$entry};
                   2220:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2221:             my %temphash=($url => $value);
1.449     matthew  2222:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2223:             if ($result eq 'ok') {
                   2224:                 delete $accesshash{$entry};
                   2225:             } elsif ($result eq 'unknown_cmd') {
                   2226:                 # Target server has old code running on it.
1.450     matthew  2227:                 my %temphash=($entry => $value);
1.449     matthew  2228:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2229:                     delete $accesshash{$entry};
                   2230:                 }
                   2231:             }
                   2232:         } else {
1.811     albertel 2233:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2234:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2235:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2236:                 delete $accesshash{$entry};
                   2237:             }
1.185     www      2238:         }
1.191     harris41 2239:     }
1.352     www      2240: #
                   2241: # Roles
                   2242: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2243: #
1.800     albertel 2244:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2245:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2246: 	    split(/\:/,$entry);
                   2247:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2248:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2249:                 $rudom,$runame) eq 'ok') {
                   2250: 	    delete $userrolehash{$entry};
                   2251:         }
                   2252:     }
1.662     raeburn  2253: #
                   2254: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2255: #
                   2256:     my %domrolebuffer = ();
                   2257:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2258:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2259:         if ($domrolebuffer{$rudom}) {
                   2260:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2261:                       '='.&escape($domainrolehash{$entry});
                   2262:         } else {
                   2263:             $domrolebuffer{$rudom}.=&escape($entry).
                   2264:                       '='.&escape($domainrolehash{$entry});
                   2265:         }
                   2266:         delete $domainrolehash{$entry};
                   2267:     }
                   2268:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2269: 	my %servers = &get_servers($dom,'library');
                   2270: 	foreach my $tryserver (keys(%servers)) {
                   2271: 	    unless (&reply('domroleput:'.$dom.':'.
                   2272: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2273: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2274: 	    }
1.662     raeburn  2275:         }
                   2276:     }
1.186     www      2277:     $dumpcount++;
1.157     www      2278: }
                   2279: 
                   2280: sub courselog {
                   2281:     my $what=shift;
1.158     www      2282:     $what=time.':'.$what;
1.620     albertel 2283:     unless ($env{'request.course.id'}) { return ''; }
                   2284:     $coursedombuf{$env{'request.course.id'}}=
                   2285:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2286:     $coursenumbuf{$env{'request.course.id'}}=
                   2287:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2288:     $coursehombuf{$env{'request.course.id'}}=
                   2289:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2290:     $coursedescrbuf{$env{'request.course.id'}}=
                   2291:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2292:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2293:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2294:     $courseownerbuf{$env{'request.course.id'}}=
                   2295:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2296:     $coursetypebuf{$env{'request.course.id'}}=
                   2297:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2298:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2299: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2300:     } else {
1.620     albertel 2301: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2302:     }
1.620     albertel 2303:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2304: 	&flushcourselogs();
                   2305:     }
1.158     www      2306: }
                   2307: 
                   2308: sub courseacclog {
                   2309:     my $fnsymb=shift;
1.620     albertel 2310:     unless ($env{'request.course.id'}) { return ''; }
                   2311:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2312:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2313:         $what.=':POST';
1.583     matthew  2314:         # FIXME: Probably ought to escape things....
1.800     albertel 2315: 	foreach my $key (keys(%env)) {
                   2316:             if ($key=~/^form\.(.*)/) {
                   2317: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2318:             }
1.191     harris41 2319:         }
1.583     matthew  2320:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2321:         # FIXME: We should not be depending on a form parameter that someone
                   2322:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2323:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2324:             $what.= ':POST';
                   2325:             # FIXME: Probably ought to escape things....
                   2326:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2327:                                  'crsdiscuss') {
1.620     albertel 2328:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2329:             }
                   2330:         }
1.158     www      2331:     }
                   2332:     &courselog($what);
1.149     www      2333: }
                   2334: 
1.185     www      2335: sub countacc {
                   2336:     my $url=&declutter(shift);
1.458     matthew  2337:     return if (! defined($url) || $url eq '');
1.620     albertel 2338:     unless ($env{'request.course.id'}) { return ''; }
                   2339:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2340:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2341:     $accesshash{$key}++;
1.185     www      2342: }
1.349     www      2343: 
1.361     www      2344: sub linklog {
                   2345:     my ($from,$to)=@_;
                   2346:     $from=&declutter($from);
                   2347:     $to=&declutter($to);
                   2348:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2349:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2350: }
                   2351:   
1.349     www      2352: sub userrolelog {
                   2353:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2354:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2355:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2356:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2357:         ($trole=~/^ta/)) {
1.350     www      2358:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2359:        $userrolehash
                   2360:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2361:                     =$tend.':'.$tstart;
1.662     raeburn  2362:     }
1.898     albertel 2363:     if (($env{'request.role'} =~ /dc\./) &&
                   2364: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2365: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2366: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2367:        $userrolehash
                   2368:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2369:                     =$tend.':'.$tstart;
                   2370:     }
1.662     raeburn  2371:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2372:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2373:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2374:         ($trole=~/^sc/)) {
                   2375:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2376:        $domainrolehash
                   2377:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2378:                     = $tend.':'.$tstart;
                   2379:     }
1.351     www      2380: }
                   2381: 
                   2382: sub get_course_adv_roles {
                   2383:     my $cid=shift;
1.620     albertel 2384:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2385:     my %coursehash=&coursedescription($cid);
1.470     www      2386:     my %nothide=();
1.800     albertel 2387:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2388: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2389:     }
1.351     www      2390:     my %returnhash=();
                   2391:     my %dumphash=
                   2392:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2393:     my $now=time;
1.800     albertel 2394:     foreach my $entry (keys %dumphash) {
                   2395: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2396:         if (($tstart) && ($tstart<0)) { next; }
                   2397:         if (($tend) && ($tend<$now)) { next; }
                   2398:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2399:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2400: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2401: 	if ((&privileged($username,$domain)) && 
                   2402: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2403: 	if ($role eq 'cr') { next; }
1.351     www      2404:         my $key=&plaintext($role);
                   2405:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2406:         if ($returnhash{$key}) {
                   2407: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2408:         } else {
                   2409:             $returnhash{$key}=$username.':'.$domain;
                   2410:         }
1.400     www      2411:      }
                   2412:     return %returnhash;
                   2413: }
                   2414: 
                   2415: sub get_my_roles {
1.858     raeburn  2416:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2417:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2418:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2419:     my %dumphash;
                   2420:     if ($context eq 'userroles') { 
                   2421:         %dumphash = &dump('roles',$udom,$uname);
                   2422:     } else {
                   2423:         %dumphash=
1.400     www      2424:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2425:     }
1.400     www      2426:     my %returnhash=();
                   2427:     my $now=time;
1.800     albertel 2428:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2429:         my ($role,$tend,$tstart);
                   2430:         if ($context eq 'userroles') {
                   2431: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2432:         } else {
                   2433:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2434:         }
1.400     www      2435:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2436:         my $status = 'active';
                   2437:         if (($tend) && ($tend<$now)) {
                   2438:             $status = 'previous';
                   2439:         } 
                   2440:         if (($tstart) && ($now<$tstart)) {
                   2441:             $status = 'future';
                   2442:         }
                   2443:         if (ref($types) eq 'ARRAY') {
                   2444:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2445:                 next;
                   2446:             } 
                   2447:         } else {
                   2448:             if ($status ne 'active') {
                   2449:                 next;
                   2450:             }
                   2451:         }
1.867     raeburn  2452:         my ($rolecode,$username,$domain,$section,$area);
                   2453:         if ($context eq 'userroles') {
                   2454:             ($area,$rolecode) = split(/_/,$entry);
                   2455:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2456:         } else {
                   2457:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2458:         }
1.832     raeburn  2459:         if (ref($roledoms) eq 'ARRAY') {
                   2460:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2461:                 next;
                   2462:             }
                   2463:         }
                   2464:         if (ref($roles) eq 'ARRAY') {
                   2465:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2466:                 next;
                   2467:             }
1.867     raeburn  2468:         }
1.400     www      2469: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2470:     }
1.373     www      2471:     return %returnhash;
1.399     www      2472: }
                   2473: 
                   2474: # ----------------------------------------------------- Frontpage Announcements
                   2475: #
                   2476: #
                   2477: 
                   2478: sub postannounce {
                   2479:     my ($server,$text)=@_;
1.844     albertel 2480:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2481:     unless ($text=~/\w/) { $text=''; }
                   2482:     return &reply('setannounce:'.&escape($text),$server);
                   2483: }
                   2484: 
                   2485: sub getannounce {
1.448     albertel 2486: 
                   2487:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2488: 	my $announcement='';
1.800     albertel 2489: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2490: 	close($fh);
1.399     www      2491: 	if ($announcement=~/\w/) { 
                   2492: 	    return 
                   2493:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2494:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2495: 	} else {
                   2496: 	    return '';
                   2497: 	}
                   2498:     } else {
                   2499: 	return '';
                   2500:     }
1.351     www      2501: }
1.353     www      2502: 
                   2503: # ---------------------------------------------------------- Course ID routines
                   2504: # Deal with domain's nohist_courseid.db files
                   2505: #
                   2506: 
                   2507: sub courseidput {
1.921   ! raeburn  2508:     my ($domain,$storehash,$coursehome,$caller) = @_;
        !          2509:     my $outcome;
        !          2510:     if ($caller eq 'timeonly') {
        !          2511:         my $cids = '';
        !          2512:         foreach my $item (keys(%$storehash)) {
        !          2513:             $cids.=&escape($item).'&';
        !          2514:         }
        !          2515:         $cids=~s/\&$//;
        !          2516:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
        !          2517:                           $coursehome);       
        !          2518:     } else {
        !          2519:         my $items = '';
        !          2520:         foreach my $item (keys(%$storehash)) {
        !          2521:             $items.= &escape($item).'='.
        !          2522:                      &freeze_escape($$storehash{$item}).'&';
        !          2523:         }
        !          2524:         $items=~s/\&$//;
        !          2525:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
        !          2526:                           $coursehome);
1.918     raeburn  2527:     }
                   2528:     if ($outcome eq 'unknown_cmd') {
                   2529:         my $what;
                   2530:         foreach my $cid (keys(%$storehash)) {
                   2531:             $what .= &escape($cid).'=';
1.921   ! raeburn  2532:             foreach my $item ('description','inst_code','owner','type') {
        !          2533:                 $what .= &escape($storehash->{$item}).':';
1.918     raeburn  2534:             }
                   2535:             $what =~ s/\:$/&/;
                   2536:         }
                   2537:         $what =~ s/\&$//;  
                   2538:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2539:     } else {
                   2540:         return $outcome;
                   2541:     }
1.353     www      2542: }
                   2543: 
                   2544: sub courseiddump {
1.921   ! raeburn  2545:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
        !          2546:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.918     raeburn  2547:     my $as_hash = 1;
                   2548:     my %returnhash;
                   2549:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2550:     my %libserv = &all_library();
                   2551:     foreach my $tryserver (keys(%libserv)) {
                   2552:         if ( (  $hostidflag == 1 
                   2553: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2554: 	     || (!defined($hostidflag)) ) {
                   2555: 
1.918     raeburn  2556: 	    if (($domfilter eq '') ||
                   2557: 		(&host_domain($tryserver) eq $domfilter)) {
                   2558:                 my $rep = 
                   2559:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2560:                          $sincefilter.':'.&escape($descfilter).':'.
                   2561:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2562:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.921   ! raeburn  2563:                          ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
1.918     raeburn  2564:                 my @pairs=split(/\&/,$rep);
                   2565:                 foreach my $item (@pairs) {
                   2566:                     my ($key,$value)=split(/\=/,$item,2);
                   2567:                     $key = &unescape($key);
                   2568:                     next if ($key =~ /^error: 2 /);
                   2569:                     my $result = &thaw_unescape($value);
                   2570:                     if (ref($result) eq 'HASH') {
                   2571:                         $returnhash{$key}=$result;
                   2572:                     } else {
1.921   ! raeburn  2573:                         my @responses = split(/:/,$value);
        !          2574:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2575:                         for (my $i=0; $i<@responses; $i++) {
1.921   ! raeburn  2576:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2577:                         }
                   2578:                     } 
1.353     www      2579:                 }
                   2580:             }
                   2581:         }
                   2582:     }
                   2583:     return %returnhash;
                   2584: }
                   2585: 
1.658     raeburn  2586: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2587: 
                   2588: sub dcmailput {
1.685     raeburn  2589:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2590:     my $status = &Apache::lonnet::critical(
1.740     www      2591:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2592:        &escape($message),$server);
1.662     raeburn  2593:     return $status;
                   2594: }
                   2595: 
1.658     raeburn  2596: sub dcmaildump {
                   2597:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2598:     my %returnhash=();
1.846     albertel 2599: 
                   2600:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2601:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2602:                                                          &escape($enddate).':';
                   2603: 	my @esc_senders=map { &escape($_)} @$senders;
                   2604: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2605: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2606:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2607:             if (($key) && ($value)) {
                   2608:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2609:             }
                   2610:         }
                   2611:     }
                   2612:     return %returnhash;
                   2613: }
1.662     raeburn  2614: # ---------------------------------------------------------- Domain roles
                   2615: 
                   2616: sub get_domain_roles {
                   2617:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2618:     if (undef($startdate) || $startdate eq '') {
                   2619:         $startdate = '.';
                   2620:     }
                   2621:     if (undef($enddate) || $enddate eq '') {
                   2622:         $enddate = '.';
                   2623:     }
                   2624:     my $rolelist = join(':',@{$roles});
                   2625:     my %personnel = ();
1.841     albertel 2626: 
                   2627:     my %servers = &get_servers($dom,'library');
                   2628:     foreach my $tryserver (keys(%servers)) {
                   2629: 	%{$personnel{$tryserver}}=();
                   2630: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2631: 					    &escape($startdate).':'.
                   2632: 					    &escape($enddate).':'.
                   2633: 					    &escape($rolelist), $tryserver))) {
                   2634: 	    my ($key,$value) = split(/\=/,$line,2);
                   2635: 	    if (($key) && ($value)) {
                   2636: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2637: 	    }
                   2638: 	}
1.662     raeburn  2639:     }
                   2640:     return %personnel;
                   2641: }
1.658     raeburn  2642: 
1.149     www      2643: # ----------------------------------------------------------- Check out an item
                   2644: 
1.504     albertel 2645: sub get_first_access {
                   2646:     my ($type,$argsymb)=@_;
1.790     albertel 2647:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2648:     if ($argsymb) { $symb=$argsymb; }
                   2649:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2650:     if ($type eq 'map') {
                   2651: 	$res=&symbread($map);
                   2652:     } else {
                   2653: 	$res=$symb;
                   2654:     }
                   2655:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2656:     return $times{"$courseid\0$res"};
1.504     albertel 2657: }
                   2658: 
                   2659: sub set_first_access {
                   2660:     my ($type)=@_;
1.790     albertel 2661:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2662:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2663:     if ($type eq 'map') {
                   2664: 	$res=&symbread($map);
                   2665:     } else {
                   2666: 	$res=$symb;
                   2667:     }
                   2668:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2669:     if (!$firstaccess) {
1.588     albertel 2670: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2671:     }
                   2672:     return 'already_set';
1.504     albertel 2673: }
                   2674: 
1.149     www      2675: sub checkout {
                   2676:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2677:     my $now=time;
                   2678:     my $lonhost=$perlvar{'lonHostID'};
                   2679:     my $infostr=&escape(
1.234     www      2680:                  'CHECKOUTTOKEN&'.
1.149     www      2681:                  $tuname.'&'.
                   2682:                  $tudom.'&'.
                   2683:                  $tcrsid.'&'.
                   2684:                  $symb.'&'.
                   2685: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2686:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2687:     if ($token=~/^error\:/) { 
1.672     albertel 2688:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2689:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2690:                  "</font>");
                   2691:         return ''; 
                   2692:     }
                   2693: 
1.149     www      2694:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2695:     $token=~tr/a-z/A-Z/;
                   2696: 
1.153     www      2697:     my %infohash=('resource.0.outtoken' => $token,
                   2698:                   'resource.0.checkouttime' => $now,
                   2699:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2700: 
                   2701:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2702:        return '';
1.151     www      2703:     } else {
1.672     albertel 2704:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2705:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2706:                  "</font>");
1.149     www      2707:     }    
                   2708: 
                   2709:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2710:                          &escape('Checkout '.$infostr.' - '.
                   2711:                                                  $token)) ne 'ok') {
                   2712: 	return '';
1.151     www      2713:     } else {
1.672     albertel 2714:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2715:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2716:                  "</font>");
1.149     www      2717:     }
1.151     www      2718:     return $token;
1.149     www      2719: }
                   2720: 
                   2721: # ------------------------------------------------------------ Check in an item
                   2722: 
                   2723: sub checkin {
                   2724:     my $token=shift;
1.150     www      2725:     my $now=time;
                   2726:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2727:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2728:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2729:     $dtoken=~s/\W/\_/g;
1.234     www      2730:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2731:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2732: 
1.154     www      2733:     unless (($tuname) && ($tudom)) {
                   2734:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2735:         return '';
                   2736:     }
                   2737:     
                   2738:     unless (&allowed('mgr',$tcrsid)) {
                   2739:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2740:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2741:         return '';
                   2742:     }
                   2743: 
1.153     www      2744:     my %infohash=('resource.0.intoken' => $token,
                   2745:                   'resource.0.checkintime' => $now,
                   2746:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2747: 
                   2748:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2749:        return '';
                   2750:     }    
                   2751: 
                   2752:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2753:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2754: 	return '';
                   2755:     }
                   2756: 
                   2757:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2758: }
                   2759: 
                   2760: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2761: 
                   2762: sub expirespread {
                   2763:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2764:     my $cid=$env{'request.course.id'}; 
1.110     www      2765:     if ($cid) {
                   2766:        my $now=time;
                   2767:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2768:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2769:                             $env{'course.'.$cid.'.num'}.
1.110     www      2770: 	        	    ':nohist_expirationdates:'.
                   2771:                             &escape($key).'='.$now,
1.620     albertel 2772:                             $env{'course.'.$cid.'.home'})
1.110     www      2773:     }
                   2774:     return 'ok';
1.14      www      2775: }
                   2776: 
1.109     www      2777: # ----------------------------------------------------- Devalidate Spreadsheets
                   2778: 
                   2779: sub devalidate {
1.325     www      2780:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2781:     my $cid=$env{'request.course.id'}; 
1.109     www      2782:     if ($cid) {
1.391     matthew  2783:         # delete the stored spreadsheets for
                   2784:         # - the student level sheet of this user in course's homespace
                   2785:         # - the assessment level sheet for this resource 
                   2786:         #   for this user in user's homespace
1.553     albertel 2787: 	# - current conditional state info
1.325     www      2788: 	my $key=$uname.':'.$udom.':';
1.109     www      2789:         my $status=
1.299     matthew  2790: 	    &del('nohist_calculatedsheets',
1.391     matthew  2791: 		 [$key.'studentcalc:'],
1.620     albertel 2792: 		 $env{'course.'.$cid.'.domain'},
                   2793: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2794: 		.' '.
                   2795: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2796: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2797:         unless ($status eq 'ok ok') {
                   2798:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2799:                     $uname.' at '.$udom.' for '.
1.109     www      2800: 		    $symb.': '.$status);
1.133     albertel 2801:         }
1.553     albertel 2802: 	&delenv('user.state.'.$cid);
1.109     www      2803:     }
                   2804: }
                   2805: 
1.265     albertel 2806: sub get_scalar {
                   2807:     my ($string,$end) = @_;
                   2808:     my $value;
                   2809:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2810: 	$value = $1;
                   2811:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2812: 	$value = $1;
                   2813:     }
                   2814:     return &unescape($value);
                   2815: }
                   2816: 
                   2817: sub array2str {
                   2818:   my (@array) = @_;
                   2819:   my $result=&arrayref2str(\@array);
                   2820:   $result=~s/^__ARRAY_REF__//;
                   2821:   $result=~s/__END_ARRAY_REF__$//;
                   2822:   return $result;
                   2823: }
                   2824: 
1.204     albertel 2825: sub arrayref2str {
                   2826:   my ($arrayref) = @_;
1.265     albertel 2827:   my $result='__ARRAY_REF__';
1.204     albertel 2828:   foreach my $elem (@$arrayref) {
1.265     albertel 2829:     if(ref($elem) eq 'ARRAY') {
                   2830:       $result.=&arrayref2str($elem).'&';
                   2831:     } elsif(ref($elem) eq 'HASH') {
                   2832:       $result.=&hashref2str($elem).'&';
                   2833:     } elsif(ref($elem)) {
                   2834:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2835:     } else {
                   2836:       $result.=&escape($elem).'&';
                   2837:     }
                   2838:   }
                   2839:   $result=~s/\&$//;
1.265     albertel 2840:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2841:   return $result;
                   2842: }
                   2843: 
1.168     albertel 2844: sub hash2str {
1.204     albertel 2845:   my (%hash) = @_;
                   2846:   my $result=&hashref2str(\%hash);
1.265     albertel 2847:   $result=~s/^__HASH_REF__//;
                   2848:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2849:   return $result;
                   2850: }
                   2851: 
                   2852: sub hashref2str {
                   2853:   my ($hashref)=@_;
1.265     albertel 2854:   my $result='__HASH_REF__';
1.800     albertel 2855:   foreach my $key (sort(keys(%$hashref))) {
                   2856:     if (ref($key) eq 'ARRAY') {
                   2857:       $result.=&arrayref2str($key).'=';
                   2858:     } elsif (ref($key) eq 'HASH') {
                   2859:       $result.=&hashref2str($key).'=';
                   2860:     } elsif (ref($key)) {
1.265     albertel 2861:       $result.='=';
1.800     albertel 2862:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2863:     } else {
1.800     albertel 2864: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2865:     }
                   2866: 
1.800     albertel 2867:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2868:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2869:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2870:       $result.=&hashref2str($hashref->{$key}).'&';
                   2871:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2872:        $result.='&';
1.800     albertel 2873:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2874:     } else {
1.800     albertel 2875:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2876:     }
                   2877:   }
1.168     albertel 2878:   $result=~s/\&$//;
1.265     albertel 2879:   $result .= '__END_HASH_REF__';
1.168     albertel 2880:   return $result;
                   2881: }
                   2882: 
                   2883: sub str2hash {
1.265     albertel 2884:     my ($string)=@_;
                   2885:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2886:     return %$hash;
                   2887: }
                   2888: 
                   2889: sub str2hashref {
1.168     albertel 2890:   my ($string) = @_;
1.265     albertel 2891: 
                   2892:   my %hash;
                   2893: 
                   2894:   if($string !~ /^__HASH_REF__/) {
                   2895:       if (! ($string eq '' || !defined($string))) {
                   2896: 	  $hash{'error'}='Not hash reference';
                   2897:       }
                   2898:       return (\%hash, $string);
                   2899:   }
                   2900: 
                   2901:   $string =~ s/^__HASH_REF__//;
                   2902: 
                   2903:   while($string !~ /^__END_HASH_REF__/) {
                   2904:       #key
                   2905:       my $key='';
                   2906:       if($string =~ /^__HASH_REF__/) {
                   2907:           ($key, $string)=&str2hashref($string);
                   2908:           if(defined($key->{'error'})) {
                   2909:               $hash{'error'}='Bad data';
                   2910:               return (\%hash, $string);
                   2911:           }
                   2912:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2913:           ($key, $string)=&str2arrayref($string);
                   2914:           if($key->[0] eq 'Array reference error') {
                   2915:               $hash{'error'}='Bad data';
                   2916:               return (\%hash, $string);
                   2917:           }
                   2918:       } else {
                   2919:           $string =~ s/^(.*?)=//;
1.267     albertel 2920: 	  $key=&unescape($1);
1.265     albertel 2921:       }
                   2922:       $string =~ s/^=//;
                   2923: 
                   2924:       #value
                   2925:       my $value='';
                   2926:       if($string =~ /^__HASH_REF__/) {
                   2927:           ($value, $string)=&str2hashref($string);
                   2928:           if(defined($value->{'error'})) {
                   2929:               $hash{'error'}='Bad data';
                   2930:               return (\%hash, $string);
                   2931:           }
                   2932:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2933:           ($value, $string)=&str2arrayref($string);
                   2934:           if($value->[0] eq 'Array reference error') {
                   2935:               $hash{'error'}='Bad data';
                   2936:               return (\%hash, $string);
                   2937:           }
                   2938:       } else {
                   2939: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2940:       }
                   2941:       $string =~ s/^&//;
                   2942: 
                   2943:       $hash{$key}=$value;
1.204     albertel 2944:   }
1.265     albertel 2945: 
                   2946:   $string =~ s/^__END_HASH_REF__//;
                   2947: 
                   2948:   return (\%hash, $string);
1.204     albertel 2949: }
                   2950: 
                   2951: sub str2array {
1.265     albertel 2952:     my ($string)=@_;
                   2953:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2954:     return @$array;
                   2955: }
                   2956: 
                   2957: sub str2arrayref {
1.204     albertel 2958:   my ($string) = @_;
1.265     albertel 2959:   my @array;
                   2960: 
                   2961:   if($string !~ /^__ARRAY_REF__/) {
                   2962:       if (! ($string eq '' || !defined($string))) {
                   2963: 	  $array[0]='Array reference error';
                   2964:       }
                   2965:       return (\@array, $string);
                   2966:   }
                   2967: 
                   2968:   $string =~ s/^__ARRAY_REF__//;
                   2969: 
                   2970:   while($string !~ /^__END_ARRAY_REF__/) {
                   2971:       my $value='';
                   2972:       if($string =~ /^__HASH_REF__/) {
                   2973:           ($value, $string)=&str2hashref($string);
                   2974:           if(defined($value->{'error'})) {
                   2975:               $array[0] ='Array reference error';
                   2976:               return (\@array, $string);
                   2977:           }
                   2978:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2979:           ($value, $string)=&str2arrayref($string);
                   2980:           if($value->[0] eq 'Array reference error') {
                   2981:               $array[0] ='Array reference error';
                   2982:               return (\@array, $string);
                   2983:           }
                   2984:       } else {
                   2985: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2986:       }
                   2987:       $string =~ s/^&//;
                   2988: 
                   2989:       push(@array, $value);
1.191     harris41 2990:   }
1.265     albertel 2991: 
                   2992:   $string =~ s/^__END_ARRAY_REF__//;
                   2993: 
                   2994:   return (\@array, $string);
1.168     albertel 2995: }
                   2996: 
1.167     albertel 2997: # -------------------------------------------------------------------Temp Store
                   2998: 
1.168     albertel 2999: sub tmpreset {
                   3000:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3001:   if (!$symb) {
                   3002:     $symb=&symbread();
1.620     albertel 3003:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3004:   }
                   3005:   $symb=escape($symb);
                   3006: 
1.620     albertel 3007:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3008:   $namespace=~s/\//\_/g;
                   3009:   $namespace=~s/\W//g;
                   3010: 
1.620     albertel 3011:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3012:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3013:   if ($domain eq 'public' && $stuname eq 'public') {
                   3014:       $stuname=$ENV{'REMOTE_ADDR'};
                   3015:   }
1.168     albertel 3016:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3017:   my %hash;
                   3018:   if (tie(%hash,'GDBM_File',
                   3019: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3020: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3021:     foreach my $key (keys %hash) {
1.180     albertel 3022:       if ($key=~ /:$symb/) {
1.168     albertel 3023: 	delete($hash{$key});
                   3024:       }
                   3025:     }
                   3026:   }
                   3027: }
                   3028: 
1.167     albertel 3029: sub tmpstore {
1.168     albertel 3030:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3031: 
                   3032:   if (!$symb) {
                   3033:     $symb=&symbread();
1.620     albertel 3034:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3035:   }
                   3036:   $symb=escape($symb);
                   3037: 
                   3038:   if (!$namespace) {
                   3039:     # I don't think we would ever want to store this for a course.
                   3040:     # it seems this will only be used if we don't have a course.
1.620     albertel 3041:     #$namespace=$env{'request.course.id'};
1.168     albertel 3042:     #if (!$namespace) {
1.620     albertel 3043:       $namespace=$env{'request.state'};
1.168     albertel 3044:     #}
                   3045:   }
                   3046:   $namespace=~s/\//\_/g;
                   3047:   $namespace=~s/\W//g;
1.620     albertel 3048:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3049:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3050:   if ($domain eq 'public' && $stuname eq 'public') {
                   3051:       $stuname=$ENV{'REMOTE_ADDR'};
                   3052:   }
1.168     albertel 3053:   my $now=time;
                   3054:   my %hash;
                   3055:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3056:   if (tie(%hash,'GDBM_File',
                   3057: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3058: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3059:     $hash{"version:$symb"}++;
                   3060:     my $version=$hash{"version:$symb"};
                   3061:     my $allkeys=''; 
                   3062:     foreach my $key (keys(%$storehash)) {
                   3063:       $allkeys.=$key.':';
1.591     albertel 3064:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3065:     }
                   3066:     $hash{"$version:$symb:timestamp"}=$now;
                   3067:     $allkeys.='timestamp';
                   3068:     $hash{"$version:keys:$symb"}=$allkeys;
                   3069:     if (untie(%hash)) {
                   3070:       return 'ok';
                   3071:     } else {
                   3072:       return "error:$!";
                   3073:     }
                   3074:   } else {
                   3075:     return "error:$!";
                   3076:   }
                   3077: }
1.167     albertel 3078: 
1.168     albertel 3079: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3080: 
1.168     albertel 3081: sub tmprestore {
                   3082:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3083: 
1.168     albertel 3084:   if (!$symb) {
                   3085:     $symb=&symbread();
1.620     albertel 3086:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3087:   }
                   3088:   $symb=escape($symb);
                   3089: 
1.620     albertel 3090:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3091: 
1.620     albertel 3092:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3093:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3094:   if ($domain eq 'public' && $stuname eq 'public') {
                   3095:       $stuname=$ENV{'REMOTE_ADDR'};
                   3096:   }
1.168     albertel 3097:   my %returnhash;
                   3098:   $namespace=~s/\//\_/g;
                   3099:   $namespace=~s/\W//g;
                   3100:   my %hash;
                   3101:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3102:   if (tie(%hash,'GDBM_File',
                   3103: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3104: 	  &GDBM_READER(),0640)) {
1.168     albertel 3105:     my $version=$hash{"version:$symb"};
                   3106:     $returnhash{'version'}=$version;
                   3107:     my $scope;
                   3108:     for ($scope=1;$scope<=$version;$scope++) {
                   3109:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3110:       my @keys=split(/:/,$vkeys);
                   3111:       my $key;
                   3112:       $returnhash{"$scope:keys"}=$vkeys;
                   3113:       foreach $key (@keys) {
1.591     albertel 3114: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3115: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3116:       }
                   3117:     }
1.168     albertel 3118:     if (!(untie(%hash))) {
                   3119:       return "error:$!";
                   3120:     }
                   3121:   } else {
                   3122:     return "error:$!";
                   3123:   }
                   3124:   return %returnhash;
1.167     albertel 3125: }
                   3126: 
1.9       www      3127: # ----------------------------------------------------------------------- Store
                   3128: 
                   3129: sub store {
1.124     www      3130:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3131:     my $home='';
                   3132: 
1.168     albertel 3133:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3134: 
1.213     www      3135:     $symb=&symbclean($symb);
1.122     albertel 3136:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3137: 
1.620     albertel 3138:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3139:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3140: 
                   3141:     &devalidate($symb,$stuname,$domain);
1.109     www      3142: 
                   3143:     $symb=escape($symb);
1.187     www      3144:     if (!$namespace) { 
1.620     albertel 3145:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3146:           return ''; 
                   3147:        } 
                   3148:     }
1.620     albertel 3149:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3150: 
                   3151:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3152:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3153: 
1.12      www      3154:     my $namevalue='';
1.800     albertel 3155:     foreach my $key (keys(%$storehash)) {
                   3156:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3157:     }
1.12      www      3158:     $namevalue=~s/\&$//;
1.187     www      3159:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3160:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3161: }
                   3162: 
1.47      www      3163: # -------------------------------------------------------------- Critical Store
                   3164: 
                   3165: sub cstore {
1.124     www      3166:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3167:     my $home='';
                   3168: 
1.168     albertel 3169:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3170: 
1.213     www      3171:     $symb=&symbclean($symb);
1.122     albertel 3172:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3173: 
1.620     albertel 3174:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3175:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3176: 
                   3177:     &devalidate($symb,$stuname,$domain);
1.109     www      3178: 
                   3179:     $symb=escape($symb);
1.187     www      3180:     if (!$namespace) { 
1.620     albertel 3181:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3182:           return ''; 
                   3183:        } 
                   3184:     }
1.620     albertel 3185:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3186: 
                   3187:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3188:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3189: 
1.47      www      3190:     my $namevalue='';
1.800     albertel 3191:     foreach my $key (keys(%$storehash)) {
                   3192:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3193:     }
1.47      www      3194:     $namevalue=~s/\&$//;
1.187     www      3195:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3196:     return critical
                   3197:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3198: }
                   3199: 
1.9       www      3200: # --------------------------------------------------------------------- Restore
                   3201: 
                   3202: sub restore {
1.124     www      3203:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3204:     my $home='';
                   3205: 
1.168     albertel 3206:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3207: 
1.122     albertel 3208:     if (!$symb) {
                   3209:       unless ($symb=escape(&symbread())) { return ''; }
                   3210:     } else {
1.213     www      3211:       $symb=&escape(&symbclean($symb));
1.122     albertel 3212:     }
1.188     www      3213:     if (!$namespace) { 
1.620     albertel 3214:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3215:           return ''; 
                   3216:        } 
                   3217:     }
1.620     albertel 3218:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3219:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3220:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3221:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3222: 
1.12      www      3223:     my %returnhash=();
1.800     albertel 3224:     foreach my $line (split(/\&/,$answer)) {
                   3225: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3226:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3227:     }
1.75      www      3228:     my $version;
                   3229:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3230:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3231:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3232:        }
1.75      www      3233:     }
1.13      www      3234:     return %returnhash;
1.34      www      3235: }
                   3236: 
                   3237: # ---------------------------------------------------------- Course Description
                   3238: 
                   3239: sub coursedescription {
1.731     albertel 3240:     my ($courseid,$args)=@_;
1.34      www      3241:     $courseid=~s/^\///;
1.49      www      3242:     $courseid=~s/\_/\//g;
1.34      www      3243:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3244:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3245:     my $normalid=$cdomain.'_'.$cnum;
                   3246:     # need to always cache even if we get errors otherwise we keep 
                   3247:     # trying and trying and trying to get the course description.
                   3248:     my %envhash=();
                   3249:     my %returnhash=();
1.731     albertel 3250:     
                   3251:     my $expiretime=600;
                   3252:     if ($env{'request.course.id'} eq $normalid) {
                   3253: 	$expiretime=120;
                   3254:     }
                   3255: 
                   3256:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3257:     if (!$args->{'freshen_cache'}
                   3258: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3259: 	foreach my $key (keys(%env)) {
                   3260: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3261: 	    my ($setting) = $1;
                   3262: 	    $returnhash{$setting} = $env{$key};
                   3263: 	}
                   3264: 	return %returnhash;
                   3265:     }
                   3266: 
                   3267:     # get the data agin
                   3268:     if (!$args->{'one_time'}) {
                   3269: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3270:     }
1.811     albertel 3271: 
1.34      www      3272:     if ($chome ne 'no_host') {
1.302     albertel 3273:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3274:        if (!exists($returnhash{'con_lost'})) {
                   3275:            $returnhash{'home'}= $chome;
                   3276: 	   $returnhash{'domain'} = $cdomain;
                   3277: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3278:            if (!defined($returnhash{'type'})) {
                   3279:                $returnhash{'type'} = 'Course';
                   3280:            }
1.130     albertel 3281:            while (my ($name,$value) = each %returnhash) {
1.53      www      3282:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3283:            }
1.270     www      3284:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3285:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3286: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3287:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3288:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3289:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3290:        }
                   3291:     }
1.731     albertel 3292:     if (!$args->{'one_time'}) {
                   3293: 	&appenv(%envhash);
                   3294:     }
1.302     albertel 3295:     return %returnhash;
1.461     www      3296: }
                   3297: 
                   3298: # -------------------------------------------------See if a user is privileged
                   3299: 
                   3300: sub privileged {
                   3301:     my ($username,$domain)=@_;
                   3302:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3303: 			&homeserver($username,$domain));
                   3304:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3305:     my $now=time;
                   3306:     if ($rolesdump ne '') {
1.800     albertel 3307:         foreach my $entry (split(/&/,$rolesdump)) {
                   3308: 	    if ($entry!~/^rolesdef_/) {
                   3309: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3310: 		$area=~s/\_\w\w$//;
                   3311: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3312: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3313: 		    my $active=1;
                   3314: 		    if ($tend) {
                   3315: 			if ($tend<$now) { $active=0; }
                   3316: 		    }
                   3317: 		    if ($tstart) {
                   3318: 			if ($tstart>$now) { $active=0; }
                   3319: 		    }
                   3320: 		    if ($active) { return 1; }
                   3321: 		}
                   3322: 	    }
                   3323: 	}
                   3324:     }
                   3325:     return 0;
1.9       www      3326: }
1.1       albertel 3327: 
1.103     harris41 3328: # -------------------------------------------------------- Get user privileges
1.11      www      3329: 
                   3330: sub rolesinit {
                   3331:     my ($domain,$username,$authhost)=@_;
                   3332:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3333:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3334:     my %allroles=();
1.678     raeburn  3335:     my %allgroups=();   
1.11      www      3336:     my $now=time;
1.743     albertel 3337:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3338:     my $group_privs;
1.11      www      3339: 
                   3340:     if ($rolesdump ne '') {
1.800     albertel 3341:         foreach my $entry (split(/&/,$rolesdump)) {
                   3342: 	  if ($entry!~/^rolesdef_/) {
                   3343:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3344: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3345:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3346: 	    if ($role=~/^cr/) { 
1.807     albertel 3347: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3348: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3349: 		    ($tend,$tstart)=split('_',$trest);
                   3350: 		} else {
                   3351: 		    $trole=$role;
                   3352: 		}
1.678     raeburn  3353:             } elsif ($role =~ m|^gr/|) {
                   3354:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3355:                 ($trole,$group_privs) = split(/\//,$trole);
                   3356:                 $group_privs = &unescape($group_privs);
1.587     albertel 3357: 	    } else {
                   3358: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3359: 	    }
1.743     albertel 3360: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3361: 					 $username);
                   3362: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3363:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3364:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3365:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3366: 		my $spec=$trole.'.'.$area;
                   3367: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3368: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3369:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3370:                 } elsif ($trole eq 'gr') {
                   3371:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3372: 		} else {
1.567     raeburn  3373:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3374: 		}
1.12      www      3375:             }
1.662     raeburn  3376:           }
1.191     harris41 3377:         }
1.743     albertel 3378:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3379:         $userroles{'user.adv'}    = $adv;
                   3380: 	$userroles{'user.author'} = $author;
1.620     albertel 3381:         $env{'user.adv'}=$adv;
1.11      www      3382:     }
1.743     albertel 3383:     return \%userroles;  
1.11      www      3384: }
                   3385: 
1.567     raeburn  3386: sub set_arearole {
                   3387:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3388: # log the associated role with the area
                   3389:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3390:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3391: }
                   3392: 
                   3393: sub custom_roleprivs {
                   3394:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3395:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3396:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3397:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3398:         my ($rdummy,$roledef)=
                   3399:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3400:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3401:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3402:             if (defined($syspriv)) {
                   3403:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3404:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3405:             }
                   3406:             if ($tdomain ne '') {
                   3407:                 if (defined($dompriv)) {
                   3408:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3409:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3410:                 }
                   3411:                 if (($trest ne '') && (defined($coursepriv))) {
                   3412:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3413:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3414:                 }
                   3415:             }
                   3416:         }
                   3417:     }
                   3418: }
                   3419: 
1.678     raeburn  3420: sub group_roleprivs {
                   3421:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3422:     my $access = 1;
                   3423:     my $now = time;
                   3424:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3425:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3426:     if ($access) {
1.811     albertel 3427:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3428:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3429:     }
                   3430: }
1.567     raeburn  3431: 
                   3432: sub standard_roleprivs {
                   3433:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3434:     if (defined($pr{$trole.':s'})) {
                   3435:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3436:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3437:     }
                   3438:     if ($tdomain ne '') {
                   3439:         if (defined($pr{$trole.':d'})) {
                   3440:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3441:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3442:         }
                   3443:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3444:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3445:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3446:         }
                   3447:     }
                   3448: }
                   3449: 
                   3450: sub set_userprivs {
1.678     raeburn  3451:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3452:     my $author=0;
                   3453:     my $adv=0;
1.678     raeburn  3454:     my %grouproles = ();
                   3455:     if (keys(%{$allgroups}) > 0) {
                   3456:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3457:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3458:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3459:                 $trole = $1;
                   3460:                 $area = $2;
1.681     raeburn  3461:                 $sec = $3;
                   3462:                 $extendedarea = $area.$sec;
                   3463:                 if (exists($$allgroups{$area})) {
                   3464:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3465:                         my $spec = $trole.'.'.$extendedarea;
                   3466:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3467:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3468:                     }
                   3469:                 }
                   3470:             }
                   3471:         }
                   3472:     }
1.800     albertel 3473:     foreach my $group (keys(%grouproles)) {
                   3474:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3475:     }
1.800     albertel 3476:     foreach my $role (keys(%{$allroles})) {
                   3477:         my %thesepriv;
                   3478:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3479:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3480:             if ($item ne '') {
                   3481:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3482:                 if ($restrictions eq '') {
                   3483:                     $thesepriv{$privilege}='F';
                   3484:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3485:                     $thesepriv{$privilege}.=$restrictions;
                   3486:                 }
                   3487:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3488:             }
                   3489:         }
                   3490:         my $thesestr='';
1.800     albertel 3491:         foreach my $priv (keys(%thesepriv)) {
                   3492: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3493: 	}
                   3494:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3495:     }
                   3496:     return ($author,$adv);
                   3497: }
                   3498: 
1.12      www      3499: # --------------------------------------------------------------- get interface
                   3500: 
                   3501: sub get {
1.131     albertel 3502:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3503:    my $items='';
1.800     albertel 3504:    foreach my $item (@$storearr) {
                   3505:        $items.=&escape($item).'&';
1.191     harris41 3506:    }
1.12      www      3507:    $items=~s/\&$//;
1.620     albertel 3508:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3509:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3510:    my $uhome=&homeserver($uname,$udomain);
                   3511: 
1.133     albertel 3512:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3513:    my @pairs=split(/\&/,$rep);
1.273     albertel 3514:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3515:      return @pairs;
                   3516:    }
1.15      www      3517:    my %returnhash=();
1.42      www      3518:    my $i=0;
1.800     albertel 3519:    foreach my $item (@$storearr) {
                   3520:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3521:       $i++;
1.191     harris41 3522:    }
1.15      www      3523:    return %returnhash;
1.27      www      3524: }
                   3525: 
                   3526: # --------------------------------------------------------------- del interface
                   3527: 
                   3528: sub del {
1.133     albertel 3529:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3530:    my $items='';
1.800     albertel 3531:    foreach my $item (@$storearr) {
                   3532:        $items.=&escape($item).'&';
1.191     harris41 3533:    }
1.27      www      3534:    $items=~s/\&$//;
1.620     albertel 3535:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3536:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3537:    my $uhome=&homeserver($uname,$udomain);
                   3538: 
                   3539:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3540: }
                   3541: 
                   3542: # -------------------------------------------------------------- dump interface
                   3543: 
                   3544: sub dump {
1.755     albertel 3545:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3546:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3547:     if (!$uname) { $uname=$env{'user.name'}; }
                   3548:     my $uhome=&homeserver($uname,$udomain);
                   3549:     if ($regexp) {
                   3550: 	$regexp=&escape($regexp);
                   3551:     } else {
                   3552: 	$regexp='.';
                   3553:     }
                   3554:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3555:     my @pairs=split(/\&/,$rep);
                   3556:     my %returnhash=();
                   3557:     foreach my $item (@pairs) {
                   3558: 	my ($key,$value)=split(/=/,$item,2);
                   3559: 	$key = &unescape($key);
                   3560: 	next if ($key =~ /^error: 2 /);
                   3561: 	$returnhash{$key}=&thaw_unescape($value);
                   3562:     }
                   3563:     return %returnhash;
1.407     www      3564: }
                   3565: 
1.717     albertel 3566: # --------------------------------------------------------- dumpstore interface
                   3567: 
                   3568: sub dumpstore {
                   3569:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3570:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3571:    if (!$uname) { $uname=$env{'user.name'}; }
                   3572:    my $uhome=&homeserver($uname,$udomain);
                   3573:    if ($regexp) {
                   3574:        $regexp=&escape($regexp);
                   3575:    } else {
                   3576:        $regexp='.';
                   3577:    }
                   3578:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3579:    my @pairs=split(/\&/,$rep);
                   3580:    my %returnhash=();
                   3581:    foreach my $item (@pairs) {
                   3582:        my ($key,$value)=split(/=/,$item,2);
                   3583:        next if ($key =~ /^error: 2 /);
                   3584:        $returnhash{$key}=&thaw_unescape($value);
                   3585:    }
                   3586:    return %returnhash;
1.717     albertel 3587: }
                   3588: 
1.407     www      3589: # -------------------------------------------------------------- keys interface
                   3590: 
                   3591: sub getkeys {
                   3592:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3593:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3594:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3595:    my $uhome=&homeserver($uname,$udomain);
                   3596:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3597:    my @keyarray=();
1.800     albertel 3598:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3599:       next if ($key =~ /^error: 2 /);
1.800     albertel 3600:       push(@keyarray,&unescape($key));
1.407     www      3601:    }
                   3602:    return @keyarray;
1.318     matthew  3603: }
                   3604: 
1.319     matthew  3605: # --------------------------------------------------------------- currentdump
                   3606: sub currentdump {
1.328     matthew  3607:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3608:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3609:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3610:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3611:    my $uhome = &homeserver($sname,$sdom);
                   3612:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3613:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3614:    #
1.318     matthew  3615:    my %returnhash=();
1.319     matthew  3616:    #
                   3617:    if ($rep eq "unknown_cmd") { 
                   3618:        # an old lond will not know currentdump
                   3619:        # Do a dump and make it look like a currentdump
1.822     albertel 3620:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3621:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3622:        my %hash = @tmp;
                   3623:        @tmp=();
1.424     matthew  3624:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3625:    } else {
                   3626:        my @pairs=split(/\&/,$rep);
1.800     albertel 3627:        foreach my $pair (@pairs) {
                   3628:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3629:            my ($symb,$param) = split(/:/,$key);
                   3630:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3631:                                                         &thaw_unescape($value);
1.319     matthew  3632:        }
1.191     harris41 3633:    }
1.12      www      3634:    return %returnhash;
1.424     matthew  3635: }
                   3636: 
                   3637: sub convert_dump_to_currentdump{
                   3638:     my %hash = %{shift()};
                   3639:     my %returnhash;
                   3640:     # Code ripped from lond, essentially.  The only difference
                   3641:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3642:     # we might run in to problems with parameter names =~ /^v\./
                   3643:     while (my ($key,$value) = each(%hash)) {
                   3644:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3645: 	$symb  = &unescape($symb);
                   3646: 	$param = &unescape($param);
1.424     matthew  3647:         next if ($v eq 'version' || $symb eq 'keys');
                   3648:         next if (exists($returnhash{$symb}) &&
                   3649:                  exists($returnhash{$symb}->{$param}) &&
                   3650:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3651:         $returnhash{$symb}->{$param}=$value;
                   3652:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3653:     }
                   3654:     #
                   3655:     # Remove all of the keys in the hashes which keep track of
                   3656:     # the version of the parameter.
                   3657:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3658:         # use a foreach because we are going to delete from the hash.
                   3659:         foreach my $key (keys(%$param_hash)) {
                   3660:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3661:         }
                   3662:     }
                   3663:     return \%returnhash;
1.12      www      3664: }
                   3665: 
1.627     albertel 3666: # ------------------------------------------------------ critical inc interface
                   3667: 
                   3668: sub cinc {
                   3669:     return &inc(@_,'critical');
                   3670: }
                   3671: 
1.449     matthew  3672: # --------------------------------------------------------------- inc interface
                   3673: 
                   3674: sub inc {
1.627     albertel 3675:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3676:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3677:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3678:     my $uhome=&homeserver($uname,$udomain);
                   3679:     my $items='';
                   3680:     if (! ref($store)) {
                   3681:         # got a single value, so use that instead
                   3682:         $items = &escape($store).'=&';
                   3683:     } elsif (ref($store) eq 'SCALAR') {
                   3684:         $items = &escape($$store).'=&';        
                   3685:     } elsif (ref($store) eq 'ARRAY') {
                   3686:         $items = join('=&',map {&escape($_);} @{$store});
                   3687:     } elsif (ref($store) eq 'HASH') {
                   3688:         while (my($key,$value) = each(%{$store})) {
                   3689:             $items.= &escape($key).'='.&escape($value).'&';
                   3690:         }
                   3691:     }
                   3692:     $items=~s/\&$//;
1.627     albertel 3693:     if ($critical) {
                   3694: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3695:     } else {
                   3696: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3697:     }
1.449     matthew  3698: }
                   3699: 
1.12      www      3700: # --------------------------------------------------------------- put interface
                   3701: 
                   3702: sub put {
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.12      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.12      www      3711:    $items=~s/\&$//;
1.134     albertel 3712:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3713: }
                   3714: 
1.631     albertel 3715: # ------------------------------------------------------------ newput interface
                   3716: 
                   3717: sub newput {
                   3718:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3719:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3720:    if (!$uname) { $uname=$env{'user.name'}; }
                   3721:    my $uhome=&homeserver($uname,$udomain);
                   3722:    my $items='';
                   3723:    foreach my $key (keys(%$storehash)) {
                   3724:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3725:    }
                   3726:    $items=~s/\&$//;
                   3727:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3728: }
                   3729: 
                   3730: # ---------------------------------------------------------  putstore interface
                   3731: 
1.524     raeburn  3732: sub putstore {
1.715     albertel 3733:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3734:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3735:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3736:    my $uhome=&homeserver($uname,$udomain);
                   3737:    my $items='';
1.715     albertel 3738:    foreach my $key (keys(%$storehash)) {
                   3739:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3740:    }
1.715     albertel 3741:    $items=~s/\&$//;
1.716     albertel 3742:    my $esc_symb=&escape($symb);
                   3743:    my $esc_v=&escape($version);
1.715     albertel 3744:    my $reply =
1.716     albertel 3745:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3746: 	      $uhome);
                   3747:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3748:        # gfall back to way things use to be done
1.715     albertel 3749:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3750: 			    $uname);
1.524     raeburn  3751:    }
1.715     albertel 3752:    return $reply;
                   3753: }
                   3754: 
                   3755: sub old_putstore {
1.716     albertel 3756:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3757:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3758:     if (!$uname) { $uname=$env{'user.name'}; }
                   3759:     my $uhome=&homeserver($uname,$udomain);
                   3760:     my %newstorehash;
1.800     albertel 3761:     foreach my $item (keys(%$storehash)) {
                   3762: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3763: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3764:     }
                   3765:     my $items='';
                   3766:     my %allitems = ();
1.800     albertel 3767:     foreach my $item (keys(%newstorehash)) {
                   3768: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3769: 	    my $key = $1.':keys:'.$2;
                   3770: 	    $allitems{$key} .= $3.':';
                   3771: 	}
1.800     albertel 3772: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3773:     }
1.800     albertel 3774:     foreach my $item (keys(%allitems)) {
                   3775: 	$allitems{$item} =~ s/\:$//;
                   3776: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3777:     }
                   3778:     $items=~s/\&$//;
                   3779:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3780: }
                   3781: 
1.47      www      3782: # ------------------------------------------------------ critical put interface
                   3783: 
                   3784: sub cput {
1.134     albertel 3785:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3786:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3787:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3788:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3789:    my $items='';
1.800     albertel 3790:    foreach my $item (keys(%$storehash)) {
                   3791:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3792:    }
1.47      www      3793:    $items=~s/\&$//;
1.134     albertel 3794:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3795: }
                   3796: 
                   3797: # -------------------------------------------------------------- eget interface
                   3798: 
                   3799: sub eget {
1.133     albertel 3800:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3801:    my $items='';
1.800     albertel 3802:    foreach my $item (@$storearr) {
                   3803:        $items.=&escape($item).'&';
1.191     harris41 3804:    }
1.12      www      3805:    $items=~s/\&$//;
1.620     albertel 3806:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3807:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3808:    my $uhome=&homeserver($uname,$udomain);
                   3809:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3810:    my @pairs=split(/\&/,$rep);
                   3811:    my %returnhash=();
1.42      www      3812:    my $i=0;
1.800     albertel 3813:    foreach my $item (@$storearr) {
                   3814:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3815:       $i++;
1.191     harris41 3816:    }
1.12      www      3817:    return %returnhash;
                   3818: }
                   3819: 
1.667     albertel 3820: # ------------------------------------------------------------ tmpput interface
                   3821: sub tmpput {
1.802     raeburn  3822:     my ($storehash,$server,$context)=@_;
1.667     albertel 3823:     my $items='';
1.800     albertel 3824:     foreach my $item (keys(%$storehash)) {
                   3825: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3826:     }
                   3827:     $items=~s/\&$//;
1.802     raeburn  3828:     if (defined($context)) {
                   3829:         $items .= ':'.&escape($context);
                   3830:     }
1.667     albertel 3831:     return &reply("tmpput:$items",$server);
                   3832: }
                   3833: 
                   3834: # ------------------------------------------------------------ tmpget interface
                   3835: sub tmpget {
1.688     albertel 3836:     my ($token,$server)=@_;
                   3837:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3838:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3839:     my %returnhash;
                   3840:     foreach my $item (split(/\&/,$rep)) {
                   3841: 	my ($key,$value)=split(/=/,$item);
                   3842: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3843:     }
                   3844:     return %returnhash;
                   3845: }
                   3846: 
1.688     albertel 3847: # ------------------------------------------------------------ tmpget interface
                   3848: sub tmpdel {
                   3849:     my ($token,$server)=@_;
                   3850:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3851:     return &reply("tmpdel:$token",$server);
                   3852: }
                   3853: 
1.765     albertel 3854: # -------------------------------------------------- portfolio access checking
                   3855: 
                   3856: sub portfolio_access {
1.766     albertel 3857:     my ($requrl) = @_;
1.765     albertel 3858:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3859:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3860:     if ($result) {
                   3861:         my %setters;
                   3862:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3863:             my ($startblock,$endblock) =
                   3864:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3865:             if ($startblock && $endblock) {
                   3866:                 return 'B';
                   3867:             }
                   3868:         } else {
                   3869:             my ($startblock,$endblock) =
                   3870:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3871:             if ($startblock && $endblock) {
                   3872:                 return 'B';
                   3873:             }
                   3874:         }
                   3875:     }
1.765     albertel 3876:     if ($result eq 'ok') {
1.766     albertel 3877:        return 'F';
1.765     albertel 3878:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3879:        return 'A';
1.765     albertel 3880:     }
1.766     albertel 3881:     return '';
1.765     albertel 3882: }
                   3883: 
                   3884: sub get_portfolio_access {
1.767     albertel 3885:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3886: 
                   3887:     if (!ref($access_hash)) {
                   3888: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3889: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3890: 						   $file_name);
                   3891: 	$access_hash = $access_controls{$file_name};
                   3892:     }
                   3893: 
1.765     albertel 3894:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3895:     my $now = time;
                   3896:     if (ref($access_hash) eq 'HASH') {
                   3897:         foreach my $key (keys(%{$access_hash})) {
                   3898:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3899:             if ($start > $now) {
                   3900:                 next;
                   3901:             }
                   3902:             if ($end && $end<$now) {
                   3903:                 next;
                   3904:             }
                   3905:             if ($scope eq 'public') {
                   3906:                 $public = $key;
                   3907:                 last;
                   3908:             } elsif ($scope eq 'guest') {
                   3909:                 $guest = $key;
                   3910:             } elsif ($scope eq 'domains') {
                   3911:                 push(@domains,$key);
                   3912:             } elsif ($scope eq 'users') {
                   3913:                 push(@users,$key);
                   3914:             } elsif ($scope eq 'course') {
                   3915:                 push(@courses,$key);
                   3916:             } elsif ($scope eq 'group') {
                   3917:                 push(@groups,$key);
                   3918:             }
                   3919:         }
                   3920:         if ($public) {
                   3921:             return 'ok';
                   3922:         }
                   3923:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3924:             if ($guest) {
                   3925:                 return $guest;
                   3926:             }
                   3927:         } else {
                   3928:             if (@domains > 0) {
                   3929:                 foreach my $domkey (@domains) {
                   3930:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3931:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3932:                             return 'ok';
                   3933:                         }
                   3934:                     }
                   3935:                 }
                   3936:             }
                   3937:             if (@users > 0) {
                   3938:                 foreach my $userkey (@users) {
1.865     raeburn  3939:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3940:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3941:                             if (ref($item) eq 'HASH') {
                   3942:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3943:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3944:                                     return 'ok';
                   3945:                                 }
                   3946:                             }
                   3947:                         }
                   3948:                     } 
1.765     albertel 3949:                 }
                   3950:             }
                   3951:             my %roleshash;
                   3952:             my @courses_and_groups = @courses;
                   3953:             push(@courses_and_groups,@groups); 
                   3954:             if (@courses_and_groups > 0) {
                   3955:                 my (%allgroups,%allroles); 
                   3956:                 my ($start,$end,$role,$sec,$group);
                   3957:                 foreach my $envkey (%env) {
1.811     albertel 3958:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3959:                         my $cid = $2.'_'.$3; 
                   3960:                         if ($1 eq 'gr') {
                   3961:                             $group = $4;
                   3962:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3963:                         } else {
                   3964:                             if ($4 eq '') {
                   3965:                                 $sec = 'none';
                   3966:                             } else {
                   3967:                                 $sec = $4;
                   3968:                             }
                   3969:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3970:                         }
1.811     albertel 3971:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3972:                         my $cid = $2.'_'.$3;
                   3973:                         if ($4 eq '') {
                   3974:                             $sec = 'none';
                   3975:                         } else {
                   3976:                             $sec = $4;
                   3977:                         }
                   3978:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3979:                     }
                   3980:                 }
                   3981:                 if (keys(%allroles) == 0) {
                   3982:                     return;
                   3983:                 }
                   3984:                 foreach my $key (@courses_and_groups) {
                   3985:                     my %content = %{$$access_hash{$key}};
                   3986:                     my $cnum = $content{'number'};
                   3987:                     my $cdom = $content{'domain'};
                   3988:                     my $cid = $cdom.'_'.$cnum;
                   3989:                     if (!exists($allroles{$cid})) {
                   3990:                         next;
                   3991:                     }    
                   3992:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3993:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3994:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3995:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3996:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3997:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3998:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3999:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4000:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4001:                                         if (grep/^all$/,@sections) {
                   4002:                                             return 'ok';
                   4003:                                         } else {
                   4004:                                             if (grep/^$sec$/,@sections) {
                   4005:                                                 return 'ok';
                   4006:                                             }
                   4007:                                         }
                   4008:                                     }
                   4009:                                 }
                   4010:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4011:                                     if (grep/^none$/,@groups) {
                   4012:                                         return 'ok';
                   4013:                                     }
                   4014:                                 } else {
                   4015:                                     if (grep/^all$/,@groups) {
                   4016:                                         return 'ok';
                   4017:                                     } 
                   4018:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4019:                                         if (grep/^$group$/,@groups) {
                   4020:                                             return 'ok';
                   4021:                                         }
                   4022:                                     }
                   4023:                                 } 
                   4024:                             }
                   4025:                         }
                   4026:                     }
                   4027:                 }
                   4028:             }
                   4029:             if ($guest) {
                   4030:                 return $guest;
                   4031:             }
                   4032:         }
                   4033:     }
                   4034:     return;
                   4035: }
                   4036: 
                   4037: sub course_group_datechecker {
                   4038:     my ($dates,$now,$status) = @_;
                   4039:     my ($start,$end) = split(/\./,$dates);
                   4040:     if (!$start && !$end) {
                   4041:         return 'ok';
                   4042:     }
                   4043:     if (grep/^active$/,@{$status}) {
                   4044:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4045:             return 'ok';
                   4046:         }
                   4047:     }
                   4048:     if (grep/^previous$/,@{$status}) {
                   4049:         if ($end > $now ) {
                   4050:             return 'ok';
                   4051:         }
                   4052:     }
                   4053:     if (grep/^future$/,@{$status}) {
                   4054:         if ($start > $now) {
                   4055:             return 'ok';
                   4056:         }
                   4057:     }
                   4058:     return; 
                   4059: }
                   4060: 
                   4061: sub parse_portfolio_url {
                   4062:     my ($url) = @_;
                   4063: 
                   4064:     my ($type,$udom,$unum,$group,$file_name);
                   4065:     
1.823     albertel 4066:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4067: 	$type = 1;
                   4068:         $udom = $1;
                   4069:         $unum = $2;
                   4070:         $file_name = $3;
1.823     albertel 4071:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4072: 	$type = 2;
                   4073:         $udom = $1;
                   4074:         $unum = $2;
                   4075:         $group = $3;
                   4076:         $file_name = $3.'/'.$4;
                   4077:     }
                   4078:     if (wantarray) {
                   4079: 	return ($type,$udom,$unum,$file_name,$group);
                   4080:     }
                   4081:     return $type;
                   4082: }
                   4083: 
                   4084: sub is_portfolio_url {
                   4085:     my ($url) = @_;
                   4086:     return scalar(&parse_portfolio_url($url));
                   4087: }
                   4088: 
1.798     raeburn  4089: sub is_portfolio_file {
                   4090:     my ($file) = @_;
1.820     raeburn  4091:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4092:         return 1;
                   4093:     }
                   4094:     return;
                   4095: }
                   4096: 
                   4097: 
1.341     www      4098: # ---------------------------------------------- Custom access rule evaluation
                   4099: 
                   4100: sub customaccess {
                   4101:     my ($priv,$uri)=@_;
1.807     albertel 4102:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4103:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4104:     $udom = &LONCAPA::clean_domain($udom);
                   4105:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4106:     my $access=0;
1.800     albertel 4107:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4108: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4109: 	if ($type eq 'user') {
                   4110: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4111: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4112: 		if ($tdom) {
                   4113: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4114: 		}
1.896     albertel 4115: 		if ($tuname) {
                   4116: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4117: 		}
                   4118: 		$access=($effect eq 'allow');
                   4119: 		last;
                   4120: 	    }
                   4121: 	} else {
                   4122: 	    if ($role) {
                   4123: 		if ($role ne $urole) { next; }
                   4124: 	    }
                   4125: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4126: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4127: 		if ($tdom) {
                   4128: 		    if ($tdom ne $udom) { next; }
                   4129: 		}
                   4130: 		if ($tcrs) {
                   4131: 		    if ($tcrs ne $ucrs) { next; }
                   4132: 		}
                   4133: 		if ($tsec) {
                   4134: 		    if ($tsec ne $usec) { next; }
                   4135: 		}
                   4136: 		$access=($effect eq 'allow');
                   4137: 		last;
                   4138: 	    }
                   4139: 	    if ($realm eq '' && $role eq '') {
                   4140: 		$access=($effect eq 'allow');
                   4141: 	    }
1.402     bowersj2 4142: 	}
1.341     www      4143:     }
                   4144:     return $access;
                   4145: }
                   4146: 
1.103     harris41 4147: # ------------------------------------------------- Check for a user privilege
1.12      www      4148: 
                   4149: sub allowed {
1.810     raeburn  4150:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4151:     my $ver_orguri=$uri;
1.439     www      4152:     $uri=&deversion($uri);
1.152     www      4153:     my $orguri=$uri;
1.52      www      4154:     $uri=&declutter($uri);
1.809     raeburn  4155: 
1.810     raeburn  4156:     if ($priv eq 'evb') {
                   4157: # Evade communication block restrictions for specified role in a course
                   4158:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4159:             return $1;
                   4160:         } else {
                   4161:             return;
                   4162:         }
                   4163:     }
                   4164: 
1.620     albertel 4165:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4166: # Free bre access to adm and meta resources
1.775     albertel 4167:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4168: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4169: 	&& ($priv eq 'bre')) {
1.14      www      4170: 	return 'F';
1.159     www      4171:     }
                   4172: 
1.545     banghart 4173: # Free bre access to user's own portfolio contents
1.714     raeburn  4174:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4175:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4176: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4177:         my %setters;
                   4178:         my ($startblock,$endblock) = 
                   4179:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4180:         if ($startblock && $endblock) {
                   4181:             return 'B';
                   4182:         } else {
                   4183:             return 'F';
                   4184:         }
1.545     banghart 4185:     }
                   4186: 
1.762     raeburn  4187: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4188:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4189:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4190:         if (exists($env{'request.course.id'})) {
                   4191:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4192:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4193:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4194:                 my $courseprivid=$env{'request.course.id'};
                   4195:                 $courseprivid=~s/\_/\//;
                   4196:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4197:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4198:                     return $1; 
1.762     raeburn  4199:                 } else {
                   4200:                     if ($env{'request.course.sec'}) {
                   4201:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4202:                     }
                   4203:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4204:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4205:                         return $2;
                   4206:                     }
1.714     raeburn  4207:                 }
                   4208:             }
                   4209:         }
                   4210:     }
                   4211: 
1.159     www      4212: # Free bre to public access
                   4213: 
                   4214:     if ($priv eq 'bre') {
1.238     www      4215:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4216: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4217:            return 'F'; 
                   4218:         }
1.238     www      4219:         if ($copyright eq 'priv') {
                   4220:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4221: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4222: 		return '';
                   4223:             }
                   4224:         }
                   4225:         if ($copyright eq 'domain') {
                   4226:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4227: 	    unless (($env{'user.domain'} eq $1) ||
                   4228:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4229: 		return '';
                   4230:             }
1.262     matthew  4231:         }
1.620     albertel 4232:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4233:             # Library role, so allow browsing of resources in this domain.
                   4234:             return 'F';
1.238     www      4235:         }
1.341     www      4236:         if ($copyright eq 'custom') {
                   4237: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4238:         }
1.14      www      4239:     }
1.264     matthew  4240:     # Domain coordinator is trying to create a course
1.620     albertel 4241:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4242:         # uri is the requested domain in this case.
                   4243:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4244:         # a role of dc for the domain in question.
1.620     albertel 4245:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4246:     }
1.29      www      4247: 
1.52      www      4248:     my $thisallowed='';
                   4249:     my $statecond=0;
                   4250:     my $courseprivid='';
                   4251: 
                   4252: # Course
                   4253: 
1.620     albertel 4254:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4255:        $thisallowed.=$1;
                   4256:     }
1.29      www      4257: 
1.52      www      4258: # Domain
                   4259: 
1.620     albertel 4260:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4261:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4262:        $thisallowed.=$1;
                   4263:     }
1.52      www      4264: 
                   4265: # Course: uri itself is a course
1.66      www      4266:     my $courseuri=$uri;
                   4267:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4268:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4269: 
1.620     albertel 4270:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4271:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4272:        $thisallowed.=$1;
                   4273:     }
1.29      www      4274: 
1.665     albertel 4275: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4276: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4277:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4278: 	$thisallowed='';
1.671     raeburn  4279:         my ($match)=&is_on_map($uri);
                   4280:         if ($match) {
                   4281:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4282:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4283:                 $thisallowed.=$1;
                   4284:             }
                   4285:         } else {
1.705     albertel 4286:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4287:             if ($refuri) {
                   4288:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4289:                     $thisallowed='F';
1.671     raeburn  4290:                 } else {
                   4291:                     $refuri=&declutter($refuri);
                   4292:                     my ($match) = &is_on_map($refuri);
                   4293:                     if ($match) {
                   4294:                         $thisallowed='F';
                   4295:                     }
1.669     raeburn  4296:                 }
1.671     raeburn  4297:             }
                   4298:         }
1.314     www      4299:     }
1.492     albertel 4300: 
1.766     albertel 4301:     if ($priv eq 'bre'
                   4302: 	&& $thisallowed ne 'F' 
                   4303: 	&& $thisallowed ne '2'
                   4304: 	&& &is_portfolio_url($uri)) {
                   4305: 	$thisallowed = &portfolio_access($uri);
                   4306:     }
                   4307:     
1.52      www      4308: # Full access at system, domain or course-wide level? Exit.
1.29      www      4309: 
                   4310:     if ($thisallowed=~/F/) {
                   4311: 	return 'F';
                   4312:     }
                   4313: 
1.52      www      4314: # If this is generating or modifying users, exit with special codes
1.29      www      4315: 
1.643     www      4316:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4317: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4318: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4319: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4320: 	    unless ($auname) { return $thisallowed; }
                   4321: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4322: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4323: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4324: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4325: 	}
1.52      www      4326: 	return $thisallowed;
                   4327:     }
                   4328: #
1.103     harris41 4329: # Gathered so far: system, domain and course wide privileges
1.52      www      4330: #
                   4331: # Course: See if uri or referer is an individual resource that is part of 
                   4332: # the course
                   4333: 
1.620     albertel 4334:     if ($env{'request.course.id'}) {
1.232     www      4335: 
1.620     albertel 4336:        $courseprivid=$env{'request.course.id'};
                   4337:        if ($env{'request.course.sec'}) {
                   4338:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4339:        }
                   4340:        $courseprivid=~s/\_/\//;
                   4341:        my $checkreferer=1;
1.232     www      4342:        my ($match,$cond)=&is_on_map($uri);
                   4343:        if ($match) {
                   4344:            $statecond=$cond;
1.620     albertel 4345:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4346:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4347:                $thisallowed.=$1;
                   4348:                $checkreferer=0;
                   4349:            }
1.29      www      4350:        }
1.83      www      4351:        
1.148     www      4352:        if ($checkreferer) {
1.620     albertel 4353: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4354:             unless ($refuri) {
1.800     albertel 4355:                 foreach my $key (keys(%env)) {
                   4356: 		    if ($key=~/^httpref\..*\*/) {
                   4357: 			my $pattern=$key;
1.156     www      4358:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4359:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4360:                         $pattern=~s/\//\\\//g;
1.152     www      4361:                         if ($orguri=~/$pattern/) {
1.800     albertel 4362: 			    $refuri=$env{$key};
1.148     www      4363:                         }
                   4364:                     }
1.191     harris41 4365:                 }
1.148     www      4366:             }
1.232     www      4367: 
1.148     www      4368:          if ($refuri) { 
1.152     www      4369: 	  $refuri=&declutter($refuri);
1.232     www      4370:           my ($match,$cond)=&is_on_map($refuri);
                   4371:             if ($match) {
                   4372:               my $refstatecond=$cond;
1.620     albertel 4373:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4374:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4375:                   $thisallowed.=$1;
1.53      www      4376:                   $uri=$refuri;
                   4377:                   $statecond=$refstatecond;
1.52      www      4378:               }
                   4379:           }
1.148     www      4380:         }
1.29      www      4381:        }
1.52      www      4382:    }
1.29      www      4383: 
1.52      www      4384: #
1.103     harris41 4385: # Gathered now: all privileges that could apply, and condition number
1.52      www      4386: # 
                   4387: #
                   4388: # Full or no access?
                   4389: #
1.29      www      4390: 
1.52      www      4391:     if ($thisallowed=~/F/) {
                   4392: 	return 'F';
                   4393:     }
1.29      www      4394: 
1.52      www      4395:     unless ($thisallowed) {
                   4396:         return '';
                   4397:     }
1.29      www      4398: 
1.52      www      4399: # Restrictions exist, deal with them
                   4400: #
                   4401: #   C:according to course preferences
                   4402: #   R:according to resource settings
                   4403: #   L:unless locked
                   4404: #   X:according to user session state
                   4405: #
                   4406: 
                   4407: # Possibly locked functionality, check all courses
1.54      www      4408: # Locks might take effect only after 10 minutes cache expiration for other
                   4409: # courses, and 2 minutes for current course
1.52      www      4410: 
                   4411:     my $envkey;
                   4412:     if ($thisallowed=~/L/) {
1.620     albertel 4413:         foreach $envkey (keys %env) {
1.54      www      4414:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4415:                my $courseid=$2;
                   4416:                my $roleid=$1.'.'.$2;
1.92      www      4417:                $courseid=~s/^\///;
1.54      www      4418:                my $expiretime=600;
1.620     albertel 4419:                if ($env{'request.role'} eq $roleid) {
1.54      www      4420: 		  $expiretime=120;
                   4421:                }
                   4422: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4423:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4424:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4425: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4426:                }
1.620     albertel 4427:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4428:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4429: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4430:                        &log($env{'user.domain'},$env{'user.name'},
                   4431:                             $env{'user.home'},
1.57      www      4432:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4433:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4434:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4435: 		       return '';
                   4436:                    }
                   4437:                }
1.620     albertel 4438:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4439:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4440: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4441:                        &log($env{'user.domain'},$env{'user.name'},
                   4442:                             $env{'user.home'},
1.57      www      4443:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4444:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4445:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4446: 		       return '';
                   4447:                    }
                   4448:                }
                   4449: 	   }
1.29      www      4450:        }
1.52      www      4451:     }
                   4452:    
                   4453: #
                   4454: # Rest of the restrictions depend on selected course
                   4455: #
                   4456: 
1.620     albertel 4457:     unless ($env{'request.course.id'}) {
1.766     albertel 4458: 	if ($thisallowed eq 'A') {
                   4459: 	    return 'A';
1.814     raeburn  4460:         } elsif ($thisallowed eq 'B') {
                   4461:             return 'B';
1.766     albertel 4462: 	} else {
                   4463: 	    return '1';
                   4464: 	}
1.52      www      4465:     }
1.29      www      4466: 
1.52      www      4467: #
                   4468: # Now user is definitely in a course
                   4469: #
1.53      www      4470: 
                   4471: 
                   4472: # Course preferences
                   4473: 
                   4474:    if ($thisallowed=~/C/) {
1.620     albertel 4475:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4476:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4477:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4478: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4479: 	   if ($priv ne 'pch') { 
                   4480: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4481: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4482: 			$env{'request.course.id'});
                   4483: 	   }
1.237     www      4484:            return '';
                   4485:        }
                   4486: 
1.620     albertel 4487:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4488: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4489: 	   if ($priv ne 'pch') { 
                   4490: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4491: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4492: 			$env{'request.course.id'});
                   4493: 	   }
1.54      www      4494:            return '';
                   4495:        }
1.53      www      4496:    }
                   4497: 
                   4498: # Resource preferences
                   4499: 
                   4500:    if ($thisallowed=~/R/) {
1.620     albertel 4501:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4502:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4503: 	   if ($priv ne 'pch') { 
                   4504: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4505: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4506: 	   }
                   4507: 	   return '';
1.54      www      4508:        }
1.53      www      4509:    }
1.30      www      4510: 
1.246     www      4511: # Restricted by state or randomout?
1.30      www      4512: 
1.52      www      4513:    if ($thisallowed=~/X/) {
1.620     albertel 4514:       if ($env{'acc.randomout'}) {
1.579     albertel 4515: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4516:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4517:             return ''; 
                   4518:          }
1.247     www      4519:       }
                   4520:       if (&condval($statecond)) {
1.52      www      4521: 	 return '2';
                   4522:       } else {
                   4523:          return '';
                   4524:       }
                   4525:    }
1.30      www      4526: 
1.766     albertel 4527:     if ($thisallowed eq 'A') {
                   4528: 	return 'A';
1.814     raeburn  4529:     } elsif ($thisallowed eq 'B') {
                   4530:         return 'B';
1.766     albertel 4531:     }
1.52      www      4532:    return 'F';
1.232     www      4533: }
                   4534: 
1.710     albertel 4535: sub split_uri_for_cond {
                   4536:     my $uri=&deversion(&declutter(shift));
                   4537:     my @uriparts=split(/\//,$uri);
                   4538:     my $filename=pop(@uriparts);
                   4539:     my $pathname=join('/',@uriparts);
                   4540:     return ($pathname,$filename);
                   4541: }
1.232     www      4542: # --------------------------------------------------- Is a resource on the map?
                   4543: 
                   4544: sub is_on_map {
1.710     albertel 4545:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4546:     #Trying to find the conditional for the file
1.620     albertel 4547:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4548: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4549:     if ($match) {
1.289     bowersj2 4550: 	return (1,$1);
                   4551:     } else {
1.434     www      4552: 	return (0,0);
1.289     bowersj2 4553:     }
1.12      www      4554: }
                   4555: 
1.427     www      4556: # --------------------------------------------------------- Get symb from alias
                   4557: 
                   4558: sub get_symb_from_alias {
                   4559:     my $symb=shift;
                   4560:     my ($map,$resid,$url)=&decode_symb($symb);
                   4561: # Already is a symb
                   4562:     if ($url) { return $symb; }
                   4563: # Must be an alias
                   4564:     my $aliassymb='';
                   4565:     my %bighash;
1.620     albertel 4566:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4567:                             &GDBM_READER(),0640)) {
                   4568:         my $rid=$bighash{'mapalias_'.$symb};
                   4569: 	if ($rid) {
                   4570: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4571: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4572: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4573: 	}
                   4574:         untie %bighash;
                   4575:     }
                   4576:     return $aliassymb;
                   4577: }
                   4578: 
1.12      www      4579: # ----------------------------------------------------------------- Define Role
                   4580: 
                   4581: sub definerole {
                   4582:   if (allowed('mcr','/')) {
                   4583:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4584:     foreach my $role (split(':',$sysrole)) {
                   4585: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4586:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4587:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4588: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4589:                return "refused:s:$crole&$cqual"; 
                   4590:             }
                   4591:         }
1.191     harris41 4592:     }
1.800     albertel 4593:     foreach my $role (split(':',$domrole)) {
                   4594: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4595:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4596:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4597: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4598:                return "refused:d:$crole&$cqual"; 
                   4599:             }
                   4600:         }
1.191     harris41 4601:     }
1.800     albertel 4602:     foreach my $role (split(':',$courole)) {
                   4603: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4604:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4605:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4606: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4607:                return "refused:c:$crole&$cqual"; 
                   4608:             }
                   4609:         }
1.191     harris41 4610:     }
1.620     albertel 4611:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4612:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4613: 	        "rolesdef_$rolename=".
                   4614:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4615:     return reply($command,$env{'user.home'});
1.12      www      4616:   } else {
                   4617:     return 'refused';
                   4618:   }
1.105     harris41 4619: }
                   4620: 
                   4621: # ---------------- Make a metadata query against the network of library servers
                   4622: 
                   4623: sub metadata_query {
1.244     matthew  4624:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4625:     my %rhash;
1.845     albertel 4626:     my %libserv = &all_library();
1.244     matthew  4627:     my @server_list = (defined($server_array) ? @$server_array
                   4628:                                               : keys(%libserv) );
                   4629:     for my $server (@server_list) {
1.118     harris41 4630: 	unless ($custom or $customshow) {
                   4631: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4632: 	    $rhash{$server}=$reply;
                   4633: 	}
                   4634: 	else {
                   4635: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4636: 			     &escape($custom).':'.&escape($customshow),
                   4637: 			     $server);
                   4638: 	    $rhash{$server}=$reply;
                   4639: 	}
1.112     harris41 4640:     }
1.118     harris41 4641:     return \%rhash;
1.240     www      4642: }
                   4643: 
                   4644: # ----------------------------------------- Send log queries and wait for reply
                   4645: 
                   4646: sub log_query {
                   4647:     my ($uname,$udom,$query,%filters)=@_;
                   4648:     my $uhome=&homeserver($uname,$udom);
                   4649:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4650:     my $uhost=&hostname($uhome);
1.800     albertel 4651:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4652:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4653:                        $uhome);
1.479     albertel 4654:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4655:     return get_query_reply($queryid);
                   4656: }
                   4657: 
1.818     raeburn  4658: # -------------------------- Update MySQL table for portfolio file
                   4659: 
                   4660: sub update_portfolio_table {
1.821     raeburn  4661:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4662:     my $homeserver = &homeserver($uname,$udom);
                   4663:     my $queryid=
1.821     raeburn  4664:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4665:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4666:     my $reply = &get_query_reply($queryid);
                   4667:     return $reply;
                   4668: }
                   4669: 
1.899     raeburn  4670: # -------------------------- Update MySQL allusers table
                   4671: 
                   4672: sub update_allusers_table {
                   4673:     my ($uname,$udom,$names) = @_;
                   4674:     my $homeserver = &homeserver($uname,$udom);
                   4675:     my $queryid=
                   4676:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4677:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4678:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4679:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4680:                'generation='.&escape($names->{'generation'}).'%%'.
                   4681:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4682:                'id='.&escape($names->{'id'}),$homeserver);
                   4683:     my $reply = &get_query_reply($queryid);
                   4684:     return $reply;
                   4685: }
                   4686: 
1.508     raeburn  4687: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4688: 
                   4689: sub fetch_enrollment_query {
1.511     raeburn  4690:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4691:     my $homeserver;
1.547     raeburn  4692:     my $maxtries = 1;
1.508     raeburn  4693:     if ($context eq 'automated') {
                   4694:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4695:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4696:     } else {
                   4697:         $homeserver = &homeserver($cnum,$dom);
                   4698:     }
1.838     albertel 4699:     my $host=&hostname($homeserver);
1.506     raeburn  4700:     my $cmd = '';
1.800     albertel 4701:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4702:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4703:     }
                   4704:     $cmd =~ s/%%$//;
                   4705:     $cmd = &escape($cmd);
                   4706:     my $query = 'fetchenrollment';
1.620     albertel 4707:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4708:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4709:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4710:         return 'error: '.$queryid;
                   4711:     }
1.506     raeburn  4712:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4713:     my $tries = 1;
                   4714:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4715:         $reply = &get_query_reply($queryid);
                   4716:         $tries ++;
                   4717:     }
1.526     raeburn  4718:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4719:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4720:     } else {
1.901     albertel 4721:         my @responses = split(/:/,$reply);
1.515     raeburn  4722:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4723:             foreach my $line (@responses) {
                   4724:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4725:                 $$replyref{$key} = $value;
                   4726:             }
                   4727:         } else {
1.506     raeburn  4728:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4729:             foreach my $line (@responses) {
                   4730:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4731:                 $$replyref{$key} = $value;
                   4732:                 if ($value > 0) {
1.800     albertel 4733:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4734:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4735:                         my $destname = $pathname.'/'.$filename;
                   4736:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4737:                         if ($xml_classlist =~ /^error/) {
                   4738:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4739:                         } else {
1.506     raeburn  4740:                             if ( open(FILE,">$destname") ) {
                   4741:                                 print FILE &unescape($xml_classlist);
                   4742:                                 close(FILE);
1.526     raeburn  4743:                             } else {
                   4744:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4745:                             }
                   4746:                         }
                   4747:                     }
                   4748:                 }
                   4749:             }
                   4750:         }
                   4751:         return 'ok';
                   4752:     }
                   4753:     return 'error';
                   4754: }
                   4755: 
1.242     www      4756: sub get_query_reply {
                   4757:     my $queryid=shift;
1.240     www      4758:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4759:     my $reply='';
                   4760:     for (1..100) {
                   4761: 	sleep 2;
                   4762:         if (-e $replyfile.'.end') {
1.448     albertel 4763: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4764: 		$reply = join('',<$fh>);
                   4765: 		close($fh);
1.240     www      4766: 	   } else { return 'error: reply_file_error'; }
1.242     www      4767:            return &unescape($reply);
                   4768: 	}
1.240     www      4769:     }
1.242     www      4770:     return 'timeout:'.$queryid;
1.240     www      4771: }
                   4772: 
                   4773: sub courselog_query {
1.241     www      4774: #
                   4775: # possible filters:
                   4776: # url: url or symb
                   4777: # username
                   4778: # domain
                   4779: # action: view, submit, grade
                   4780: # start: timestamp
                   4781: # end: timestamp
                   4782: #
1.240     www      4783:     my (%filters)=@_;
1.620     albertel 4784:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4785:     if ($filters{'url'}) {
                   4786: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4787:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4788:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4789:     }
1.620     albertel 4790:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4791:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4792:     return &log_query($cname,$cdom,'courselog',%filters);
                   4793: }
                   4794: 
                   4795: sub userlog_query {
1.858     raeburn  4796: #
                   4797: # possible filters:
                   4798: # action: log check role
                   4799: # start: timestamp
                   4800: # end: timestamp
                   4801: #
1.240     www      4802:     my ($uname,$udom,%filters)=@_;
                   4803:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4804: }
                   4805: 
1.506     raeburn  4806: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4807: 
                   4808: sub auto_run {
1.508     raeburn  4809:     my ($cnum,$cdom) = @_;
1.876     raeburn  4810:     my $response = 0;
                   4811:     my $settings;
                   4812:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4813:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4814:         $settings = $domconfig{'autoenroll'};
                   4815:         if ($settings->{'run'} eq '1') {
                   4816:             $response = 1;
                   4817:         }
                   4818:     } else {
                   4819:         my $homeserver = &homeserver($cnum,$cdom);
                   4820:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4821:     }
1.506     raeburn  4822:     return $response;
                   4823: }
1.776     albertel 4824: 
1.506     raeburn  4825: sub auto_get_sections {
1.508     raeburn  4826:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4827:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4828:     my @secs = ();
1.511     raeburn  4829:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4830:     unless ($response eq 'refused') {
1.901     albertel 4831:         @secs = split(/:/,$response);
1.506     raeburn  4832:     }
                   4833:     return @secs;
                   4834: }
1.776     albertel 4835: 
1.506     raeburn  4836: sub auto_new_course {
1.508     raeburn  4837:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4838:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4839:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4840:     return $response;
                   4841: }
1.776     albertel 4842: 
1.506     raeburn  4843: sub auto_validate_courseID {
1.508     raeburn  4844:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4845:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4846:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4847:     return $response;
                   4848: }
1.776     albertel 4849: 
1.506     raeburn  4850: sub auto_create_password {
1.873     raeburn  4851:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4852:     my ($homeserver,$response);
1.506     raeburn  4853:     my $create_passwd = 0;
                   4854:     my $authchk = '';
1.873     raeburn  4855:     if ($udom =~ /^$match_domain$/) {
                   4856:         $homeserver = &domain($udom,'primary');
                   4857:     }
                   4858:     if ($homeserver eq '') {
                   4859:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4860:             $homeserver = &homeserver($cnum,$cdom);
                   4861:         }
                   4862:     }
                   4863:     if ($homeserver eq '') {
                   4864:         $authchk = 'nodomain';
1.506     raeburn  4865:     } else {
1.873     raeburn  4866:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4867:         if ($response eq 'refused') {
                   4868:             $authchk = 'refused';
                   4869:         } else {
1.901     albertel 4870:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4871:         }
1.506     raeburn  4872:     }
                   4873:     return ($authparam,$create_passwd,$authchk);
                   4874: }
                   4875: 
1.706     raeburn  4876: sub auto_photo_permission {
                   4877:     my ($cnum,$cdom,$students) = @_;
                   4878:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4879:     my ($outcome,$perm_reqd,$conditions) = 
                   4880: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4881:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4882: 	return (undef,undef);
                   4883:     }
1.706     raeburn  4884:     return ($outcome,$perm_reqd,$conditions);
                   4885: }
                   4886: 
                   4887: sub auto_checkphotos {
                   4888:     my ($uname,$udom,$pid) = @_;
                   4889:     my $homeserver = &homeserver($uname,$udom);
                   4890:     my ($result,$resulttype);
                   4891:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4892: 				   &escape($uname).':'.&escape($pid),
                   4893: 				   $homeserver));
1.709     albertel 4894:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4895: 	return (undef,undef);
                   4896:     }
1.706     raeburn  4897:     if ($outcome) {
                   4898:         ($result,$resulttype) = split(/:/,$outcome);
                   4899:     } 
                   4900:     return ($result,$resulttype);
                   4901: }
                   4902: 
                   4903: sub auto_photochoice {
                   4904:     my ($cnum,$cdom) = @_;
                   4905:     my $homeserver = &homeserver($cnum,$cdom);
                   4906:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4907: 						       &escape($cdom),
                   4908: 						       $homeserver)));
1.709     albertel 4909:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4910: 	return (undef,undef);
                   4911:     }
1.706     raeburn  4912:     return ($update,$comment);
                   4913: }
                   4914: 
                   4915: sub auto_photoupdate {
                   4916:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4917:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4918:     my $host=&hostname($homeserver);
1.706     raeburn  4919:     my $cmd = '';
                   4920:     my $maxtries = 1;
1.800     albertel 4921:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4922:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4923:     }
                   4924:     $cmd =~ s/%%$//;
                   4925:     $cmd = &escape($cmd);
                   4926:     my $query = 'institutionalphotos';
                   4927:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4928:     unless ($queryid=~/^\Q$host\E\_/) {
                   4929:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4930:         return 'error: '.$queryid;
                   4931:     }
                   4932:     my $reply = &get_query_reply($queryid);
                   4933:     my $tries = 1;
                   4934:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4935:         $reply = &get_query_reply($queryid);
                   4936:         $tries ++;
                   4937:     }
                   4938:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4939:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4940:     } else {
                   4941:         my @responses = split(/:/,$reply);
                   4942:         my $outcome = shift(@responses); 
                   4943:         foreach my $item (@responses) {
                   4944:             my ($key,$value) = split(/=/,$item);
                   4945:             $$photo{$key} = $value;
                   4946:         }
                   4947:         return $outcome;
                   4948:     }
                   4949:     return 'error';
                   4950: }
                   4951: 
1.521     raeburn  4952: sub auto_instcode_format {
1.793     albertel 4953:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4954: 	$cat_order) = @_;
1.521     raeburn  4955:     my $courses = '';
1.772     raeburn  4956:     my @homeservers;
1.521     raeburn  4957:     if ($caller eq 'global') {
1.841     albertel 4958: 	my %servers = &get_servers($codedom,'library');
                   4959: 	foreach my $tryserver (keys(%servers)) {
                   4960: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4961: 		push(@homeservers,$tryserver);
                   4962: 	    }
1.584     raeburn  4963:         }
1.521     raeburn  4964:     } else {
1.772     raeburn  4965:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4966:     }
1.793     albertel 4967:     foreach my $code (keys(%{$instcodes})) {
                   4968:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4969:     }
                   4970:     chop($courses);
1.772     raeburn  4971:     my $ok_response = 0;
                   4972:     my $response;
                   4973:     while (@homeservers > 0 && $ok_response == 0) {
                   4974:         my $server = shift(@homeservers); 
                   4975:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4976:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4977:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4978: 		split(/:/,$response);
1.772     raeburn  4979:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4980:             push(@{$codetitles},&str2array($codetitles_str));
                   4981:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4982:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4983:             $ok_response = 1;
                   4984:         }
                   4985:     }
                   4986:     if ($ok_response) {
1.521     raeburn  4987:         return 'ok';
1.772     raeburn  4988:     } else {
                   4989:         return $response;
1.521     raeburn  4990:     }
                   4991: }
                   4992: 
1.792     raeburn  4993: sub auto_instcode_defaults {
                   4994:     my ($domain,$returnhash,$code_order) = @_;
                   4995:     my @homeservers;
1.841     albertel 4996: 
                   4997:     my %servers = &get_servers($domain,'library');
                   4998:     foreach my $tryserver (keys(%servers)) {
                   4999: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5000: 	    push(@homeservers,$tryserver);
                   5001: 	}
1.792     raeburn  5002:     }
1.841     albertel 5003: 
1.792     raeburn  5004:     my $response;
1.841     albertel 5005:     foreach my $server (@homeservers) {
1.792     raeburn  5006:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5007:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5008: 	
                   5009: 	foreach my $pair (split(/\&/,$response)) {
                   5010: 	    my ($name,$value)=split(/\=/,$pair);
                   5011: 	    if ($name eq 'code_order') {
                   5012: 		@{$code_order} = split(/\&/,&unescape($value));
                   5013: 	    } else {
                   5014: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5015: 	    }
                   5016: 	}
                   5017: 	return 'ok';
1.792     raeburn  5018:     }
1.841     albertel 5019: 
                   5020:     return $response;
1.792     raeburn  5021: } 
                   5022: 
1.777     albertel 5023: sub auto_validate_class_sec {
1.918     raeburn  5024:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5025:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5026:     my $ownerlist;
                   5027:     if (ref($owners) eq 'ARRAY') {
                   5028:         $ownerlist = join(',',@{$owners});
                   5029:     } else {
                   5030:         $ownerlist = $owners;
                   5031:     }
1.773     raeburn  5032:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5033:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5034:     return $response;
                   5035: }
                   5036: 
1.679     raeburn  5037: # ------------------------------------------------------- Course Group routines
                   5038: 
                   5039: sub get_coursegroups {
1.809     raeburn  5040:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5041:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5042: }
                   5043: 
1.679     raeburn  5044: sub modify_coursegroup {
                   5045:     my ($cdom,$cnum,$groupsettings) = @_;
                   5046:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5047: }
                   5048: 
1.809     raeburn  5049: sub toggle_coursegroup_status {
                   5050:     my ($cdom,$cnum,$group,$action) = @_;
                   5051:     my ($from_namespace,$to_namespace);
                   5052:     if ($action eq 'delete') {
                   5053:         $from_namespace = 'coursegroups';
                   5054:         $to_namespace = 'deleted_groups';
                   5055:     } else {
                   5056:         $from_namespace = 'deleted_groups';
                   5057:         $to_namespace = 'coursegroups';
                   5058:     }
                   5059:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5060:     if (my $tmp = &error(%curr_group)) {
                   5061:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5062:         return ('read error',$tmp);
                   5063:     } else {
                   5064:         my %savedsettings = %curr_group; 
1.809     raeburn  5065:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5066:         my $deloutcome;
                   5067:         if ($result eq 'ok') {
1.809     raeburn  5068:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5069:         } else {
                   5070:             return ('write error',$result);
                   5071:         }
                   5072:         if ($deloutcome eq 'ok') {
                   5073:             return 'ok';
                   5074:         } else {
                   5075:             return ('delete error',$deloutcome);
                   5076:         }
                   5077:     }
                   5078: }
                   5079: 
1.679     raeburn  5080: sub modify_group_roles {
                   5081:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5082:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5083:     my $role = 'gr/'.&escape($userprivs);
                   5084:     my ($uname,$udom) = split(/:/,$user);
                   5085:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5086:     if ($result eq 'ok') {
                   5087:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5088:     }
1.679     raeburn  5089:     return $result;
                   5090: }
                   5091: 
                   5092: sub modify_coursegroup_membership {
                   5093:     my ($cdom,$cnum,$membership) = @_;
                   5094:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5095:     return $result;
                   5096: }
                   5097: 
1.682     raeburn  5098: sub get_active_groups {
                   5099:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5100:     my $now = time;
                   5101:     my %groups = ();
                   5102:     foreach my $key (keys(%env)) {
1.811     albertel 5103:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5104:             my ($start,$end) = split(/\./,$env{$key});
                   5105:             if (($end!=0) && ($end<$now)) { next; }
                   5106:             if (($start!=0) && ($start>$now)) { next; }
                   5107:             if ($1 eq $cdom && $2 eq $cnum) {
                   5108:                 $groups{$3} = $env{$key} ;
                   5109:             }
                   5110:         }
                   5111:     }
                   5112:     return %groups;
                   5113: }
                   5114: 
1.683     raeburn  5115: sub get_group_membership {
                   5116:     my ($cdom,$cnum,$group) = @_;
                   5117:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5118: }
                   5119: 
                   5120: sub get_users_groups {
                   5121:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5122:     my @usersgroups;
1.683     raeburn  5123:     my $cachetime=1800;
                   5124: 
                   5125:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5126:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5127:     if (defined($cached)) {
1.734     albertel 5128:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5129:     } else {  
                   5130:         $grouplist = '';
1.816     raeburn  5131:         my $courseurl = &courseid_to_courseurl($courseid);
                   5132:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5133:         my $access_end = $env{'course.'.$courseid.
                   5134:                               '.default_enrollment_end_date'};
                   5135:         my $now = time;
                   5136:         foreach my $key (keys(%roleshash)) {
                   5137:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5138:                 my $group = $1;
                   5139:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5140:                     my $start = $2;
                   5141:                     my $end = $1;
                   5142:                     if ($start == -1) { next; } # deleted from group
                   5143:                     if (($start!=0) && ($start>$now)) { next; }
                   5144:                     if (($end!=0) && ($end<$now)) {
                   5145:                         if ($access_end && $access_end < $now) {
                   5146:                             if ($access_end - $end < 86400) {
                   5147:                                 push(@usersgroups,$group);
1.733     raeburn  5148:                             }
                   5149:                         }
1.817     raeburn  5150:                         next;
1.733     raeburn  5151:                     }
1.817     raeburn  5152:                     push(@usersgroups,$group);
1.683     raeburn  5153:                 }
                   5154:             }
                   5155:         }
1.817     raeburn  5156:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5157:         $grouplist = join(':',@usersgroups);
                   5158:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5159:     }
1.733     raeburn  5160:     return @usersgroups;
1.683     raeburn  5161: }
                   5162: 
                   5163: sub devalidate_getgroups_cache {
                   5164:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5165:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5166: 
1.683     raeburn  5167:     my $hashid="$udom:$uname:$courseid";
                   5168:     &devalidate_cache_new('getgroups',$hashid);
                   5169: }
                   5170: 
1.12      www      5171: # ------------------------------------------------------------------ Plain Text
                   5172: 
                   5173: sub plaintext {
1.742     raeburn  5174:     my ($short,$type,$cid) = @_;
1.758     albertel 5175:     if ($short =~ /^cr/) {
                   5176: 	return (split('/',$short))[-1];
                   5177:     }
1.742     raeburn  5178:     if (!defined($cid)) {
                   5179:         $cid = $env{'request.course.id'};
                   5180:     }
                   5181:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5182:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5183:                                           '.plaintext'});
                   5184:     }
                   5185:     my %rolenames = (
                   5186:                       Course => 'std',
                   5187:                       Group => 'alt1',
                   5188:                     );
                   5189:     if (defined($type) && 
                   5190:          defined($rolenames{$type}) && 
                   5191:          defined($prp{$short}{$rolenames{$type}})) {
                   5192:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5193:     } else {
                   5194:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5195:     }
1.12      www      5196: }
                   5197: 
                   5198: # ----------------------------------------------------------------- Assign Role
                   5199: 
                   5200: sub assignrole {
1.357     www      5201:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5202:     my $mrole;
                   5203:     if ($role =~ /^cr\//) {
1.393     www      5204:         my $cwosec=$url;
1.811     albertel 5205:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5206: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5207:            &logthis('Refused custom assignrole: '.
                   5208:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5209: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5210:            return 'refused'; 
                   5211:         }
1.21      www      5212:         $mrole='cr';
1.678     raeburn  5213:     } elsif ($role =~ /^gr\//) {
                   5214:         my $cwogrp=$url;
1.811     albertel 5215:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5216:         unless (&allowed('mdg',$cwogrp)) {
                   5217:             &logthis('Refused group assignrole: '.
                   5218:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5219:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5220:             return 'refused';
                   5221:         }
                   5222:         $mrole='gr';
1.21      www      5223:     } else {
1.82      www      5224:         my $cwosec=$url;
1.811     albertel 5225:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5226:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5227:            &logthis('Refused assignrole: '.
                   5228:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5229: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5230:            return 'refused'; 
                   5231:         }
1.21      www      5232:         $mrole=$role;
                   5233:     }
1.620     albertel 5234:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5235:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5236:     if ($end) { $command.='_'.$end; }
1.21      www      5237:     if ($start) {
                   5238: 	if ($end) { 
1.81      www      5239:            $command.='_'.$start; 
1.21      www      5240:         } else {
1.81      www      5241:            $command.='_0_'.$start;
1.21      www      5242:         }
                   5243:     }
1.739     raeburn  5244:     my $origstart = $start;
                   5245:     my $origend = $end;
1.357     www      5246: # actually delete
                   5247:     if ($deleteflag) {
1.373     www      5248: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5249: # modify command to delete the role
1.620     albertel 5250:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5251:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5252: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5253: # set start and finish to negative values for userrolelog
                   5254:            $start=-1;
                   5255:            $end=-1;
                   5256:         }
                   5257:     }
                   5258: # send command
1.349     www      5259:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5260: # log new user role if status is ok
1.349     www      5261:     if ($answer eq 'ok') {
1.663     raeburn  5262: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5263: # for course roles, perform group memberships changes triggered by role change.
                   5264:         unless ($role =~ /^gr/) {
                   5265:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5266:                                              $origstart);
                   5267:         }
1.349     www      5268:     }
                   5269:     return $answer;
1.169     harris41 5270: }
                   5271: 
                   5272: # -------------------------------------------------- Modify user authentication
1.197     www      5273: # Overrides without validation
                   5274: 
1.169     harris41 5275: sub modifyuserauth {
                   5276:     my ($udom,$uname,$umode,$upass)=@_;
                   5277:     my $uhome=&homeserver($uname,$udom);
1.197     www      5278:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5279:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5280:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5281:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5282:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5283: 		     &escape($upass),$uhome);
1.620     albertel 5284:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5285:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5286:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5287:     &log($udom,,$uname,$uhome,
1.620     albertel 5288:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5289:                                      $env{'user.name'}.', '.$umode.
1.197     www      5290:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5291:     unless ($reply eq 'ok') {
1.197     www      5292:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5293: 	return 'error: '.$reply;
                   5294:     }   
1.170     harris41 5295:     return 'ok';
1.80      www      5296: }
                   5297: 
1.81      www      5298: # --------------------------------------------------------------- Modify a user
1.80      www      5299: 
1.81      www      5300: sub modifyuser {
1.206     matthew  5301:     my ($udom,    $uname, $uid,
                   5302:         $umode,   $upass, $first,
                   5303:         $middle,  $last,  $gene,
1.387     www      5304:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5305:     $udom= &LONCAPA::clean_domain($udom);
                   5306:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5307:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5308:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5309: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5310:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5311:                                      ' desiredhome not specified'). 
1.620     albertel 5312:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5313:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5314:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5315: # ----------------------------------------------------------------- Create User
1.406     albertel 5316:     if (($uhome eq 'no_host') && 
                   5317: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5318:         my $unhome='';
1.844     albertel 5319:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5320:             $unhome = $desiredhome;
1.620     albertel 5321: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5322: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5323:         } else { # load balancing routine for determining $unhome
1.81      www      5324:             my $loadm=10000000;
1.841     albertel 5325: 	    my %servers = &get_servers($udom,'library');
                   5326: 	    foreach my $tryserver (keys(%servers)) {
                   5327: 		my $answer=reply('load',$tryserver);
                   5328: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5329: 		    $loadm=$answer;
                   5330: 		    $unhome=$tryserver;
                   5331: 		}
1.80      www      5332: 	    }
                   5333:         }
                   5334:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5335: 	    return 'error: unable to find a home server for '.$uname.
                   5336:                    ' in domain '.$udom;
1.80      www      5337:         }
                   5338:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5339:                          &escape($upass),$unhome);
                   5340: 	unless ($reply eq 'ok') {
                   5341:             return 'error: '.$reply;
                   5342:         }   
1.230     stredwic 5343:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5344:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5345: 	    return 'error: unable verify users home machine.';
1.80      www      5346:         }
1.209     matthew  5347:     }   # End of creation of new user
1.80      www      5348: # ---------------------------------------------------------------------- Add ID
                   5349:     if ($uid) {
                   5350:        $uid=~tr/A-Z/a-z/;
                   5351:        my %uidhash=&idrget($udom,$uname);
1.196     www      5352:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5353:          && (!$forceid)) {
1.80      www      5354: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5355: 	      return 'error: user id "'.$uid.'" does not match '.
                   5356:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5357:           }
                   5358:        } else {
                   5359: 	  &idput($udom,($uname => $uid));
                   5360:        }
                   5361:     }
                   5362: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5363:     my @tmp=&get('environment',
1.899     raeburn  5364: 		   ['firstname','middlename','lastname','generation','id',
                   5365:                     'permanentemail'],
1.134     albertel 5366: 		   $udom,$uname);
1.313     matthew  5367:     my %names;
                   5368:     if ($tmp[0] =~ m/^error:.*/) { 
                   5369:         %names=(); 
                   5370:     } else {
                   5371:         %names = @tmp;
                   5372:     }
1.388     www      5373: #
                   5374: # Make sure to not trash student environment if instructor does not bother
                   5375: # to supply name and email information
                   5376: #
                   5377:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5378:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5379:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5380:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5381:     if ($email) {
                   5382:        $email=~s/[^\w\@\.\-\,]//gs;
                   5383:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5384: 			   $names{'critnotification'} = $email;
                   5385: 			   $names{'permanentemail'} = $email; }
                   5386:     }
1.899     raeburn  5387:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5388:     my $reply = &put('environment', \%names, $udom,$uname);
                   5389:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5390:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5391:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5392:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5393:              $umode.', '.$first.', '.$middle.', '.
                   5394: 	     $last.', '.$gene.' by '.
1.620     albertel 5395:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5396:     return 'ok';
1.80      www      5397: }
                   5398: 
1.81      www      5399: # -------------------------------------------------------------- Modify student
1.80      www      5400: 
1.81      www      5401: sub modifystudent {
                   5402:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5403:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5404:     if (!$cid) {
1.620     albertel 5405: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5406: 	    return 'not_in_class';
                   5407: 	}
1.80      www      5408:     }
                   5409: # --------------------------------------------------------------- Make the user
1.81      www      5410:     my $reply=&modifyuser
1.209     matthew  5411: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5412:          $desiredhome,$email);
1.80      www      5413:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5414:     # This will cause &modify_student_enrollment to get the uid from the
                   5415:     # students environment
                   5416:     $uid = undef if (!$forceid);
1.455     albertel 5417:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5418: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5419:     return $reply;
                   5420: }
                   5421: 
                   5422: sub modify_student_enrollment {
1.515     raeburn  5423:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5424:     my ($cdom,$cnum,$chome);
                   5425:     if (!$cid) {
1.620     albertel 5426: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5427: 	    return 'not_in_class';
                   5428: 	}
1.620     albertel 5429: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5430: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5431:     } else {
                   5432: 	($cdom,$cnum)=split(/_/,$cid);
                   5433:     }
1.620     albertel 5434:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5435:     if (!$chome) {
1.457     raeburn  5436: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5437:     }
1.455     albertel 5438:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5439:     # Make sure the user exists
1.81      www      5440:     my $uhome=&homeserver($uname,$udom);
                   5441:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5442: 	return 'error: no such user';
                   5443:     }
1.297     matthew  5444:     # Get student data if we were not given enough information
                   5445:     if (!defined($first)  || $first  eq '' || 
                   5446:         !defined($last)   || $last   eq '' || 
                   5447:         !defined($uid)    || $uid    eq '' || 
                   5448:         !defined($middle) || $middle eq '' || 
                   5449:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5450:         # They did not supply us with enough data to enroll the student, so
                   5451:         # we need to pick up more information.
1.297     matthew  5452:         my %tmp = &get('environment',
1.294     matthew  5453:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5454:                        ,$udom,$uname);
                   5455: 
1.800     albertel 5456:         #foreach my $key (keys(%tmp)) {
                   5457:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5458:         #}
1.294     matthew  5459:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5460:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5461:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5462:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5463:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5464:     }
1.556     albertel 5465:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5466:     my $reply=cput('classlist',
                   5467: 		   {"$uname:$udom" => 
1.515     raeburn  5468: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5469: 		   $cdom,$cnum);
1.81      www      5470:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5471: 	return 'error: '.$reply;
1.652     albertel 5472:     } else {
                   5473: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5474:     }
1.297     matthew  5475:     # Add student role to user
1.83      www      5476:     my $uurl='/'.$cid;
1.81      www      5477:     $uurl=~s/\_/\//g;
                   5478:     if ($usec) {
                   5479: 	$uurl.='/'.$usec;
                   5480:     }
                   5481:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5482: }
                   5483: 
1.556     albertel 5484: sub format_name {
                   5485:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5486:     my $name;
                   5487:     if ($first ne 'lastname') {
                   5488: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5489:     } else {
                   5490: 	if ($lastname=~/\S/) {
                   5491: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5492: 	    $name=~s/\s+,/,/;
                   5493: 	} else {
                   5494: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5495: 	}
                   5496:     }
                   5497:     $name=~s/^\s+//;
                   5498:     $name=~s/\s+$//;
                   5499:     $name=~s/\s+/ /g;
                   5500:     return $name;
                   5501: }
                   5502: 
1.84      www      5503: # ------------------------------------------------- Write to course preferences
                   5504: 
                   5505: sub writecoursepref {
                   5506:     my ($courseid,%prefs)=@_;
                   5507:     $courseid=~s/^\///;
                   5508:     $courseid=~s/\_/\//g;
                   5509:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5510:     my $chome=homeserver($cnum,$cdomain);
                   5511:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5512: 	return 'error: no such course';
                   5513:     }
                   5514:     my $cstring='';
1.800     albertel 5515:     foreach my $pref (keys(%prefs)) {
                   5516: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5517:     }
1.84      www      5518:     $cstring=~s/\&$//;
                   5519:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5520: }
                   5521: 
                   5522: # ---------------------------------------------------------- Make/modify course
                   5523: 
                   5524: sub createcourse {
1.741     raeburn  5525:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5526:         $course_owner,$crstype)=@_;
1.84      www      5527:     $url=&declutter($url);
                   5528:     my $cid='';
1.264     matthew  5529:     unless (&allowed('ccc',$udom)) {
1.84      www      5530:         return 'refused';
                   5531:     }
                   5532: # ------------------------------------------------------------------- Create ID
1.674     www      5533:    my $uname=int(1+rand(9)).
                   5534:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5535:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5536:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5537: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5538:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5539:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5540:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5541:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5542:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5543:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5544:            return 'error: unable to generate unique course-ID';
                   5545:        } 
                   5546:    }
1.264     matthew  5547: # ------------------------------------------------ Check supplied server name
1.620     albertel 5548:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5549:     if (! &is_library($course_server)) {
1.264     matthew  5550:         return 'error:bad server name '.$course_server;
                   5551:     }
1.84      www      5552: # ------------------------------------------------------------- Make the course
                   5553:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5554:                       $course_server);
1.84      www      5555:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5556:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5557:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5558: 	return 'error: no such course';
                   5559:     }
1.271     www      5560: # ----------------------------------------------------------------- Course made
1.516     raeburn  5561: # log existence
1.918     raeburn  5562:     my $newcourse = {
                   5563:                     $udom.'_'.$uname => {
1.921   ! raeburn  5564:                                      description => $description,
        !          5565:                                      inst_code   => $inst_code,
        !          5566:                                      owner       => $course_owner,
        !          5567:                                      type        => $crstype,
1.918     raeburn  5568:                                                 },
                   5569:                     };
1.921   ! raeburn  5570:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5571: # set toplevel url
1.271     www      5572:     my $topurl=$url;
                   5573:     unless ($nonstandard) {
                   5574: # ------------------------------------------ For standard courses, make top url
                   5575:         my $mapurl=&clutter($url);
1.278     www      5576:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5577:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5578: <map>
                   5579: <resource id="1" type="start"></resource>
                   5580: <resource id="2" src="$mapurl"></resource>
                   5581: <resource id="3" type="finish"></resource>
                   5582: <link index="1" from="1" to="2"></link>
                   5583: <link index="2" from="2" to="3"></link>
                   5584: </map>
                   5585: ENDINITMAP
                   5586:         $topurl=&declutter(
1.638     albertel 5587:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5588:                           );
                   5589:     }
                   5590: # ----------------------------------------------------------- Write preferences
1.84      www      5591:     &writecoursepref($udom.'_'.$uname,
                   5592:                      ('description' => $description,
1.271     www      5593:                       'url'         => $topurl));
1.84      www      5594:     return '/'.$udom.'/'.$uname;
                   5595: }
                   5596: 
1.813     albertel 5597: sub is_course {
                   5598:     my ($cdom,$cnum) = @_;
                   5599:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.918     raeburn  5600: 				undef,'.',undef,1);
1.813     albertel 5601:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5602:         return 1;
                   5603:     }
                   5604:     return 0;
                   5605: }
                   5606: 
1.21      www      5607: # ---------------------------------------------------------- Assign Custom Role
                   5608: 
                   5609: sub assigncustomrole {
1.357     www      5610:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5611:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5612:                        $end,$start,$deleteflag);
1.21      www      5613: }
                   5614: 
                   5615: # ----------------------------------------------------------------- Revoke Role
                   5616: 
                   5617: sub revokerole {
1.357     www      5618:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5619:     my $now=time;
1.357     www      5620:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5621: }
                   5622: 
                   5623: # ---------------------------------------------------------- Revoke Custom Role
                   5624: 
                   5625: sub revokecustomrole {
1.357     www      5626:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5627:     my $now=time;
1.357     www      5628:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5629:            $deleteflag);
1.17      www      5630: }
                   5631: 
1.533     banghart 5632: # ------------------------------------------------------------ Disk usage
1.535     albertel 5633: sub diskusage {
1.533     banghart 5634:     my ($udom,$uname,$directoryRoot)=@_;
                   5635:     $directoryRoot =~ s/\/$//;
1.535     albertel 5636:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5637:     return $listing;
1.512     banghart 5638: }
                   5639: 
1.566     banghart 5640: sub is_locked {
                   5641:     my ($file_name, $domain, $user) = @_;
                   5642:     my @check;
                   5643:     my $is_locked;
                   5644:     push @check, $file_name;
1.613     albertel 5645:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5646: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5647:     my ($tmp)=keys(%locked);
                   5648:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5649:     
1.566     banghart 5650:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5651:         $is_locked = 'false';
                   5652:         foreach my $entry (@{$locked{$file_name}}) {
                   5653:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5654:                $is_locked = 'true';
                   5655:                last;
1.745     raeburn  5656:            }
                   5657:        }
1.566     banghart 5658:     } else {
                   5659:         $is_locked = 'false';
                   5660:     }
                   5661: }
                   5662: 
1.759     albertel 5663: sub declutter_portfile {
                   5664:     my ($file) = @_;
1.833     albertel 5665:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5666:     return $file;
                   5667: }
                   5668: 
1.559     banghart 5669: # ------------------------------------------------------------- Mark as Read Only
                   5670: 
                   5671: sub mark_as_readonly {
                   5672:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5673:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5674:     my ($tmp)=keys(%current_permissions);
                   5675:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5676:     foreach my $file (@{$files}) {
1.759     albertel 5677: 	$file = &declutter_portfile($file);
1.561     banghart 5678:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5679:     }
1.613     albertel 5680:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5681:     return;
                   5682: }
                   5683: 
1.572     banghart 5684: # ------------------------------------------------------------Save Selected Files
                   5685: 
                   5686: sub save_selected_files {
                   5687:     my ($user, $path, @files) = @_;
                   5688:     my $filename = $user."savedfiles";
1.573     banghart 5689:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5690:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5691:     foreach my $file (@files) {
1.620     albertel 5692:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5693:     }
                   5694:     foreach my $file (@other_files) {
1.574     banghart 5695:         print (OUT $file."\n");
1.572     banghart 5696:     }
1.574     banghart 5697:     close (OUT);
1.572     banghart 5698:     return 'ok';
                   5699: }
                   5700: 
1.574     banghart 5701: sub clear_selected_files {
                   5702:     my ($user) = @_;
                   5703:     my $filename = $user."savedfiles";
                   5704:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5705:     print (OUT undef);
                   5706:     close (OUT);
                   5707:     return ("ok");    
                   5708: }
                   5709: 
1.572     banghart 5710: sub files_in_path {
                   5711:     my ($user, $path) = @_;
                   5712:     my $filename = $user."savedfiles";
                   5713:     my %return_files;
1.574     banghart 5714:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5715:     while (my $line_in = <IN>) {
1.574     banghart 5716:         chomp ($line_in);
                   5717:         my @paths_and_file = split (m!/!, $line_in);
                   5718:         my $file_part = pop (@paths_and_file);
                   5719:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5720:         $path_part.='/';
                   5721:         my $path_and_file = $path_part.$file_part;
                   5722:         if ($path_part eq $path) {
                   5723:             $return_files{$file_part}= 'selected';
                   5724:         }
                   5725:     }
1.574     banghart 5726:     close (IN);
                   5727:     return (\%return_files);
1.572     banghart 5728: }
                   5729: 
                   5730: # called in portfolio select mode, to show files selected NOT in current directory
                   5731: sub files_not_in_path {
                   5732:     my ($user, $path) = @_;
                   5733:     my $filename = $user."savedfiles";
                   5734:     my @return_files;
                   5735:     my $path_part;
1.800     albertel 5736:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5737:     while (my $line = <IN>) {
1.572     banghart 5738:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5739:         my @paths_and_file = split(m|/|, $line);
                   5740:         my $file_part = pop(@paths_and_file);
                   5741:         chomp($file_part);
                   5742:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5743:         $path_part .= '/';
                   5744:         my $path_and_file = $path_part.$file_part;
                   5745:         if ($path_part ne $path) {
1.800     albertel 5746:             push(@return_files, ($path_and_file));
1.572     banghart 5747:         }
                   5748:     }
1.800     albertel 5749:     close(OUT);
1.574     banghart 5750:     return (@return_files);
1.572     banghart 5751: }
                   5752: 
1.745     raeburn  5753: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5754: 
1.745     raeburn  5755: sub get_portfile_permissions {
                   5756:     my ($domain,$user) = @_;
1.613     albertel 5757:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5758:     my ($tmp)=keys(%current_permissions);
                   5759:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5760:     return \%current_permissions;
                   5761: }
                   5762: 
                   5763: #---------------------------------------------Get portfolio file access controls
                   5764: 
1.749     raeburn  5765: sub get_access_controls {
1.745     raeburn  5766:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5767:     my %access;
                   5768:     my $real_file = $file;
                   5769:     $file =~ s/\.meta$//;
1.745     raeburn  5770:     if (defined($file)) {
1.749     raeburn  5771:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5772:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5773:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5774:             }
                   5775:         }
1.745     raeburn  5776:     } else {
1.749     raeburn  5777:         foreach my $key (keys(%{$current_permissions})) {
                   5778:             if ($key =~ /\0accesscontrol$/) {
                   5779:                 if (defined($group)) {
                   5780:                     if ($key !~ m-^\Q$group\E/-) {
                   5781:                         next;
                   5782:                     }
                   5783:                 }
                   5784:                 my ($fullpath) = split(/\0/,$key);
                   5785:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5786:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5787:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5788:                     }
                   5789:                 }
                   5790:             }
                   5791:         }
                   5792:     }
                   5793:     return %access;
                   5794: }
                   5795: 
                   5796: sub modify_access_controls {
                   5797:     my ($file_name,$changes,$domain,$user)=@_;
                   5798:     my ($outcome,$deloutcome);
                   5799:     my %store_permissions;
                   5800:     my %new_values;
                   5801:     my %new_control;
                   5802:     my %translation;
                   5803:     my @deletions = ();
                   5804:     my $now = time;
                   5805:     if (exists($$changes{'activate'})) {
                   5806:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5807:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5808:             my $numnew = scalar(@newitems);
                   5809:             for (my $i=0; $i<$numnew; $i++) {
                   5810:                 my $newkey = $newitems[$i];
                   5811:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5812:                 if ($newkey =~ /^\d+:/) { 
                   5813:                     $newkey =~ s/^(\d+)/$newid/;
                   5814:                     $translation{$1} = $newid;
                   5815:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5816:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5817:                     $translation{$1} = $newid;
                   5818:                 }
1.749     raeburn  5819:                 $new_values{$file_name."\0".$newkey} = 
                   5820:                                           $$changes{'activate'}{$newitems[$i]};
                   5821:                 $new_control{$newkey} = $now;
                   5822:             }
                   5823:         }
                   5824:     }
                   5825:     my %todelete;
                   5826:     my %changed_items;
                   5827:     foreach my $action ('delete','update') {
                   5828:         if (exists($$changes{$action})) {
                   5829:             if (ref($$changes{$action}) eq 'HASH') {
                   5830:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5831:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5832:                     if ($action eq 'delete') { 
                   5833:                         $todelete{$itemnum} = 1;
                   5834:                     } else {
                   5835:                         $changed_items{$itemnum} = $key;
                   5836:                     }
                   5837:                 }
1.745     raeburn  5838:             }
                   5839:         }
1.749     raeburn  5840:     }
                   5841:     # get lock on access controls for file.
                   5842:     my $lockhash = {
                   5843:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5844:                                                        ':'.$env{'user.domain'},
                   5845:                    }; 
                   5846:     my $tries = 0;
                   5847:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5848:    
                   5849:     while (($gotlock ne 'ok') && $tries <3) {
                   5850:         $tries ++;
                   5851:         sleep 1;
                   5852:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5853:     }
                   5854:     if ($gotlock eq 'ok') {
                   5855:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5856:         my ($tmp)=keys(%curr_permissions);
                   5857:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5858:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5859:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5860:             if (ref($curr_controls) eq 'HASH') {
                   5861:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5862:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5863:                     if (defined($todelete{$itemnum})) {
                   5864:                         push(@deletions,$file_name."\0".$control_item);
                   5865:                     } else {
                   5866:                         if (defined($changed_items{$itemnum})) {
                   5867:                             $new_control{$changed_items{$itemnum}} = $now;
                   5868:                             push(@deletions,$file_name."\0".$control_item);
                   5869:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5870:                         } else {
                   5871:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5872:                         }
                   5873:                     }
1.745     raeburn  5874:                 }
                   5875:             }
                   5876:         }
1.749     raeburn  5877:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5878:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5879:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5880:         #  remove lock
                   5881:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5882:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5883:         my ($file,$group);
                   5884:         if (&is_course($domain,$user)) {
                   5885:             ($group,$file) = split(/\//,$file_name,2);
                   5886:         } else {
                   5887:             $file = $file_name;
                   5888:         }
                   5889:         my $sqlresult =
                   5890:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5891:                                     $group);
1.749     raeburn  5892:     } else {
                   5893:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5894:     }
1.749     raeburn  5895:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5896: }
                   5897: 
1.827     raeburn  5898: sub make_public_indefinitely {
                   5899:     my ($requrl) = @_;
                   5900:     my $now = time;
                   5901:     my $action = 'activate';
                   5902:     my $aclnum = 0;
                   5903:     if (&is_portfolio_url($requrl)) {
                   5904:         my (undef,$udom,$unum,$file_name,$group) =
                   5905:             &parse_portfolio_url($requrl);
                   5906:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5907:         my %access_controls = &get_access_controls($current_perms,
                   5908:                                                    $group,$file_name);
                   5909:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5910:             my ($num,$scope,$end,$start) = 
                   5911:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5912:             if ($scope eq 'public') {
                   5913:                 if ($start <= $now && $end == 0) {
                   5914:                     $action = 'none';
                   5915:                 } else {
                   5916:                     $action = 'update';
                   5917:                     $aclnum = $num;
                   5918:                 }
                   5919:                 last;
                   5920:             }
                   5921:         }
                   5922:         if ($action eq 'none') {
                   5923:              return 'ok';
                   5924:         } else {
                   5925:             my %changes;
                   5926:             my $newend = 0;
                   5927:             my $newstart = $now;
                   5928:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5929:             $changes{$action}{$newkey} = {
                   5930:                 type => 'public',
                   5931:                 time => {
                   5932:                     start => $newstart,
                   5933:                     end   => $newend,
                   5934:                 },
                   5935:             };
                   5936:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5937:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5938:             return $outcome;
                   5939:         }
                   5940:     } else {
                   5941:         return 'invalid';
                   5942:     }
                   5943: }
                   5944: 
1.745     raeburn  5945: #------------------------------------------------------Get Marked as Read Only
                   5946: 
                   5947: sub get_marked_as_readonly {
                   5948:     my ($domain,$user,$what,$group) = @_;
                   5949:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5950:     my @readonly_files;
1.629     banghart 5951:     my $cmp1=$what;
                   5952:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5953:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5954:         if (defined($group)) {
                   5955:             if ($file_name !~ m-^\Q$group\E/-) {
                   5956:                 next;
                   5957:             }
                   5958:         }
1.561     banghart 5959:         if (ref($value) eq "ARRAY"){
                   5960:             foreach my $stored_what (@{$value}) {
1.629     banghart 5961:                 my $cmp2=$stored_what;
1.759     albertel 5962:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5963:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5964:                 }
1.629     banghart 5965:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5966:                     push(@readonly_files, $file_name);
1.745     raeburn  5967:                     last;
1.563     banghart 5968:                 } elsif (!defined($what)) {
                   5969:                     push(@readonly_files, $file_name);
1.745     raeburn  5970:                     last;
1.561     banghart 5971:                 }
                   5972:             }
1.745     raeburn  5973:         }
1.561     banghart 5974:     }
                   5975:     return @readonly_files;
                   5976: }
1.577     banghart 5977: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5978: 
1.577     banghart 5979: sub get_marked_as_readonly_hash {
1.745     raeburn  5980:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5981:     my %readonly_files;
1.745     raeburn  5982:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5983:         if (defined($group)) {
                   5984:             if ($file_name !~ m-^\Q$group\E/-) {
                   5985:                 next;
                   5986:             }
                   5987:         }
1.577     banghart 5988:         if (ref($value) eq "ARRAY"){
                   5989:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5990:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5991:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5992:                         if ($lock_descriptor eq 'graded') {
                   5993:                             $readonly_files{$file_name} = 'graded';
                   5994:                         } elsif ($lock_descriptor eq 'handback') {
                   5995:                             $readonly_files{$file_name} = 'handback';
                   5996:                         } else {
                   5997:                             if (!exists($readonly_files{$file_name})) {
                   5998:                                 $readonly_files{$file_name} = 'locked';
                   5999:                             }
                   6000:                         }
1.745     raeburn  6001:                     }
1.750     banghart 6002:                 } 
1.577     banghart 6003:             }
                   6004:         } 
                   6005:     }
                   6006:     return %readonly_files;
                   6007: }
1.559     banghart 6008: # ------------------------------------------------------------ Unmark as Read Only
                   6009: 
                   6010: sub unmark_as_readonly {
1.629     banghart 6011:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6012:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6013:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6014:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6015:     my $symb_crs = $what;
                   6016:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6017:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6018:     my ($tmp)=keys(%current_permissions);
                   6019:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6020:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6021:     foreach my $file (@readonly_files) {
1.759     albertel 6022: 	my $clean_file = &declutter_portfile($file);
                   6023: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6024: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6025:         my @new_locks;
                   6026:         my @del_keys;
                   6027:         if (ref($current_locks) eq "ARRAY"){
                   6028:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6029:                 my $compare=$locker;
1.749     raeburn  6030:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6031:                     $compare=join('',@{$locker});
1.746     raeburn  6032:                     if ($compare ne $symb_crs) {
                   6033:                         push(@new_locks, $locker);
                   6034:                     }
1.563     banghart 6035:                 }
                   6036:             }
1.650     albertel 6037:             if (scalar(@new_locks) > 0) {
1.563     banghart 6038:                 $current_permissions{$file} = \@new_locks;
                   6039:             } else {
                   6040:                 push(@del_keys, $file);
1.613     albertel 6041:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6042:                 delete($current_permissions{$file});
1.563     banghart 6043:             }
                   6044:         }
1.561     banghart 6045:     }
1.613     albertel 6046:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6047:     return;
                   6048: }
1.512     banghart 6049: 
1.17      www      6050: # ------------------------------------------------------------ Directory lister
                   6051: 
                   6052: sub dirlist {
1.253     stredwic 6053:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   6054: 
1.18      www      6055:     $uri=~s/^\///;
                   6056:     $uri=~s/\/$//;
1.253     stredwic 6057:     my ($udom, $uname);
                   6058:     (undef,$udom,$uname)=split(/\//,$uri);
                   6059:     if(defined($userdomain)) {
                   6060:         $udom = $userdomain;
                   6061:     }
                   6062:     if(defined($username)) {
                   6063:         $uname = $username;
                   6064:     }
                   6065: 
                   6066:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6067:     if(defined($alternateDirectoryRoot)) {
                   6068:         $dirRoot = $alternateDirectoryRoot;
                   6069:         $dirRoot =~ s/\/$//;
1.751     banghart 6070:     }
1.253     stredwic 6071: 
                   6072:     if($udom) {
                   6073:         if($uname) {
1.800     albertel 6074:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6075: 				 &homeserver($uname,$udom));
1.605     matthew  6076:             my @listing_results;
                   6077:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6078:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6079: 				  &homeserver($uname,$udom));
1.605     matthew  6080:                 @listing_results = split(/:/,$listing);
                   6081:             } else {
                   6082:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6083:             }
                   6084:             return @listing_results;
1.253     stredwic 6085:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6086:             my %allusers;
1.841     albertel 6087: 	    my %servers = &get_servers($udom,'library');
                   6088: 	    foreach my $tryserver (keys(%servers)) {
                   6089: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6090: 				     $udom, $tryserver);
                   6091: 		my @listing_results;
                   6092: 		if ($listing eq 'unknown_cmd') {
                   6093: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6094: 				      $udom, $tryserver);
                   6095: 		    @listing_results = split(/:/,$listing);
                   6096: 		} else {
                   6097: 		    @listing_results =
                   6098: 			map { &unescape($_); } split(/:/,$listing);
                   6099: 		}
                   6100: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6101: 		    $listing_results[0] ne 'empty'       &&
                   6102: 		    $listing_results[0] ne 'con_lost') {
                   6103: 		    foreach my $line (@listing_results) {
                   6104: 			my ($entry) = split(/&/,$line,2);
                   6105: 			$allusers{$entry} = 1;
                   6106: 		    }
                   6107: 		}
1.253     stredwic 6108:             }
                   6109:             my $alluserstr='';
1.800     albertel 6110:             foreach my $user (sort(keys(%allusers))) {
                   6111:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6112:             }
                   6113:             $alluserstr=~s/:$//;
                   6114:             return split(/:/,$alluserstr);
                   6115:         } else {
1.800     albertel 6116:             return ('missing user name');
1.253     stredwic 6117:         }
                   6118:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6119:         my @all_domains = sort(&all_domains());
                   6120:          foreach my $domain (@all_domains) {
                   6121:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6122:          }
                   6123:          return @all_domains;
                   6124:      } else {
1.800     albertel 6125:         return ('missing domain');
1.275     stredwic 6126:     }
                   6127: }
                   6128: 
                   6129: # --------------------------------------------- GetFileTimestamp
                   6130: # This function utilizes dirlist and returns the date stamp for
                   6131: # when it was last modified.  It will also return an error of -1
                   6132: # if an error occurs
                   6133: 
1.410     matthew  6134: ##
                   6135: ## FIXME: This subroutine assumes its caller knows something about the
                   6136: ## directory structure of the home server for the student ($root).
                   6137: ## Not a good assumption to make.  Since this is for looking up files
                   6138: ## in user directories, the full path should be constructed by lond, not
                   6139: ## whatever machine we request data from.
                   6140: ##
1.275     stredwic 6141: sub GetFileTimestamp {
                   6142:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6143:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6144:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6145:     my $subdir=$studentName.'__';
                   6146:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6147:     my $proname="$studentDomain/$subdir/$studentName";
                   6148:     $proname .= '/'.$filename;
1.375     matthew  6149:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6150:                                               $studentName, $root);
1.275     stredwic 6151:     my @stats = split('&', $fileStat);
                   6152:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6153:         # @stats contains first the filename, then the stat output
                   6154:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6155:     } else {
                   6156:         return -1;
1.253     stredwic 6157:     }
1.26      www      6158: }
                   6159: 
1.712     albertel 6160: sub stat_file {
                   6161:     my ($uri) = @_;
1.787     albertel 6162:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6163: 
1.712     albertel 6164:     my ($udom,$uname,$file,$dir);
                   6165:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6166: 	($udom,$uname,$file) =
1.811     albertel 6167: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6168: 	$file = 'userfiles/'.$file;
1.740     www      6169: 	$dir = &propath($udom,$uname);
1.712     albertel 6170:     }
                   6171:     if ($uri =~ m-^/res/-) {
                   6172: 	($udom,$uname) = 
1.807     albertel 6173: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6174: 	$file = $uri;
                   6175:     }
                   6176: 
                   6177:     if (!$udom || !$uname || !$file) {
                   6178: 	# unable to handle the uri
                   6179: 	return ();
                   6180:     }
                   6181: 
                   6182:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6183:     my @stats = split('&', $result);
1.721     banghart 6184:     
1.712     albertel 6185:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6186: 	shift(@stats); #filename is first
                   6187: 	return @stats;
                   6188:     }
                   6189:     return ();
                   6190: }
                   6191: 
1.26      www      6192: # -------------------------------------------------------- Value of a Condition
                   6193: 
1.713     albertel 6194: # gets the value of a specific preevaluated condition
                   6195: #    stored in the string  $env{user.state.<cid>}
                   6196: # or looks up a condition reference in the bighash and if if hasn't
                   6197: # already been evaluated recurses into docondval to get the value of
                   6198: # the condition, then memoizing it to 
                   6199: #   $env{user.state.<cid>.<condition>}
1.40      www      6200: sub directcondval {
                   6201:     my $number=shift;
1.620     albertel 6202:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6203: 	&Apache::lonuserstate::evalstate();
                   6204:     }
1.713     albertel 6205:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6206: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6207:     } elsif ($number =~ /^_/) {
                   6208: 	my $sub_condition;
                   6209: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6210: 		&GDBM_READER(),0640)) {
                   6211: 	    $sub_condition=$bighash{'conditions'.$number};
                   6212: 	    untie(%bighash);
                   6213: 	}
                   6214: 	my $value = &docondval($sub_condition);
                   6215: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6216: 	return $value;
                   6217:     }
1.620     albertel 6218:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6219:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6220:     } else {
                   6221:        return 2;
                   6222:     }
                   6223: }
                   6224: 
1.713     albertel 6225: # get the collection of conditions for this resource
1.26      www      6226: sub condval {
                   6227:     my $condidx=shift;
1.54      www      6228:     my $allpathcond='';
1.713     albertel 6229:     foreach my $cond (split(/\|/,$condidx)) {
                   6230: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6231: 	    $allpathcond.=
                   6232: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6233: 	}
1.191     harris41 6234:     }
1.54      www      6235:     $allpathcond=~s/\|$//;
1.713     albertel 6236:     return &docondval($allpathcond);
                   6237: }
                   6238: 
                   6239: #evaluates an expression of conditions
                   6240: sub docondval {
                   6241:     my ($allpathcond) = @_;
                   6242:     my $result=0;
                   6243:     if ($env{'request.course.id'}
                   6244: 	&& defined($allpathcond)) {
                   6245: 	my $operand='|';
                   6246: 	my @stack;
                   6247: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6248: 	    if ($chunk eq '(') {
                   6249: 		push @stack,($operand,$result);
                   6250: 	    } elsif ($chunk eq ')') {
                   6251: 		my $before=pop @stack;
                   6252: 		if (pop @stack eq '&') {
                   6253: 		    $result=$result>$before?$before:$result;
                   6254: 		} else {
                   6255: 		    $result=$result>$before?$result:$before;
                   6256: 		}
                   6257: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6258: 		$operand=$chunk;
                   6259: 	    } else {
                   6260: 		my $new=directcondval($chunk);
                   6261: 		if ($operand eq '&') {
                   6262: 		    $result=$result>$new?$new:$result;
                   6263: 		} else {
                   6264: 		    $result=$result>$new?$result:$new;
                   6265: 		}
                   6266: 	    }
                   6267: 	}
1.26      www      6268:     }
                   6269:     return $result;
1.421     albertel 6270: }
                   6271: 
                   6272: # ---------------------------------------------------- Devalidate courseresdata
                   6273: 
                   6274: sub devalidatecourseresdata {
                   6275:     my ($coursenum,$coursedomain)=@_;
                   6276:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6277:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6278: }
                   6279: 
1.763     www      6280: 
1.200     www      6281: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6282: #
                   6283: #  Parameters:
                   6284: #      $coursenum    - Number of the course.
                   6285: #      $coursedomain - Domain at which the course was created.
                   6286: #  Returns:
                   6287: #     A hash of the course parameters along (I think) with timestamps
                   6288: #     and version info.
1.877     foxr     6289: 
1.624     albertel 6290: sub get_courseresdata {
                   6291:     my ($coursenum,$coursedomain)=@_;
1.200     www      6292:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6293:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6294:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6295:     my %dumpreply;
1.417     albertel 6296:     unless (defined($cached)) {
1.624     albertel 6297: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6298: 	$result=\%dumpreply;
1.251     albertel 6299: 	my ($tmp) = keys(%dumpreply);
                   6300: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6301: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6302: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6303: 	    return $tmp;
1.416     albertel 6304: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6305: 	    $result=undef;
1.599     albertel 6306: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6307: 	}
                   6308:     }
1.624     albertel 6309:     return $result;
                   6310: }
                   6311: 
1.633     albertel 6312: sub devalidateuserresdata {
                   6313:     my ($uname,$udom)=@_;
                   6314:     my $hashid="$udom:$uname";
                   6315:     &devalidate_cache_new('userres',$hashid);
                   6316: }
                   6317: 
1.624     albertel 6318: sub get_userresdata {
                   6319:     my ($uname,$udom)=@_;
                   6320:     #most student don\'t have any data set, check if there is some data
                   6321:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6322: 
                   6323:     my $hashid="$udom:$uname";
                   6324:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6325:     if (!defined($cached)) {
                   6326: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6327: 	$result=\%resourcedata;
                   6328: 	&do_cache_new('userres',$hashid,$result,600);
                   6329:     }
                   6330:     my ($tmp)=keys(%$result);
                   6331:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6332: 	return $result;
                   6333:     }
                   6334:     #error 2 occurs when the .db doesn't exist
                   6335:     if ($tmp!~/error: 2 /) {
1.672     albertel 6336: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6337: 		 " Trying to get resource data for ".
                   6338: 		 $uname." at ".$udom.": ".
                   6339: 		 $tmp."</font>");
                   6340:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6341: 	#&EXT_cache_set($udom,$uname);
                   6342: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6343: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6344:     }
                   6345:     return $tmp;
                   6346: }
1.879     foxr     6347: #----------------------------------------------- resdata - return resource data
                   6348: #  Purpose:
                   6349: #    Return resource data for either users or for a course.
                   6350: #  Parameters:
                   6351: #     $name      - Course/user name.
                   6352: #     $domain    - Name of the domain the user/course is registered on.
                   6353: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6354: #     @which     - Array of names of resources desired.
                   6355: #  Returns:
                   6356: #     The value of the first reasource in @which that is found in the
                   6357: #     resource hash.
                   6358: #  Exceptional Conditions:
                   6359: #     If the $type passed in is not valid (not the string 'course' or 
                   6360: #     'user', an undefined  reference is returned.
                   6361: #     If none of the resources are found, an undef is returned
1.624     albertel 6362: sub resdata {
                   6363:     my ($name,$domain,$type,@which)=@_;
                   6364:     my $result;
                   6365:     if ($type eq 'course') {
                   6366: 	$result=&get_courseresdata($name,$domain);
                   6367:     } elsif ($type eq 'user') {
                   6368: 	$result=&get_userresdata($name,$domain);
                   6369:     }
                   6370:     if (!ref($result)) { return $result; }    
1.251     albertel 6371:     foreach my $item (@which) {
1.417     albertel 6372: 	if (defined($result->{$item})) {
                   6373: 	    return $result->{$item};
1.251     albertel 6374: 	}
1.250     albertel 6375:     }
1.291     albertel 6376:     return undef;
1.200     www      6377: }
                   6378: 
1.379     matthew  6379: #
                   6380: # EXT resource caching routines
                   6381: #
                   6382: 
                   6383: sub clear_EXT_cache_status {
1.383     albertel 6384:     &delenv('cache.EXT.');
1.379     matthew  6385: }
                   6386: 
                   6387: sub EXT_cache_status {
                   6388:     my ($target_domain,$target_user) = @_;
1.383     albertel 6389:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6390:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6391:         # We know already the user has no data
                   6392:         return 1;
                   6393:     } else {
                   6394:         return 0;
                   6395:     }
                   6396: }
                   6397: 
                   6398: sub EXT_cache_set {
                   6399:     my ($target_domain,$target_user) = @_;
1.383     albertel 6400:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6401:     #&appenv($cachename => time);
1.379     matthew  6402: }
                   6403: 
1.28      www      6404: # --------------------------------------------------------- Value of a Variable
1.58      www      6405: sub EXT {
1.715     albertel 6406: 
1.395     albertel 6407:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6408:     unless ($varname) { return ''; }
1.218     albertel 6409:     #get real user name/domain, courseid and symb
                   6410:     my $courseid;
1.359     albertel 6411:     my $publicuser;
1.427     www      6412:     if ($symbparm) {
                   6413: 	$symbparm=&get_symb_from_alias($symbparm);
                   6414:     }
1.218     albertel 6415:     if (!($uname && $udom)) {
1.790     albertel 6416:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6417:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6418:     } else {
1.620     albertel 6419: 	$courseid=$env{'request.course.id'};
1.218     albertel 6420:     }
1.48      www      6421:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6422:     my $rest;
1.320     albertel 6423:     if (defined($therest[0])) {
1.48      www      6424:        $rest=join('.',@therest);
                   6425:     } else {
                   6426:        $rest='';
                   6427:     }
1.320     albertel 6428: 
1.57      www      6429:     my $qualifierrest=$qualifier;
                   6430:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6431:     my $spacequalifierrest=$space;
                   6432:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6433:     if ($realm eq 'user') {
1.48      www      6434: # --------------------------------------------------------------- user.resource
                   6435: 	if ($space eq 'resource') {
1.651     albertel 6436: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6437: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6438: 		 &&
1.744     albertel 6439: 		 ($symbparm eq &symbread()) ) {	
                   6440: 		# if we are in the middle of processing the resource the
                   6441: 		# get the value we are planning on committing
                   6442:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6443:                     return $Apache::lonhomework::results{$qualifierrest};
                   6444:                 } else {
                   6445:                     return $Apache::lonhomework::history{$qualifierrest};
                   6446:                 }
1.335     albertel 6447: 	    } else {
1.359     albertel 6448: 		my %restored;
1.620     albertel 6449: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6450: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6451: 		} else {
                   6452: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6453: 		}
1.335     albertel 6454: 		return $restored{$qualifierrest};
                   6455: 	    }
1.48      www      6456: # ----------------------------------------------------------------- user.access
                   6457:         } elsif ($space eq 'access') {
1.218     albertel 6458: 	    # FIXME - not supporting calls for a specific user
1.48      www      6459:             return &allowed($qualifier,$rest);
                   6460: # ------------------------------------------ user.preferences, user.environment
                   6461:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6462: 	    if (($uname eq $env{'user.name'}) &&
                   6463: 		($udom eq $env{'user.domain'})) {
                   6464: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6465: 	    } else {
1.359     albertel 6466: 		my %returnhash;
                   6467: 		if (!$publicuser) {
                   6468: 		    %returnhash=&userenvironment($udom,$uname,
                   6469: 						 $qualifierrest);
                   6470: 		}
1.218     albertel 6471: 		return $returnhash{$qualifierrest};
                   6472: 	    }
1.48      www      6473: # ----------------------------------------------------------------- user.course
                   6474:         } elsif ($space eq 'course') {
1.218     albertel 6475: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6476:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6477: # ------------------------------------------------------------------- user.role
                   6478:         } elsif ($space eq 'role') {
1.218     albertel 6479: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6480:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6481:             if ($qualifier eq 'value') {
                   6482: 		return $role;
                   6483:             } elsif ($qualifier eq 'extent') {
                   6484:                 return $where;
                   6485:             }
                   6486: # ----------------------------------------------------------------- user.domain
                   6487:         } elsif ($space eq 'domain') {
1.218     albertel 6488:             return $udom;
1.48      www      6489: # ------------------------------------------------------------------- user.name
                   6490:         } elsif ($space eq 'name') {
1.218     albertel 6491:             return $uname;
1.48      www      6492: # ---------------------------------------------------- Any other user namespace
1.29      www      6493:         } else {
1.359     albertel 6494: 	    my %reply;
                   6495: 	    if (!$publicuser) {
                   6496: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6497: 	    }
                   6498: 	    return $reply{$qualifierrest};
1.48      www      6499:         }
1.236     www      6500:     } elsif ($realm eq 'query') {
                   6501: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6502:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6503: 						[$spacequalifierrest]);
1.620     albertel 6504: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6505:    } elsif ($realm eq 'request') {
1.48      www      6506: # ------------------------------------------------------------- request.browser
                   6507:         if ($space eq 'browser') {
1.430     www      6508: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6509: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6510: 		    return 1;
                   6511: 		} else {
                   6512: 		    return 0;
                   6513: 		}
                   6514: 	    } else {
1.620     albertel 6515: 		return $env{'browser.'.$qualifier};
1.430     www      6516: 	    }
1.57      www      6517: # ------------------------------------------------------------ request.filename
                   6518:         } else {
1.620     albertel 6519:             return $env{'request.'.$spacequalifierrest};
1.29      www      6520:         }
1.28      www      6521:     } elsif ($realm eq 'course') {
1.48      www      6522: # ---------------------------------------------------------- course.description
1.620     albertel 6523:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6524:     } elsif ($realm eq 'resource') {
1.165     www      6525: 
1.620     albertel 6526: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6527: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6528: 	}
1.693     albertel 6529: 
                   6530: 	if ($space eq 'title') {
                   6531: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6532: 	    return &gettitle($symbparm);
                   6533: 	}
                   6534: 	
                   6535: 	if ($space eq 'map') {
                   6536: 	    my ($map) = &decode_symb($symbparm);
                   6537: 	    return &symbread($map);
                   6538: 	}
1.905     albertel 6539: 	if ($space eq 'filename') {
                   6540: 	    if ($symbparm) {
                   6541: 		return &clutter((&decode_symb($symbparm))[2]);
                   6542: 	    }
                   6543: 	    return &hreflocation('',$env{'request.filename'});
                   6544: 	}
1.693     albertel 6545: 
                   6546: 	my ($section, $group, @groups);
1.593     albertel 6547: 	my ($courselevelm,$courselevel);
1.539     albertel 6548: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6549: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6550: 
1.218     albertel 6551: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6552: 
1.60      www      6553: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6554: 	    my $symbp=$symbparm;
1.735     albertel 6555: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6556: 
                   6557: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6558: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6559: 
1.620     albertel 6560: 	    if (($env{'user.name'} eq $uname) &&
                   6561: 		($env{'user.domain'} eq $udom)) {
                   6562: 		$section=$env{'request.course.sec'};
1.733     raeburn  6563:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6564:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6565: 	    } else {
1.539     albertel 6566: 		if (! defined($usection)) {
1.551     albertel 6567: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6568: 		} else {
                   6569: 		    $section = $usection;
                   6570: 		}
1.733     raeburn  6571:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6572: 	    }
                   6573: 
                   6574: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6575: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6576: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6577: 
1.593     albertel 6578: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6579: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6580: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6581: 
1.60      www      6582: # ----------------------------------------------------------- first, check user
1.624     albertel 6583: 
                   6584: 	    my $userreply=&resdata($uname,$udom,'user',
                   6585: 				       ($courselevelr,$courselevelm,
                   6586: 					$courselevel));
                   6587: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6588: 
1.594     albertel 6589: # ------------------------------------------------ second, check some of course
1.684     raeburn  6590:             my $coursereply;
1.691     raeburn  6591:             if (@groups > 0) {
                   6592:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6593:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6594:                 if (defined($coursereply)) { return $coursereply; }
                   6595:             }
1.96      www      6596: 
1.684     raeburn  6597: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6598: 				     $env{'course.'.$courseid.'.domain'},
                   6599: 				     'course',
                   6600: 				     ($seclevelr,$seclevelm,$seclevel,
                   6601: 				      $courselevelr));
1.287     albertel 6602: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6603: 
1.60      www      6604: # ------------------------------------------------------ third, check map parms
1.218     albertel 6605: 	    my %parmhash=();
                   6606: 	    my $thisparm='';
                   6607: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6608: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6609: 		    &GDBM_READER(),0640)) {
1.218     albertel 6610: 		$thisparm=$parmhash{$symbparm};
                   6611: 		untie(%parmhash);
                   6612: 	    }
                   6613: 	    if ($thisparm) { return $thisparm; }
                   6614: 	}
1.594     albertel 6615: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6616: 
1.218     albertel 6617: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6618: 	my $filename;
                   6619: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6620: 	if ($symbparm) {
1.409     www      6621: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6622: 	} else {
1.620     albertel 6623: 	    $filename=$env{'request.filename'};
1.282     albertel 6624: 	}
                   6625: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6626: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6627: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6628: 	if (defined($metadata)) { return $metadata; }
1.142     www      6629: 
1.594     albertel 6630: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6631: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6632: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6633: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6634: 				     $env{'course.'.$courseid.'.domain'},
                   6635: 				     'course',
                   6636: 				     ($courselevelm,$courselevel));
1.593     albertel 6637: 	    if (defined($coursereply)) { return $coursereply; }
                   6638: 	}
1.145     www      6639: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6640: 	unless ($space eq '0') {
1.336     albertel 6641: 	    my @parts=split(/_/,$space);
                   6642: 	    my $id=pop(@parts);
                   6643: 	    my $part=join('_',@parts);
                   6644: 	    if ($part eq '') { $part='0'; }
                   6645: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6646: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6647: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6648: 	}
1.395     albertel 6649: 	if ($recurse) { return undef; }
                   6650: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6651: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6652: 
1.48      www      6653: # ---------------------------------------------------- Any other user namespace
                   6654:     } elsif ($realm eq 'environment') {
                   6655: # ----------------------------------------------------------------- environment
1.620     albertel 6656: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6657: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6658: 	} else {
1.770     albertel 6659: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6660: 		return '';
                   6661: 	    }
1.219     albertel 6662: 	    my %returnhash=&userenvironment($udom,$uname,
                   6663: 					    $spacequalifierrest);
                   6664: 	    return $returnhash{$spacequalifierrest};
                   6665: 	}
1.28      www      6666:     } elsif ($realm eq 'system') {
1.48      www      6667: # ----------------------------------------------------------------- system.time
                   6668: 	if ($space eq 'time') {
                   6669: 	    return time;
                   6670:         }
1.696     albertel 6671:     } elsif ($realm eq 'server') {
                   6672: # ----------------------------------------------------------------- system.time
                   6673: 	if ($space eq 'name') {
                   6674: 	    return $ENV{'SERVER_NAME'};
                   6675:         }
1.28      www      6676:     }
1.48      www      6677:     return '';
1.61      www      6678: }
                   6679: 
1.691     raeburn  6680: sub check_group_parms {
                   6681:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6682:     my @groupitems = ();
                   6683:     my $resultitem;
                   6684:     my @levels = ($symbparm,$mapparm,$what);
                   6685:     foreach my $group (@{$groups}) {
                   6686:         foreach my $level (@levels) {
                   6687:              my $item = $courseid.'.['.$group.'].'.$level;
                   6688:              push(@groupitems,$item);
                   6689:         }
                   6690:     }
                   6691:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6692:                             $env{'course.'.$courseid.'.domain'},
                   6693:                                      'course',@groupitems);
                   6694:     return $coursereply;
                   6695: }
                   6696: 
                   6697: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6698:     my ($courseid,@groups) = @_;
                   6699:     @groups = sort(@groups);
1.691     raeburn  6700:     return @groups;
                   6701: }
                   6702: 
1.395     albertel 6703: sub packages_tab_default {
                   6704:     my ($uri,$varname)=@_;
                   6705:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6706: 
                   6707:     my (@extension,@specifics,$do_default);
                   6708:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6709: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6710: 	if ($pack_type eq 'default') {
                   6711: 	    $do_default=1;
                   6712: 	} elsif ($pack_type eq 'extension') {
                   6713: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6714: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6715: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6716: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6717: 	}
                   6718:     }
                   6719:     # first look for a package that matches the requested part id
                   6720:     foreach my $package (@specifics) {
                   6721: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6722: 	next if ($pack_part ne $part);
                   6723: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6724: 	    return $packagetab{"$pack_type&$name&default"};
                   6725: 	}
                   6726:     }
                   6727:     # look for any possible matching non extension_ package
                   6728:     foreach my $package (@specifics) {
                   6729: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6730: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6731: 	    return $packagetab{"$pack_type&$name&default"};
                   6732: 	}
1.585     albertel 6733: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6734: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6735: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6736: 	}
                   6737:     }
1.738     albertel 6738:     # look for any posible extension_ match
                   6739:     foreach my $package (@extension) {
                   6740: 	my ($package,$pack_type)=@{$package};
                   6741: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6742: 	    return $packagetab{"$pack_type&$name&default"};
                   6743: 	}
                   6744: 	if (defined($packagetab{$package."&$name&default"})) {
                   6745: 	    return $packagetab{$package."&$name&default"};
                   6746: 	}
                   6747:     }
                   6748:     # look for a global default setting
                   6749:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6750: 	return $packagetab{"default&$name&default"};
                   6751:     }
1.395     albertel 6752:     return undef;
                   6753: }
                   6754: 
1.334     albertel 6755: sub add_prefix_and_part {
                   6756:     my ($prefix,$part)=@_;
                   6757:     my $keyroot;
                   6758:     if (defined($prefix) && $prefix !~ /^__/) {
                   6759: 	# prefix that has a part already
                   6760: 	$keyroot=$prefix;
                   6761:     } elsif (defined($prefix)) {
                   6762: 	# prefix that is missing a part
                   6763: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6764:     } else {
                   6765: 	# no prefix at all
                   6766: 	if (defined($part)) { $keyroot='_'.$part; }
                   6767:     }
                   6768:     return $keyroot;
                   6769: }
                   6770: 
1.71      www      6771: # ---------------------------------------------------------------- Get metadata
                   6772: 
1.599     albertel 6773: my %metaentry;
1.71      www      6774: sub metadata {
1.176     www      6775:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6776:     $uri=&declutter($uri);
1.288     albertel 6777:     # if it is a non metadata possible uri return quickly
1.529     albertel 6778:     if (($uri eq '') || 
                   6779: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6780: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6781:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6782: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6783: 	return undef;
1.288     albertel 6784:     }
1.73      www      6785:     my $filename=$uri;
                   6786:     $uri=~s/\.meta$//;
1.172     www      6787: #
                   6788: # Is the metadata already cached?
1.177     www      6789: # Look at timestamp of caching
1.172     www      6790: # Everything is cached by the main uri, libraries are never directly cached
                   6791: #
1.428     albertel 6792:     if (!defined($liburi)) {
1.599     albertel 6793: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6794: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6795:     }
                   6796:     {
1.172     www      6797: #
                   6798: # Is this a recursive call for a library?
                   6799: #
1.599     albertel 6800: #	if (! exists($metacache{$uri})) {
                   6801: #	    $metacache{$uri}={};
                   6802: #	}
1.171     www      6803:         if ($liburi) {
                   6804: 	    $liburi=&declutter($liburi);
                   6805:             $filename=$liburi;
1.401     bowersj2 6806:         } else {
1.599     albertel 6807: 	    &devalidate_cache_new('meta',$uri);
                   6808: 	    undef(%metaentry);
1.401     bowersj2 6809: 	}
1.140     www      6810:         my %metathesekeys=();
1.73      www      6811:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6812: 	my $metastring;
1.768     albertel 6813: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6814: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6815: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6816: 	    $metastring=&getfile($file);
1.489     albertel 6817: 	}
1.208     albertel 6818:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6819:         my $token;
1.140     www      6820:         undef %metathesekeys;
1.71      www      6821:         while ($token=$parser->get_token) {
1.339     albertel 6822: 	    if ($token->[0] eq 'S') {
                   6823: 		if (defined($token->[2]->{'package'})) {
1.172     www      6824: #
                   6825: # This is a package - get package info
                   6826: #
1.339     albertel 6827: 		    my $package=$token->[2]->{'package'};
                   6828: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6829: 		    if (defined($token->[2]->{'id'})) { 
                   6830: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6831: 		    }
1.599     albertel 6832: 		    if ($metaentry{':packages'}) {
                   6833: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6834: 		    } else {
1.599     albertel 6835: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6836: 		    }
1.736     albertel 6837: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6838: 			my $part=$keyroot;
                   6839: 			$part=~s/^\_//;
1.736     albertel 6840: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6841: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6842: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6843: 			    # ignore package.tab specified default values
                   6844:                             # here &package_tab_default() will fetch those
                   6845: 			    if ($subp eq 'default') { next; }
1.736     albertel 6846: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6847: 			    my $unikey;
                   6848: 			    if ($pack =~ /_0$/) {
                   6849: 				$unikey='parameter_0_'.$name;
                   6850: 				$part=0;
                   6851: 			    } else {
                   6852: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6853: 			    }
1.339     albertel 6854: 			    if ($subp eq 'display') {
                   6855: 				$value.=' [Part: '.$part.']';
                   6856: 			    }
1.599     albertel 6857: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6858: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6859: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6860: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6861: 			    }
1.599     albertel 6862: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6863: 				$metaentry{':'.$unikey}=
                   6864: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6865: 			    }
1.339     albertel 6866: 			}
                   6867: 		    }
                   6868: 		} else {
1.172     www      6869: #
                   6870: # This is not a package - some other kind of start tag
1.339     albertel 6871: #
                   6872: 		    my $entry=$token->[1];
                   6873: 		    my $unikey;
                   6874: 		    if ($entry eq 'import') {
                   6875: 			$unikey='';
                   6876: 		    } else {
                   6877: 			$unikey=$entry;
                   6878: 		    }
                   6879: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6880: 
                   6881: 		    if (defined($token->[2]->{'id'})) { 
                   6882: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6883: 		    }
1.175     www      6884: 
1.339     albertel 6885: 		    if ($entry eq 'import') {
1.175     www      6886: #
                   6887: # Importing a library here
1.339     albertel 6888: #
                   6889: 			if ($depthcount<20) {
                   6890: 			    my $location=$parser->get_text('/import');
                   6891: 			    my $dir=$filename;
                   6892: 			    $dir=~s|[^/]*$||;
                   6893: 			    $location=&filelocation($dir,$location);
1.736     albertel 6894: 			    my $metadata = 
                   6895: 				&metadata($uri,'keys', $location,$unikey,
                   6896: 					  $depthcount+1);
                   6897: 			    foreach my $meta (split(',',$metadata)) {
                   6898: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6899: 				$metathesekeys{$meta}=1;
1.339     albertel 6900: 			    }
                   6901: 			}
                   6902: 		    } else { 
                   6903: 			
                   6904: 			if (defined($token->[2]->{'name'})) { 
                   6905: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6906: 			}
                   6907: 			$metathesekeys{$unikey}=1;
1.736     albertel 6908: 			foreach my $param (@{$token->[3]}) {
                   6909: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6910: 				$token->[2]->{$param};
1.339     albertel 6911: 			}
                   6912: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6913: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6914: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6915: 		 # only ws inside the tag, and not in default, so use default
                   6916: 		 # as value
1.599     albertel 6917: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6918: 			} elsif ( $internaltext =~ /\S/ ) {
                   6919: 		  # something interesting inside the tag
                   6920: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6921: 			} else {
1.908     albertel 6922: 		  # no interesting values, don't set a default
1.339     albertel 6923: 			}
1.172     www      6924: # end of not-a-package not-a-library import
1.339     albertel 6925: 		    }
1.172     www      6926: # end of not-a-package start tag
1.339     albertel 6927: 		}
1.172     www      6928: # the next is the end of "start tag"
1.339     albertel 6929: 	    }
                   6930: 	}
1.483     albertel 6931: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6932: 	$extension = lc($extension);
                   6933: 	if ($extension eq 'htm') { $extension='html'; }
                   6934: 
1.737     albertel 6935: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6936: 	    #no specific packages #how's our extension
                   6937: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6938: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6939: 					 \%metathesekeys);
                   6940: 	}
1.883     albertel 6941: 
                   6942: 	if (!exists($metaentry{':packages'})
                   6943: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6944: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6945: 		#no specific packages well let's get default then
                   6946: 		if ($key!~/^default&/) { next; }
1.488     albertel 6947: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6948: 					     \%metathesekeys);
                   6949: 	    }
                   6950: 	}
1.338     www      6951: # are there custom rights to evaluate
1.599     albertel 6952: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6953: 
1.338     www      6954:     #
                   6955:     # Importing a rights file here
1.339     albertel 6956:     #
                   6957: 	    unless ($depthcount) {
1.599     albertel 6958: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6959: 		my $dir=$filename;
                   6960: 		$dir=~s|[^/]*$||;
                   6961: 		$location=&filelocation($dir,$location);
1.736     albertel 6962: 		my $rights_metadata =
                   6963: 		    &metadata($uri,'keys',$location,'_rights',
                   6964: 			      $depthcount+1);
                   6965: 		foreach my $rights (split(',',$rights_metadata)) {
                   6966: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6967: 		    $metathesekeys{$rights}=1;
1.339     albertel 6968: 		}
                   6969: 	    }
                   6970: 	}
1.737     albertel 6971: 	# uniqifiy package listing
                   6972: 	my %seen;
                   6973: 	my @uniq_packages =
                   6974: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6975: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6976: 
                   6977: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6978: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6979: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6980: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6981: # this is the end of "was not already recently cached
1.71      www      6982:     }
1.599     albertel 6983:     return $metaentry{':'.$what};
1.261     albertel 6984: }
                   6985: 
1.488     albertel 6986: sub metadata_create_package_def {
1.483     albertel 6987:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6988:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6989:     if ($subp eq 'default') { next; }
                   6990:     
1.599     albertel 6991:     if (defined($metaentry{':packages'})) {
                   6992: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6993:     } else {
1.599     albertel 6994: 	$metaentry{':packages'}=$package;
1.483     albertel 6995:     }
                   6996:     my $value=$packagetab{$key};
                   6997:     my $unikey;
                   6998:     $unikey='parameter_0_'.$name;
1.599     albertel 6999:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7000:     $$metathesekeys{$unikey}=1;
1.599     albertel 7001:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7002: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7003:     }
1.599     albertel 7004:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7005: 	$metaentry{':'.$unikey}=
                   7006: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7007:     }
                   7008: }
                   7009: 
1.261     albertel 7010: sub metadata_generate_part0 {
                   7011:     my ($metadata,$metacache,$uri) = @_;
                   7012:     my %allnames;
1.737     albertel 7013:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7014: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7015: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7016: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7017: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7018: 	    $allnames{$name}=$part;
                   7019: 	  }
                   7020: 	}
                   7021:     }
                   7022:     foreach my $name (keys(%allnames)) {
                   7023:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7024:       my $key=":parameter_0_$name";
1.261     albertel 7025:       $$metacache{"$key.part"}='0';
                   7026:       $$metacache{"$key.name"}=$name;
1.428     albertel 7027:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7028: 					   $allnames{$name}.'_'.$name.
                   7029: 					   '.type'};
1.428     albertel 7030:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7031: 			     '.display'};
1.644     www      7032:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7033:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7034:       $$metacache{"$key.display"}=$olddis;
                   7035:     }
1.71      www      7036: }
                   7037: 
1.764     albertel 7038: # ------------------------------------------------------ Devalidate title cache
                   7039: 
                   7040: sub devalidate_title_cache {
                   7041:     my ($url)=@_;
                   7042:     if (!$env{'request.course.id'}) { return; }
                   7043:     my $symb=&symbread($url);
                   7044:     if (!$symb) { return; }
                   7045:     my $key=$env{'request.course.id'}."\0".$symb;
                   7046:     &devalidate_cache_new('title',$key);
                   7047: }
                   7048: 
1.301     www      7049: # ------------------------------------------------- Get the title of a resource
                   7050: 
                   7051: sub gettitle {
                   7052:     my $urlsymb=shift;
                   7053:     my $symb=&symbread($urlsymb);
1.534     albertel 7054:     if ($symb) {
1.620     albertel 7055: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7056: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7057: 	if (defined($cached)) { 
                   7058: 	    return $result;
                   7059: 	}
1.534     albertel 7060: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7061: 	my $title='';
1.907     albertel 7062: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7063: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7064: 	} else {
                   7065: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7066: 		    &GDBM_READER(),0640)) {
                   7067: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7068: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7069: 		untie(%bighash);
                   7070: 	    }
1.534     albertel 7071: 	}
                   7072: 	$title=~s/\&colon\;/\:/gs;
                   7073: 	if ($title) {
1.599     albertel 7074: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7075: 	}
                   7076: 	$urlsymb=$url;
                   7077:     }
                   7078:     my $title=&metadata($urlsymb,'title');
                   7079:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7080:     return $title;
1.301     www      7081: }
1.613     albertel 7082: 
1.614     albertel 7083: sub get_slot {
                   7084:     my ($which,$cnum,$cdom)=@_;
                   7085:     if (!$cnum || !$cdom) {
1.790     albertel 7086: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7087: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7088: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7089:     }
1.703     albertel 7090:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7091:     my %slotinfo;
                   7092:     if (exists($remembered{$key})) {
                   7093: 	$slotinfo{$which} = $remembered{$key};
                   7094:     } else {
                   7095: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7096: 	&Apache::lonhomework::showhash(%slotinfo);
                   7097: 	my ($tmp)=keys(%slotinfo);
                   7098: 	if ($tmp=~/^error:/) { return (); }
                   7099: 	$remembered{$key} = $slotinfo{$which};
                   7100:     }
1.616     albertel 7101:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7102: 	return %{$slotinfo{$which}};
                   7103:     }
                   7104:     return $slotinfo{$which};
1.614     albertel 7105: }
1.31      www      7106: # ------------------------------------------------- Update symbolic store links
                   7107: 
                   7108: sub symblist {
                   7109:     my ($mapname,%newhash)=@_;
1.438     www      7110:     $mapname=&deversion(&declutter($mapname));
1.31      www      7111:     my %hash;
1.620     albertel 7112:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7113:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7114:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7115: 	    foreach my $url (keys %newhash) {
                   7116: 		next if ($url eq 'last_known'
                   7117: 			 && $env{'form.no_update_last_known'});
                   7118: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7119: 						    $newhash{$url}->[1],
                   7120: 						    $newhash{$url}->[0]);
1.191     harris41 7121:             }
1.31      www      7122:             if (untie(%hash)) {
                   7123: 		return 'ok';
                   7124:             }
                   7125:         }
                   7126:     }
                   7127:     return 'error';
1.212     www      7128: }
                   7129: 
                   7130: # --------------------------------------------------------------- Verify a symb
                   7131: 
                   7132: sub symbverify {
1.510     www      7133:     my ($symb,$thisurl)=@_;
                   7134:     my $thisfn=$thisurl;
1.439     www      7135:     $thisfn=&declutter($thisfn);
1.215     www      7136: # direct jump to resource in page or to a sequence - will construct own symbs
                   7137:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7138: # check URL part
1.409     www      7139:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7140: 
1.431     www      7141:     unless ($url eq $thisfn) { return 0; }
1.213     www      7142: 
1.216     www      7143:     $symb=&symbclean($symb);
1.510     www      7144:     $thisurl=&deversion($thisurl);
1.439     www      7145:     $thisfn=&deversion($thisfn);
1.213     www      7146: 
                   7147:     my %bighash;
                   7148:     my $okay=0;
1.431     www      7149: 
1.620     albertel 7150:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7151:                             &GDBM_READER(),0640)) {
1.510     www      7152:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7153:         unless ($ids) { 
1.510     www      7154:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7155:         }
                   7156:         if ($ids) {
                   7157: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7158: 	    foreach my $id (split(/\,/,$ids)) {
                   7159: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7160:                if (
                   7161:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7162:    eq $symb) { 
1.620     albertel 7163: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7164: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7165: 		       $okay=1; 
                   7166: 		   }
                   7167: 	       }
1.216     www      7168: 	   }
                   7169:         }
1.213     www      7170: 	untie(%bighash);
                   7171:     }
                   7172:     return $okay;
1.31      www      7173: }
                   7174: 
1.210     www      7175: # --------------------------------------------------------------- Clean-up symb
                   7176: 
                   7177: sub symbclean {
                   7178:     my $symb=shift;
1.568     albertel 7179:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7180: # remove version from map
                   7181:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7182: 
1.210     www      7183: # remove version from URL
                   7184:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7185: 
1.507     www      7186: # remove wrapper
                   7187: 
1.510     www      7188:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7189:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7190:     return $symb;
1.409     www      7191: }
                   7192: 
                   7193: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7194: 
                   7195: sub encode_symb {
                   7196:     my ($map,$resid,$url)=@_;
                   7197:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7198: }
1.409     www      7199: 
                   7200: sub decode_symb {
1.568     albertel 7201:     my $symb=shift;
                   7202:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7203:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7204:     return (&fixversion($map),$resid,&fixversion($url));
                   7205: }
                   7206: 
                   7207: sub fixversion {
                   7208:     my $fn=shift;
1.609     banghart 7209:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7210:     my %bighash;
                   7211:     my $uri=&clutter($fn);
1.620     albertel 7212:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7213: # is this cached?
1.599     albertel 7214:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7215:     if (defined($cached)) { return $result; }
                   7216: # unfortunately not cached, or expired
1.620     albertel 7217:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7218: 	    &GDBM_READER(),0640)) {
                   7219:  	if ($bighash{'version_'.$uri}) {
                   7220:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7221:  	    unless (($version eq 'mostrecent') || 
                   7222: 		    ($version==&getversion($uri))) {
1.440     www      7223:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7224:  	    }
                   7225:  	}
                   7226:  	untie %bighash;
1.413     www      7227:     }
1.599     albertel 7228:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7229: }
                   7230: 
                   7231: sub deversion {
                   7232:     my $url=shift;
                   7233:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7234:     return $url;
1.210     www      7235: }
                   7236: 
1.31      www      7237: # ------------------------------------------------------ Return symb list entry
                   7238: 
                   7239: sub symbread {
1.249     www      7240:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7241:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7242:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7243: # no filename provided? try from environment
1.44      www      7244:     unless ($thisfn) {
1.620     albertel 7245:         if ($env{'request.symb'}) {
                   7246: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7247: 	}
1.620     albertel 7248: 	$thisfn=$env{'request.filename'};
1.44      www      7249:     }
1.569     albertel 7250:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7251: # is that filename actually a symb? Verify, clean, and return
                   7252:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7253: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7254: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7255: 	}
1.242     www      7256:     }
1.44      www      7257:     $thisfn=declutter($thisfn);
1.31      www      7258:     my %hash;
1.37      www      7259:     my %bighash;
                   7260:     my $syval='';
1.620     albertel 7261:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7262:         my $targetfn = $thisfn;
1.609     banghart 7263:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7264:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7265:         }
1.687     albertel 7266: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7267: 	    $targetfn=$1;
                   7268: 	}
1.620     albertel 7269:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7270:                       &GDBM_READER(),0640)) {
1.481     raeburn  7271: 	    $syval=$hash{$targetfn};
1.37      www      7272:             untie(%hash);
                   7273:         }
                   7274: # ---------------------------------------------------------- There was an entry
                   7275:         if ($syval) {
1.601     albertel 7276: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7277: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7278: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7279: 		    #return $env{$cache_str}='';
1.601     albertel 7280: 		#}    
                   7281: 		#$syval.=$1;
                   7282: 	    #}
1.37      www      7283:         } else {
                   7284: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7285:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7286:                             &GDBM_READER(),0640)) {
1.37      www      7287: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7288:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7289:               unless ($ids) { 
                   7290:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7291:               }
                   7292:               unless ($ids) {
                   7293: # alias?
                   7294: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7295:               }
1.37      www      7296:               if ($ids) {
                   7297: # ------------------------------------------------------------------- Has ID(s)
                   7298:                  my @possibilities=split(/\,/,$ids);
1.39      www      7299:                  if ($#possibilities==0) {
                   7300: # ----------------------------------------------- There is only one possibility
1.37      www      7301: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7302: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7303: 						    $resid,$thisfn);
1.249     www      7304:                  } elsif (!$donotrecurse) {
1.39      www      7305: # ------------------------------------------ There is more than one possibility
                   7306:                      my $realpossible=0;
1.800     albertel 7307:                      foreach my $id (@possibilities) {
                   7308: 			 my $file=$bighash{'src_'.$id};
1.39      www      7309:                          if (&allowed('bre',$file)) {
1.800     albertel 7310:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7311:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7312: 				$realpossible++;
1.626     albertel 7313:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7314: 						    $resid,$thisfn);
1.39      www      7315:                             }
                   7316: 			 }
1.191     harris41 7317:                      }
1.39      www      7318: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7319:                  } else {
                   7320:                      $syval='';
1.37      www      7321:                  }
                   7322: 	      }
                   7323:               untie(%bighash)
1.481     raeburn  7324:            }
1.31      www      7325:         }
1.62      www      7326:         if ($syval) {
1.620     albertel 7327: 	    return $env{$cache_str}=$syval;
1.62      www      7328:         }
1.31      www      7329:     }
1.44      www      7330:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7331:     return $env{$cache_str}='';
1.31      www      7332: }
                   7333: 
                   7334: # ---------------------------------------------------------- Return random seed
                   7335: 
1.32      www      7336: sub numval {
                   7337:     my $txt=shift;
                   7338:     $txt=~tr/A-J/0-9/;
                   7339:     $txt=~tr/a-j/0-9/;
                   7340:     $txt=~tr/K-T/0-9/;
                   7341:     $txt=~tr/k-t/0-9/;
                   7342:     $txt=~tr/U-Z/0-5/;
                   7343:     $txt=~tr/u-z/0-5/;
                   7344:     $txt=~s/\D//g;
1.564     albertel 7345:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7346:     return int($txt);
1.368     albertel 7347: }
                   7348: 
1.484     albertel 7349: sub numval2 {
                   7350:     my $txt=shift;
                   7351:     $txt=~tr/A-J/0-9/;
                   7352:     $txt=~tr/a-j/0-9/;
                   7353:     $txt=~tr/K-T/0-9/;
                   7354:     $txt=~tr/k-t/0-9/;
                   7355:     $txt=~tr/U-Z/0-5/;
                   7356:     $txt=~tr/u-z/0-5/;
                   7357:     $txt=~s/\D//g;
                   7358:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7359:     my $total;
                   7360:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7361:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7362:     return int($total);
                   7363: }
                   7364: 
1.575     albertel 7365: sub numval3 {
                   7366:     use integer;
                   7367:     my $txt=shift;
                   7368:     $txt=~tr/A-J/0-9/;
                   7369:     $txt=~tr/a-j/0-9/;
                   7370:     $txt=~tr/K-T/0-9/;
                   7371:     $txt=~tr/k-t/0-9/;
                   7372:     $txt=~tr/U-Z/0-5/;
                   7373:     $txt=~tr/u-z/0-5/;
                   7374:     $txt=~s/\D//g;
                   7375:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7376:     my $total;
                   7377:     foreach my $val (@txts) { $total+=$val; }
                   7378:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7379:     return $total;
                   7380: }
                   7381: 
1.675     albertel 7382: sub digest {
                   7383:     my ($data)=@_;
                   7384:     my $digest=&Digest::MD5::md5($data);
                   7385:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7386:     my ($e,$f);
                   7387:     {
                   7388:         use integer;
                   7389:         $e=($a+$b);
                   7390:         $f=($c+$d);
                   7391:         if ($_64bit) {
                   7392:             $e=(($e<<32)>>32);
                   7393:             $f=(($f<<32)>>32);
                   7394:         }
                   7395:     }
                   7396:     if (wantarray) {
                   7397: 	return ($e,$f);
                   7398:     } else {
                   7399: 	my $g;
                   7400: 	{
                   7401: 	    use integer;
                   7402: 	    $g=($e+$f);
                   7403: 	    if ($_64bit) {
                   7404: 		$g=(($g<<32)>>32);
                   7405: 	    }
                   7406: 	}
                   7407: 	return $g;
                   7408:     }
                   7409: }
                   7410: 
1.368     albertel 7411: sub latest_rnd_algorithm_id {
1.675     albertel 7412:     return '64bit5';
1.366     albertel 7413: }
1.32      www      7414: 
1.503     albertel 7415: sub get_rand_alg {
                   7416:     my ($courseid)=@_;
1.790     albertel 7417:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7418:     if ($courseid) {
1.620     albertel 7419: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7420:     }
                   7421:     return &latest_rnd_algorithm_id();
                   7422: }
                   7423: 
1.562     albertel 7424: sub validCODE {
                   7425:     my ($CODE)=@_;
                   7426:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7427:     return 0;
                   7428: }
                   7429: 
1.491     albertel 7430: sub getCODE {
1.620     albertel 7431:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7432:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7433: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7434: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7435: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7436:     }
                   7437:     return undef;
                   7438: }
                   7439: 
1.31      www      7440: sub rndseed {
1.155     albertel 7441:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7442:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7443:     if (!defined($symb)) {
1.366     albertel 7444: 	unless ($symb=$wsymb) { return time; }
                   7445:     }
                   7446:     if (!$courseid) { $courseid=$wcourseid; }
                   7447:     if (!$domain) { $domain=$wdomain; }
                   7448:     if (!$username) { $username=$wusername }
1.503     albertel 7449:     my $which=&get_rand_alg();
1.803     albertel 7450: 
1.491     albertel 7451:     if (defined(&getCODE())) {
1.675     albertel 7452: 	if ($which eq '64bit5') {
                   7453: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7454: 	} elsif ($which eq '64bit4') {
1.575     albertel 7455: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7456: 	} else {
                   7457: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7458: 	}
1.675     albertel 7459:     } elsif ($which eq '64bit5') {
                   7460: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7461:     } elsif ($which eq '64bit4') {
                   7462: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7463:     } elsif ($which eq '64bit3') {
                   7464: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7465:     } elsif ($which eq '64bit2') {
                   7466: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7467:     } elsif ($which eq '64bit') {
                   7468: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7469:     }
                   7470:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7471: }
                   7472: 
                   7473: sub rndseed_32bit {
                   7474:     my ($symb,$courseid,$domain,$username)=@_;
                   7475:     {
                   7476: 	use integer;
                   7477: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7478: 	my $symbseed=numval($symb) << 22;
                   7479: 	my $namechck=unpack("%32C*",$username) << 17;
                   7480: 	my $nameseed=numval($username) << 12;
                   7481: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7482: 	my $courseseed=unpack("%32C*",$courseid);
                   7483: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7484: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7485: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7486: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7487: 	return $num;
                   7488:     }
                   7489: }
                   7490: 
                   7491: sub rndseed_64bit {
                   7492:     my ($symb,$courseid,$domain,$username)=@_;
                   7493:     {
                   7494: 	use integer;
                   7495: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7496: 	my $symbseed=numval($symb) << 10;
                   7497: 	my $namechck=unpack("%32S*",$username);
                   7498: 	
                   7499: 	my $nameseed=numval($username) << 21;
                   7500: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7501: 	my $courseseed=unpack("%32S*",$courseid);
                   7502: 	
                   7503: 	my $num1=$symbchck+$symbseed+$namechck;
                   7504: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7505: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7506: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7507: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7508: 	return "$num1,$num2";
1.155     albertel 7509:     }
1.366     albertel 7510: }
                   7511: 
1.443     albertel 7512: sub rndseed_64bit2 {
                   7513:     my ($symb,$courseid,$domain,$username)=@_;
                   7514:     {
                   7515: 	use integer;
                   7516: 	# strings need to be an even # of cahracters long, it it is odd the
                   7517:         # last characters gets thrown away
                   7518: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7519: 	my $symbseed=numval($symb) << 10;
                   7520: 	my $namechck=unpack("%32S*",$username.' ');
                   7521: 	
                   7522: 	my $nameseed=numval($username) << 21;
1.501     albertel 7523: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7524: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7525: 	
                   7526: 	my $num1=$symbchck+$symbseed+$namechck;
                   7527: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7528: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7529: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7530: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7531: 	return "$num1,$num2";
                   7532:     }
                   7533: }
                   7534: 
                   7535: sub rndseed_64bit3 {
                   7536:     my ($symb,$courseid,$domain,$username)=@_;
                   7537:     {
                   7538: 	use integer;
                   7539: 	# strings need to be an even # of cahracters long, it it is odd the
                   7540:         # last characters gets thrown away
                   7541: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7542: 	my $symbseed=numval2($symb) << 10;
                   7543: 	my $namechck=unpack("%32S*",$username.' ');
                   7544: 	
                   7545: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7546: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7547: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7548: 	
                   7549: 	my $num1=$symbchck+$symbseed+$namechck;
                   7550: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7551: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7552: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7553: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7554: 	
1.503     albertel 7555: 	return "$num1:$num2";
1.443     albertel 7556:     }
                   7557: }
                   7558: 
1.575     albertel 7559: sub rndseed_64bit4 {
                   7560:     my ($symb,$courseid,$domain,$username)=@_;
                   7561:     {
                   7562: 	use integer;
                   7563: 	# strings need to be an even # of cahracters long, it it is odd the
                   7564:         # last characters gets thrown away
                   7565: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7566: 	my $symbseed=numval3($symb) << 10;
                   7567: 	my $namechck=unpack("%32S*",$username.' ');
                   7568: 	
                   7569: 	my $nameseed=numval3($username) << 21;
                   7570: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7571: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7572: 	
                   7573: 	my $num1=$symbchck+$symbseed+$namechck;
                   7574: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7575: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7576: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7577: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7578: 	
                   7579: 	return "$num1:$num2";
                   7580:     }
                   7581: }
                   7582: 
1.675     albertel 7583: sub rndseed_64bit5 {
                   7584:     my ($symb,$courseid,$domain,$username)=@_;
                   7585:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7586:     return "$num1:$num2";
                   7587: }
                   7588: 
1.366     albertel 7589: sub rndseed_CODE_64bit {
                   7590:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7591:     {
1.366     albertel 7592: 	use integer;
1.443     albertel 7593: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7594: 	my $symbseed=numval2($symb);
1.491     albertel 7595: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7596: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7597: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7598: 	my $num1=$symbseed+$CODEchck;
                   7599: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7600: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7601: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7602: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7603: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7604: 	return "$num1:$num2";
1.366     albertel 7605:     }
                   7606: }
                   7607: 
1.575     albertel 7608: sub rndseed_CODE_64bit4 {
                   7609:     my ($symb,$courseid,$domain,$username)=@_;
                   7610:     {
                   7611: 	use integer;
                   7612: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7613: 	my $symbseed=numval3($symb);
                   7614: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7615: 	my $CODEseed=numval3(&getCODE());
                   7616: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7617: 	my $num1=$symbseed+$CODEchck;
                   7618: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7619: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7620: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7621: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7622: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7623: 	return "$num1:$num2";
                   7624:     }
                   7625: }
                   7626: 
1.675     albertel 7627: sub rndseed_CODE_64bit5 {
                   7628:     my ($symb,$courseid,$domain,$username)=@_;
                   7629:     my $code = &getCODE();
                   7630:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7631:     return "$num1:$num2";
                   7632: }
                   7633: 
1.366     albertel 7634: sub setup_random_from_rndseed {
                   7635:     my ($rndseed)=@_;
1.503     albertel 7636:     if ($rndseed =~/([,:])/) {
                   7637: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7638: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7639:     } else {
                   7640: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7641:     }
1.36      albertel 7642: }
                   7643: 
1.474     albertel 7644: sub latest_receipt_algorithm_id {
1.835     albertel 7645:     return 'receipt3';
1.474     albertel 7646: }
                   7647: 
1.480     www      7648: sub recunique {
                   7649:     my $fucourseid=shift;
                   7650:     my $unique;
1.835     albertel 7651:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7652: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7653: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7654:     } else {
                   7655: 	$unique=$perlvar{'lonReceipt'};
                   7656:     }
                   7657:     return unpack("%32C*",$unique);
                   7658: }
                   7659: 
                   7660: sub recprefix {
                   7661:     my $fucourseid=shift;
                   7662:     my $prefix;
1.835     albertel 7663:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7664: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7665: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7666:     } else {
                   7667: 	$prefix=$perlvar{'lonHostID'};
                   7668:     }
                   7669:     return unpack("%32C*",$prefix);
                   7670: }
                   7671: 
1.76      www      7672: sub ireceipt {
1.474     albertel 7673:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7674: 
                   7675:     my $return =&recprefix($fucourseid).'-';
                   7676: 
                   7677:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7678: 	$env{'request.state'} eq 'construct') {
                   7679: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7680: 	return $return;
                   7681:     }
                   7682: 
1.76      www      7683:     my $cuname=unpack("%32C*",$funame);
                   7684:     my $cudom=unpack("%32C*",$fudom);
                   7685:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7686:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7687:     my $cunique=&recunique($fucourseid);
1.474     albertel 7688:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7689:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7690: 
1.790     albertel 7691: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7692: 			       
                   7693: 	$return.= ($cunique%$cuname+
                   7694: 		   $cunique%$cudom+
                   7695: 		   $cusymb%$cuname+
                   7696: 		   $cusymb%$cudom+
                   7697: 		   $cucourseid%$cuname+
                   7698: 		   $cucourseid%$cudom+
                   7699: 		   $cpart%$cuname+
                   7700: 		   $cpart%$cudom);
                   7701:     } else {
                   7702: 	$return.= ($cunique%$cuname+
                   7703: 		   $cunique%$cudom+
                   7704: 		   $cusymb%$cuname+
                   7705: 		   $cusymb%$cudom+
                   7706: 		   $cucourseid%$cuname+
                   7707: 		   $cucourseid%$cudom);
                   7708:     }
                   7709:     return $return;
1.76      www      7710: }
                   7711: 
                   7712: sub receipt {
1.474     albertel 7713:     my ($part)=@_;
1.790     albertel 7714:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7715:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7716: }
1.260     ng       7717: 
1.790     albertel 7718: sub whichuser {
                   7719:     my ($passedsymb)=@_;
                   7720:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7721:     if (defined($env{'form.grade_symb'})) {
                   7722: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7723: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7724: 	if (!$allowed &&
                   7725: 	    exists($env{'request.course.sec'}) &&
                   7726: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7727: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7728: 			      '/'.$env{'request.course.sec'});
                   7729: 	}
                   7730: 	if ($allowed) {
                   7731: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7732: 	    $courseid=$tmp_courseid;
                   7733: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7734: 	    ($name)=&get_env_multiple('form.grade_username');
                   7735: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7736: 	}
                   7737:     }
                   7738:     if (!$passedsymb) {
                   7739: 	$symb=&symbread();
                   7740:     } else {
                   7741: 	$symb=$passedsymb;
                   7742:     }
                   7743:     $courseid=$env{'request.course.id'};
                   7744:     $domain=$env{'user.domain'};
                   7745:     $name=$env{'user.name'};
                   7746:     if ($name eq 'public' && $domain eq 'public') {
                   7747: 	if (!defined($env{'form.username'})) {
                   7748: 	    $env{'form.username'}.=time.rand(10000000);
                   7749: 	}
                   7750: 	$name.=$env{'form.username'};
                   7751:     }
                   7752:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7753: 
                   7754: }
                   7755: 
1.36      albertel 7756: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7757: # returns either the contents of the file or 
                   7758: # -1 if the file doesn't exist
1.481     raeburn  7759: #
                   7760: # if the target is a file that was uploaded via DOCS, 
                   7761: # a check will be made to see if a current copy exists on the local server,
                   7762: # if it does this will be served, otherwise a copy will be retrieved from
                   7763: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7764: # the local server.   
1.472     albertel 7765: 
1.36      albertel 7766: sub getfile {
1.538     albertel 7767:     my ($file) = @_;
1.609     banghart 7768:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7769:     &repcopy($file);
                   7770:     return &readfile($file);
                   7771: }
                   7772: 
                   7773: sub repcopy_userfile {
                   7774:     my ($file)=@_;
1.609     banghart 7775:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7776:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7777:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7778: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7779:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7780:     if (-e "$file") {
1.828     www      7781: # we already have a local copy, check it out
1.538     albertel 7782: 	my @fileinfo = stat($file);
1.828     www      7783: 	my $rtncode;
                   7784: 	my $info;
1.538     albertel 7785: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7786: 	if ($lwpresp ne 'ok') {
1.828     www      7787: # there is no such file anymore, even though we had a local copy
1.482     albertel 7788: 	    if ($rtncode eq '404') {
1.538     albertel 7789: 		unlink($file);
1.482     albertel 7790: 	    }
                   7791: 	    return -1;
                   7792: 	}
                   7793: 	if ($info < $fileinfo[9]) {
1.828     www      7794: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7795: 	    return 'ok';
1.828     www      7796: 	} else {
                   7797: # the file is outdated, get rid of it
                   7798: 	    unlink($file);
1.482     albertel 7799: 	}
1.828     www      7800:     }
                   7801: # one way or the other, at this point, we don't have the file
                   7802: # construct the correct path for the file
                   7803:     my @parts = ($cdom,$cnum); 
                   7804:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7805: 	push @parts, split(/\//,$1);
                   7806:     }
                   7807:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7808:     foreach my $part (@parts) {
                   7809: 	$path .= '/'.$part;
                   7810: 	if (!-e $path) {
                   7811: 	    mkdir($path,0770);
1.482     albertel 7812: 	}
                   7813:     }
1.828     www      7814: # now the path exists for sure
                   7815: # get a user agent
                   7816:     my $ua=new LWP::UserAgent;
                   7817:     my $transferfile=$file.'.in.transfer';
                   7818: # FIXME: this should flock
                   7819:     if (-e $transferfile) { return 'ok'; }
                   7820:     my $request;
                   7821:     $uri=~s/^\///;
1.838     albertel 7822:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7823:     my $response=$ua->request($request,$transferfile);
                   7824: # did it work?
                   7825:     if ($response->is_error()) {
                   7826: 	unlink($transferfile);
                   7827: 	&logthis("Userfile repcopy failed for $uri");
                   7828: 	return -1;
                   7829:     }
                   7830: # worked, rename the transfer file
                   7831:     rename($transferfile,$file);
1.607     raeburn  7832:     return 'ok';
1.481     raeburn  7833: }
                   7834: 
1.517     albertel 7835: sub tokenwrapper {
                   7836:     my $uri=shift;
1.552     albertel 7837:     $uri=~s|^http\://([^/]+)||;
                   7838:     $uri=~s|^/||;
1.620     albertel 7839:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7840:     my $token=$1;
1.552     albertel 7841:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7842:     if ($udom && $uname && $file) {
                   7843: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7844:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7845:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7846:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7847:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7848:     } else {
                   7849:         return '/adm/notfound.html';
                   7850:     }
                   7851: }
                   7852: 
1.828     www      7853: # call with reqtype HEAD: get last modification time
                   7854: # call with reqtype GET: get the file contents
                   7855: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7856: #
1.481     raeburn  7857: sub getuploaded {
                   7858:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7859:     $uri=~s/^\///;
1.838     albertel 7860:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7861:     my $ua=new LWP::UserAgent;
                   7862:     my $request=new HTTP::Request($reqtype,$uri);
                   7863:     my $response=$ua->request($request);
                   7864:     $$rtncode = $response->code;
1.482     albertel 7865:     if (! $response->is_success()) {
                   7866: 	return 'failed';
                   7867:     }      
                   7868:     if ($reqtype eq 'HEAD') {
1.486     www      7869: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7870:     } elsif ($reqtype eq 'GET') {
                   7871: 	$$info = $response->content;
1.472     albertel 7872:     }
1.482     albertel 7873:     return 'ok';
1.36      albertel 7874: }
                   7875: 
1.481     raeburn  7876: sub readfile {
                   7877:     my $file = shift;
                   7878:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7879:     my $fh;
                   7880:     open($fh,"<$file");
                   7881:     my $a='';
1.800     albertel 7882:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7883:     return $a;
                   7884: }
                   7885: 
1.36      albertel 7886: sub filelocation {
1.590     banghart 7887:     my ($dir,$file) = @_;
                   7888:     my $location;
                   7889:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7890: 
                   7891:     if ($file =~ m-^/adm/-) {
                   7892: 	$file=~s-^/adm/wrapper/-/-;
                   7893: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7894:     }
1.882     albertel 7895: 
1.590     banghart 7896:     if ($file=~m:^/~:) { # is a contruction space reference
                   7897:         $location = $file;
                   7898:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7899:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7900: 	# is a correct contruction space reference
                   7901:         $location = $file;
1.609     banghart 7902:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7903:         my ($udom,$uname,$filename)=
1.811     albertel 7904:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7905:         my $home=&homeserver($uname,$udom);
                   7906:         my $is_me=0;
                   7907:         my @ids=&current_machine_ids();
                   7908:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7909:         if ($is_me) {
1.740     www      7910:   	    $location=&propath($udom,$uname).
1.590     banghart 7911:   	      '/userfiles/'.$filename;
                   7912:         } else {
                   7913:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7914:   	      $udom.'/'.$uname.'/'.$filename;
                   7915:         }
1.882     albertel 7916:     } elsif ($file =~ m-^/adm/-) {
                   7917: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7918:     } else {
                   7919:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7920:         $file=~s:^/res/:/:;
                   7921:         if ( !( $file =~ m:^/:) ) {
                   7922:             $location = $dir. '/'.$file;
                   7923:         } else {
                   7924:             $location = '/home/httpd/html/res'.$file;
                   7925:         }
1.59      albertel 7926:     }
1.590     banghart 7927:     $location=~s://+:/:g; # remove duplicate /
                   7928:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7929:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7930:     return $location;
1.46      www      7931: }
1.36      albertel 7932: 
1.46      www      7933: sub hreflocation {
                   7934:     my ($dir,$file)=@_;
1.460     albertel 7935:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7936: 	$file=filelocation($dir,$file);
1.700     albertel 7937:     } elsif ($file=~m-^/adm/-) {
                   7938: 	$file=~s-^/adm/wrapper/-/-;
                   7939: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7940:     }
                   7941:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7942: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7943:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7944: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7945:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7946: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7947: 	    -/uploaded/$1/$2/-x;
1.46      www      7948:     }
1.913     albertel 7949:     if ($file=~ m{^/userfiles/}) {
                   7950: 	$file =~ s{^/userfiles/}{/uploaded/};
                   7951:     }
1.462     albertel 7952:     return $file;
1.465     albertel 7953: }
                   7954: 
                   7955: sub current_machine_domains {
1.853     albertel 7956:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7957: }
                   7958: 
                   7959: sub machine_domains {
                   7960:     my ($hostname) = @_;
1.465     albertel 7961:     my @domains;
1.838     albertel 7962:     my %hostname = &all_hostnames();
1.465     albertel 7963:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7964: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7965: 	if ($hostname eq $name) {
1.844     albertel 7966: 	    push(@domains,&host_domain($id));
1.465     albertel 7967: 	}
                   7968:     }
                   7969:     return @domains;
                   7970: }
                   7971: 
                   7972: sub current_machine_ids {
1.853     albertel 7973:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7974: }
                   7975: 
                   7976: sub machine_ids {
                   7977:     my ($hostname) = @_;
                   7978:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7979:     my @ids;
1.888     albertel 7980:     my %name_to_host = &all_names();
1.889     albertel 7981:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7982: 	return @{ $name_to_host{$hostname} };
                   7983:     }
                   7984:     return;
1.31      www      7985: }
                   7986: 
1.824     raeburn  7987: sub additional_machine_domains {
                   7988:     my @domains;
                   7989:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7990:     while( my $line = <$fh>) {
                   7991:         $line =~ s/\s//g;
                   7992:         push(@domains,$line);
                   7993:     }
                   7994:     return @domains;
                   7995: }
                   7996: 
                   7997: sub default_login_domain {
                   7998:     my $domain = $perlvar{'lonDefDomain'};
                   7999:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8000:     foreach my $posdom (&current_machine_domains(),
                   8001:                         &additional_machine_domains()) {
                   8002:         if (lc($posdom) eq lc($testdomain)) {
                   8003:             $domain=$posdom;
                   8004:             last;
                   8005:         }
                   8006:     }
                   8007:     return $domain;
                   8008: }
                   8009: 
1.31      www      8010: # ------------------------------------------------------------- Declutters URLs
                   8011: 
                   8012: sub declutter {
                   8013:     my $thisfn=shift;
1.569     albertel 8014:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8015:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8016:     $thisfn=~s/^\///;
1.697     albertel 8017:     $thisfn=~s|^adm/wrapper/||;
                   8018:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8019:     $thisfn=~s/^res\///;
1.235     www      8020:     $thisfn=~s/\?.+$//;
1.268     www      8021:     return $thisfn;
                   8022: }
                   8023: 
                   8024: # ------------------------------------------------------------- Clutter up URLs
                   8025: 
                   8026: sub clutter {
                   8027:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8028:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8029: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8030:        $thisfn='/res'.$thisfn; 
                   8031:     }
1.694     albertel 8032:     if ($thisfn !~m|/adm|) {
1.695     albertel 8033: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8034: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8035: 	} else {
                   8036: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8037: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8038: 	    if ($embstyle eq 'ssi'
                   8039: 		|| ($embstyle eq 'hdn')
                   8040: 		|| ($embstyle eq 'rat')
                   8041: 		|| ($embstyle eq 'prv')
                   8042: 		|| ($embstyle eq 'ign')) {
                   8043: 		#do nothing with these
                   8044: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8045: 		|| ($embstyle eq 'emb')
                   8046: 		|| ($embstyle eq 'wrp')) {
                   8047: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8048: 	    } elsif ($embstyle eq 'unk'
                   8049: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8050: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8051: 	    } else {
1.718     www      8052: #		&logthis("Got a blank emb style");
1.695     albertel 8053: 	    }
1.694     albertel 8054: 	}
                   8055:     }
1.31      www      8056:     return $thisfn;
1.12      www      8057: }
                   8058: 
1.787     albertel 8059: sub clutter_with_no_wrapper {
                   8060:     my $uri = &clutter(shift);
                   8061:     if ($uri =~ m-^/adm/-) {
                   8062: 	$uri =~ s-^/adm/wrapper/-/-;
                   8063: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8064:     }
                   8065:     return $uri;
                   8066: }
                   8067: 
1.557     albertel 8068: sub freeze_escape {
                   8069:     my ($value)=@_;
                   8070:     if (ref($value)) {
                   8071: 	$value=&nfreeze($value);
                   8072: 	return '__FROZEN__'.&escape($value);
                   8073:     }
                   8074:     return &escape($value);
                   8075: }
                   8076: 
1.11      www      8077: 
1.557     albertel 8078: sub thaw_unescape {
                   8079:     my ($value)=@_;
                   8080:     if ($value =~ /^__FROZEN__/) {
                   8081: 	substr($value,0,10,undef);
                   8082: 	$value=&unescape($value);
                   8083: 	return &thaw($value);
                   8084:     }
                   8085:     return &unescape($value);
                   8086: }
                   8087: 
1.436     albertel 8088: sub correct_line_ends {
                   8089:     my ($result)=@_;
                   8090:     $$result =~s/\r\n/\n/mg;
                   8091:     $$result =~s/\r/\n/mg;
1.415     albertel 8092: }
1.1       albertel 8093: # ================================================================ Main Program
                   8094: 
1.184     www      8095: sub goodbye {
1.204     albertel 8096:    &logthis("Starting Shut down");
1.443     albertel 8097: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8098:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8099: #converted
1.599     albertel 8100: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8101:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8102: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8103: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8104: #1.1 only
1.870     albertel 8105: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8106: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8107: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8108: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8109:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8110:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8111:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8112:    &flushcourselogs();
                   8113:    &logthis("Shutting down");
                   8114: }
                   8115: 
1.852     albertel 8116: sub get_dns {
1.869     albertel 8117:     my ($url,$func,$ignore_cache) = @_;
                   8118:     if (!$ignore_cache) {
                   8119: 	my ($content,$cached)=
                   8120: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8121: 	if ($cached) {
                   8122: 	    &$func($content);
                   8123: 	    return;
                   8124: 	}
                   8125:     }
                   8126: 
                   8127:     my %alldns;
1.852     albertel 8128:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8129:     foreach my $dns (<$config>) {
                   8130: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8131: 	$alldns{$1} = 1;
                   8132:     }
                   8133:     while (%alldns) {
                   8134: 	my ($dns) = keys(%alldns);
                   8135: 	delete($alldns{$dns});
1.852     albertel 8136: 	my $ua=new LWP::UserAgent;
                   8137: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8138: 	my $response=$ua->request($request);
                   8139: 	next if ($response->is_error());
                   8140: 	my @content = split("\n",$response->content);
1.869     albertel 8141: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8142: 	&$func(\@content);
1.869     albertel 8143: 	return;
1.852     albertel 8144:     }
                   8145:     close($config);
1.871     albertel 8146:     my $which = (split('/',$url))[3];
                   8147:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8148:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8149:     my @content = <$config>;
                   8150:     &$func(\@content);
                   8151:     return;
1.852     albertel 8152: }
1.327     albertel 8153: # ------------------------------------------------------------ Read domain file
                   8154: {
1.852     albertel 8155:     my $loaded;
1.846     albertel 8156:     my %domain;
                   8157: 
1.852     albertel 8158:     sub parse_domain_tab {
                   8159: 	my ($lines) = @_;
                   8160: 	foreach my $line (@$lines) {
                   8161: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8162: 
1.846     albertel 8163: 	    chomp($line);
1.852     albertel 8164: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8165: 	    my %this_domain;
                   8166: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8167: 			       'lang_def', 'city', 'longi', 'lati',
                   8168: 			       'primary') {
                   8169: 		$this_domain{$field} = shift(@elements);
                   8170: 	    }
                   8171: 	    $domain{$name} = \%this_domain;
1.852     albertel 8172: 	}
                   8173:     }
1.864     albertel 8174: 
                   8175:     sub reset_domain_info {
                   8176: 	undef($loaded);
                   8177: 	undef(%domain);
                   8178:     }
                   8179: 
1.852     albertel 8180:     sub load_domain_tab {
1.869     albertel 8181: 	my ($ignore_cache) = @_;
                   8182: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8183: 	my $fh;
                   8184: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8185: 	    my @lines = <$fh>;
                   8186: 	    &parse_domain_tab(\@lines);
1.448     albertel 8187: 	}
1.852     albertel 8188: 	close($fh);
                   8189: 	$loaded = 1;
1.327     albertel 8190:     }
1.846     albertel 8191: 
                   8192:     sub domain {
1.852     albertel 8193: 	&load_domain_tab() if (!$loaded);
                   8194: 
1.846     albertel 8195: 	my ($name,$what) = @_;
                   8196: 	return if ( !exists($domain{$name}) );
                   8197: 
                   8198: 	if (!$what) {
                   8199: 	    return $domain{$name}{'description'};
                   8200: 	}
                   8201: 	return $domain{$name}{$what};
                   8202:     }
1.327     albertel 8203: }
                   8204: 
                   8205: 
1.1       albertel 8206: # ------------------------------------------------------------- Read hosts file
                   8207: {
1.838     albertel 8208:     my %hostname;
1.844     albertel 8209:     my %hostdom;
1.845     albertel 8210:     my %libserv;
1.852     albertel 8211:     my $loaded;
1.888     albertel 8212:     my %name_to_host;
1.852     albertel 8213: 
                   8214:     sub parse_hosts_tab {
                   8215: 	my ($file) = @_;
                   8216: 	foreach my $configline (@$file) {
                   8217: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8218: 	    next if ($configline =~ /^\^/);
                   8219: 	    chomp($configline);
                   8220: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8221: 	    $name=~s/\s//g;
                   8222: 	    if ($id && $domain && $role && $name) {
                   8223: 		$hostname{$id}=$name;
1.888     albertel 8224: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8225: 		$hostdom{$id}=$domain;
                   8226: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8227: 	    }
                   8228: 	}
                   8229:     }
1.864     albertel 8230:     
                   8231:     sub reset_hosts_info {
1.897     albertel 8232: 	&purge_remembered();
1.864     albertel 8233: 	&reset_domain_info();
                   8234: 	&reset_hosts_ip_info();
1.892     albertel 8235: 	undef(%name_to_host);
1.864     albertel 8236: 	undef(%hostname);
                   8237: 	undef(%hostdom);
                   8238: 	undef(%libserv);
                   8239: 	undef($loaded);
                   8240:     }
1.1       albertel 8241: 
1.852     albertel 8242:     sub load_hosts_tab {
1.869     albertel 8243: 	my ($ignore_cache) = @_;
                   8244: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8245: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8246: 	my @config = <$config>;
                   8247: 	&parse_hosts_tab(\@config);
                   8248: 	close($config);
                   8249: 	$loaded=1;
1.1       albertel 8250:     }
1.852     albertel 8251: 
1.838     albertel 8252:     sub hostname {
1.852     albertel 8253: 	&load_hosts_tab() if (!$loaded);
                   8254: 
1.838     albertel 8255: 	my ($lonid) = @_;
                   8256: 	return $hostname{$lonid};
                   8257:     }
1.845     albertel 8258: 
1.838     albertel 8259:     sub all_hostnames {
1.852     albertel 8260: 	&load_hosts_tab() if (!$loaded);
                   8261: 
1.838     albertel 8262: 	return %hostname;
                   8263:     }
1.845     albertel 8264: 
1.888     albertel 8265:     sub all_names {
                   8266: 	&load_hosts_tab() if (!$loaded);
                   8267: 
                   8268: 	return %name_to_host;
                   8269:     }
                   8270: 
1.845     albertel 8271:     sub is_library {
1.852     albertel 8272: 	&load_hosts_tab() if (!$loaded);
                   8273: 
1.845     albertel 8274: 	return exists($libserv{$_[0]});
                   8275:     }
                   8276: 
                   8277:     sub all_library {
1.852     albertel 8278: 	&load_hosts_tab() if (!$loaded);
                   8279: 
1.845     albertel 8280: 	return %libserv;
                   8281:     }
                   8282: 
1.841     albertel 8283:     sub get_servers {
1.852     albertel 8284: 	&load_hosts_tab() if (!$loaded);
                   8285: 
1.841     albertel 8286: 	my ($domain,$type) = @_;
                   8287: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8288: 	                                          : %hostname;
                   8289: 	my %result;
1.842     albertel 8290: 	if (ref($domain) eq 'ARRAY') {
                   8291: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8292: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8293: 		    $result{$host} = $hostname;
                   8294: 		}
                   8295: 	    }
                   8296: 	} else {
                   8297: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8298: 		if ($hostdom{$host} eq $domain) {
                   8299: 		    $result{$host} = $hostname;
                   8300: 		}
1.841     albertel 8301: 	    }
                   8302: 	}
                   8303: 	return %result;
                   8304:     }
1.845     albertel 8305: 
1.844     albertel 8306:     sub host_domain {
1.852     albertel 8307: 	&load_hosts_tab() if (!$loaded);
                   8308: 
1.844     albertel 8309: 	my ($lonid) = @_;
                   8310: 	return $hostdom{$lonid};
                   8311:     }
                   8312: 
1.841     albertel 8313:     sub all_domains {
1.852     albertel 8314: 	&load_hosts_tab() if (!$loaded);
                   8315: 
1.841     albertel 8316: 	my %seen;
                   8317: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8318: 	return @uniq;
                   8319:     }
1.1       albertel 8320: }
                   8321: 
1.847     albertel 8322: { 
                   8323:     my %iphost;
1.856     albertel 8324:     my %name_to_ip;
                   8325:     my %lonid_to_ip;
1.869     albertel 8326: 
1.847     albertel 8327:     sub get_hosts_from_ip {
                   8328: 	my ($ip) = @_;
                   8329: 	my %iphosts = &get_iphost();
                   8330: 	if (ref($iphosts{$ip})) {
                   8331: 	    return @{$iphosts{$ip}};
                   8332: 	}
                   8333: 	return;
1.839     albertel 8334:     }
1.864     albertel 8335:     
                   8336:     sub reset_hosts_ip_info {
                   8337: 	undef(%iphost);
                   8338: 	undef(%name_to_ip);
                   8339: 	undef(%lonid_to_ip);
                   8340:     }
1.856     albertel 8341: 
                   8342:     sub get_host_ip {
                   8343: 	my ($lonid) = @_;
                   8344: 	if (exists($lonid_to_ip{$lonid})) {
                   8345: 	    return $lonid_to_ip{$lonid};
                   8346: 	}
                   8347: 	my $name=&hostname($lonid);
                   8348:    	my $ip = gethostbyname($name);
                   8349: 	return if (!$ip || length($ip) ne 4);
                   8350: 	$ip=inet_ntoa($ip);
                   8351: 	$name_to_ip{$name}   = $ip;
                   8352: 	$lonid_to_ip{$lonid} = $ip;
                   8353: 	return $ip;
                   8354:     }
1.847     albertel 8355:     
                   8356:     sub get_iphost {
1.869     albertel 8357: 	my ($ignore_cache) = @_;
1.894     albertel 8358: 
1.869     albertel 8359: 	if (!$ignore_cache) {
                   8360: 	    if (%iphost) {
                   8361: 		return %iphost;
                   8362: 	    }
                   8363: 	    my ($ip_info,$cached)=
                   8364: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8365: 	    if ($cached) {
                   8366: 		%iphost      = %{$ip_info->[0]};
                   8367: 		%name_to_ip  = %{$ip_info->[1]};
                   8368: 		%lonid_to_ip = %{$ip_info->[2]};
                   8369: 		return %iphost;
                   8370: 	    }
                   8371: 	}
1.894     albertel 8372: 
                   8373: 	# get yesterday's info for fallback
                   8374: 	my %old_name_to_ip;
                   8375: 	my ($ip_info,$cached)=
                   8376: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8377: 	if ($cached) {
                   8378: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8379: 	}
                   8380: 
1.888     albertel 8381: 	my %name_to_host = &all_names();
                   8382: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8383: 	    my $ip;
                   8384: 	    if (!exists($name_to_ip{$name})) {
                   8385: 		$ip = gethostbyname($name);
                   8386: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8387: 		    if (defined($old_name_to_ip{$name})) {
                   8388: 			$ip = $old_name_to_ip{$name};
                   8389: 			&logthis("Can't find $name defaulting to old $ip");
                   8390: 		    } else {
                   8391: 			&logthis("Name $name no IP found");
                   8392: 			next;
                   8393: 		    }
                   8394: 		} else {
                   8395: 		    $ip=inet_ntoa($ip);
1.847     albertel 8396: 		}
                   8397: 		$name_to_ip{$name} = $ip;
                   8398: 	    } else {
                   8399: 		$ip = $name_to_ip{$name};
1.653     albertel 8400: 	    }
1.888     albertel 8401: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8402: 		$lonid_to_ip{$id} = $ip;
                   8403: 	    }
                   8404: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8405: 	}
1.869     albertel 8406: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8407: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8408: 				      48*60*60);
1.869     albertel 8409: 
1.847     albertel 8410: 	return %iphost;
1.598     albertel 8411:     }
                   8412: }
                   8413: 
1.862     albertel 8414: BEGIN {
                   8415: 
                   8416: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8417:     unless ($readit) {
                   8418: {
                   8419:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8420:     %perlvar = (%perlvar,%{$configvars});
                   8421: }
                   8422: 
                   8423: 
1.1       albertel 8424: # ------------------------------------------------------ Read spare server file
                   8425: {
1.448     albertel 8426:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8427: 
                   8428:     while (my $configline=<$config>) {
                   8429:        chomp($configline);
1.284     matthew  8430:        if ($configline) {
1.784     albertel 8431: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8432: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8433: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8434:        }
                   8435:     }
1.448     albertel 8436:     close($config);
1.1       albertel 8437: }
1.11      www      8438: # ------------------------------------------------------------ Read permissions
                   8439: {
1.448     albertel 8440:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8441: 
                   8442:     while (my $configline=<$config>) {
1.448     albertel 8443: 	chomp($configline);
                   8444: 	if ($configline) {
                   8445: 	    my ($role,$perm)=split(/ /,$configline);
                   8446: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8447: 	}
1.11      www      8448:     }
1.448     albertel 8449:     close($config);
1.11      www      8450: }
                   8451: 
                   8452: # -------------------------------------------- Read plain texts for permissions
                   8453: {
1.448     albertel 8454:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8455: 
                   8456:     while (my $configline=<$config>) {
1.448     albertel 8457: 	chomp($configline);
                   8458: 	if ($configline) {
1.742     raeburn  8459: 	    my ($short,@plain)=split(/:/,$configline);
                   8460:             %{$prp{$short}} = ();
                   8461: 	    if (@plain > 0) {
                   8462:                 $prp{$short}{'std'} = $plain[0];
                   8463:                 for (my $i=1; $i<@plain; $i++) {
                   8464:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8465:                 }
                   8466:             }
1.448     albertel 8467: 	}
1.135     www      8468:     }
1.448     albertel 8469:     close($config);
1.135     www      8470: }
                   8471: 
                   8472: # ---------------------------------------------------------- Read package table
                   8473: {
1.448     albertel 8474:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8475: 
                   8476:     while (my $configline=<$config>) {
1.483     albertel 8477: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8478: 	chomp($configline);
                   8479: 	my ($short,$plain)=split(/:/,$configline);
                   8480: 	my ($pack,$name)=split(/\&/,$short);
                   8481: 	if ($plain ne '') {
                   8482: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8483: 	    $packagetab{$short}=$plain; 
                   8484: 	}
1.11      www      8485:     }
1.448     albertel 8486:     close($config);
1.329     matthew  8487: }
                   8488: 
                   8489: # ------------- set up temporary directory
                   8490: {
                   8491:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8492: 
1.11      www      8493: }
                   8494: 
1.794     albertel 8495: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8496: 				'compress_threshold'=> 20_000,
                   8497:  			        });
1.185     www      8498: 
1.281     www      8499: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8500: $dumpcount=0;
1.22      www      8501: 
1.163     harris41 8502: &logtouch();
1.672     albertel 8503: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8504: $readit=1;
1.564     albertel 8505:     {
                   8506: 	use integer;
                   8507: 	my $test=(2**32)+1;
1.568     albertel 8508: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8509: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8510:     }
1.195     www      8511: }
1.1       albertel 8512: }
1.179     www      8513: 
1.1       albertel 8514: 1;
1.191     harris41 8515: __END__
                   8516: 
1.243     albertel 8517: =pod
                   8518: 
1.191     harris41 8519: =head1 NAME
                   8520: 
1.243     albertel 8521: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8522: 
                   8523: =head1 SYNOPSIS
                   8524: 
1.243     albertel 8525: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8526: 
                   8527:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8528: 
1.243     albertel 8529: Common parameters:
                   8530: 
                   8531: =over 4
                   8532: 
                   8533: =item *
                   8534: 
                   8535: $uname : an internal username (if $cname expecting a course Id specifically)
                   8536: 
                   8537: =item *
                   8538: 
                   8539: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8540: 
                   8541: =item *
                   8542: 
                   8543: $symb : a resource instance identifier
                   8544: 
                   8545: =item *
                   8546: 
                   8547: $namespace : the name of a .db file that contains the data needed or
                   8548: being set.
                   8549: 
                   8550: =back
                   8551: 
1.394     bowersj2 8552: =head1 OVERVIEW
1.191     harris41 8553: 
1.394     bowersj2 8554: lonnet provides subroutines which interact with the
                   8555: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8556: about classes, users, and resources.
1.243     albertel 8557: 
                   8558: For many of these objects you can also use this to store data about
                   8559: them or modify them in various ways.
1.191     harris41 8560: 
1.394     bowersj2 8561: =head2 Symbs
1.191     harris41 8562: 
1.394     bowersj2 8563: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8564: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8565: map, the resource number of the resource in the map, and the URL of
                   8566: the resource itself. The latter is somewhat redundant, but might help
                   8567: if maps change.
                   8568: 
                   8569: An example is
                   8570: 
                   8571:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8572: 
                   8573: The respective map entry is
                   8574: 
                   8575:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8576:   title="Problem 2">
                   8577:  </resource>
                   8578: 
                   8579: Symbs are used by the random number generator, as well as to store and
                   8580: restore data specific to a certain instance of for example a problem.
                   8581: 
                   8582: =head2 Storing And Retrieving Data
                   8583: 
                   8584: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8585: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8586: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8587: is is the non-critical message twin of cstore. These functions are for
                   8588: handlers to store a perl hash to a user's permanent data space in an
                   8589: easy manner, and to retrieve it again on another call. It is expected
                   8590: that a handler would use this once at the beginning to retrieve data,
                   8591: and then again once at the end to send only the new data back.
                   8592: 
                   8593: The data is stored in the user's data directory on the user's
                   8594: homeserver under the ID of the course.
                   8595: 
                   8596: The hash that is returned by restore will have all of the previous
                   8597: value for all of the elements of the hash.
                   8598: 
                   8599: Example:
                   8600: 
                   8601:  #creating a hash
                   8602:  my %hash;
                   8603:  $hash{'foo'}='bar';
                   8604: 
                   8605:  #storing it
                   8606:  &Apache::lonnet::cstore(\%hash);
                   8607: 
                   8608:  #changing a value
                   8609:  $hash{'foo'}='notbar';
                   8610: 
                   8611:  #adding a new value
                   8612:  $hash{'bar'}='foo';
                   8613:  &Apache::lonnet::cstore(\%hash);
                   8614: 
                   8615:  #retrieving the hash
                   8616:  my %history=&Apache::lonnet::restore();
                   8617: 
                   8618:  #print the hash
                   8619:  foreach my $key (sort(keys(%history))) {
                   8620:    print("\%history{$key} = $history{$key}");
                   8621:  }
                   8622: 
                   8623: Will print out:
1.191     harris41 8624: 
1.394     bowersj2 8625:  %history{1:foo} = bar
                   8626:  %history{1:keys} = foo:timestamp
                   8627:  %history{1:timestamp} = 990455579
                   8628:  %history{2:bar} = foo
                   8629:  %history{2:foo} = notbar
                   8630:  %history{2:keys} = foo:bar:timestamp
                   8631:  %history{2:timestamp} = 990455580
                   8632:  %history{bar} = foo
                   8633:  %history{foo} = notbar
                   8634:  %history{timestamp} = 990455580
                   8635:  %history{version} = 2
                   8636: 
                   8637: Note that the special hash entries C<keys>, C<version> and
                   8638: C<timestamp> were added to the hash. C<version> will be equal to the
                   8639: total number of versions of the data that have been stored. The
                   8640: C<timestamp> attribute will be the UNIX time the hash was
                   8641: stored. C<keys> is available in every historical section to list which
                   8642: keys were added or changed at a specific historical revision of a
                   8643: hash.
                   8644: 
                   8645: B<Warning>: do not store the hash that restore returns directly. This
                   8646: will cause a mess since it will restore the historical keys as if the
                   8647: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8648: 
1.394     bowersj2 8649: Calling convention:
1.191     harris41 8650: 
1.394     bowersj2 8651:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8652:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8653: 
1.394     bowersj2 8654: For more detailed information, see lonnet specific documentation.
1.191     harris41 8655: 
1.394     bowersj2 8656: =head1 RETURN MESSAGES
1.191     harris41 8657: 
1.394     bowersj2 8658: =over 4
1.191     harris41 8659: 
1.394     bowersj2 8660: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8661: 
1.394     bowersj2 8662: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8663: when the connection is brought back up
1.191     harris41 8664: 
1.394     bowersj2 8665: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8666: for later delivery
1.191     harris41 8667: 
1.394     bowersj2 8668: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8669: 
1.394     bowersj2 8670: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8671: that was requested
1.191     harris41 8672: 
1.243     albertel 8673: =back
1.191     harris41 8674: 
1.243     albertel 8675: =head1 PUBLIC SUBROUTINES
1.191     harris41 8676: 
1.243     albertel 8677: =head2 Session Environment Functions
1.191     harris41 8678: 
1.243     albertel 8679: =over 4
1.191     harris41 8680: 
1.394     bowersj2 8681: =item * 
                   8682: X<appenv()>
                   8683: B<appenv(%hash)>: the value of %hash is written to
                   8684: the user envirnoment file, and will be restored for each access this
1.620     albertel 8685: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8686: process
1.191     harris41 8687: 
                   8688: =item *
1.394     bowersj2 8689: X<delenv()>
                   8690: B<delenv($regexp)>: removes all items from the session
                   8691: environment file that matches the regular expression in $regexp. The
1.620     albertel 8692: values are also delted from the current processes %env.
1.191     harris41 8693: 
1.795     albertel 8694: =item * get_env_multiple($name) 
                   8695: 
                   8696: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8697: values may be defined and end up as an array ref.
                   8698: 
                   8699: returns an array of values
                   8700: 
1.243     albertel 8701: =back
                   8702: 
                   8703: =head2 User Information
1.191     harris41 8704: 
1.243     albertel 8705: =over 4
1.191     harris41 8706: 
                   8707: =item *
1.394     bowersj2 8708: X<queryauthenticate()>
                   8709: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8710: authentication scheme
                   8711: 
                   8712: =item *
1.394     bowersj2 8713: X<authenticate()>
                   8714: B<authenticate($uname,$upass,$udom)>: try to
                   8715: authenticate user from domain's lib servers (first use the current
                   8716: one). C<$upass> should be the users password.
1.191     harris41 8717: 
                   8718: =item *
1.394     bowersj2 8719: X<homeserver()>
                   8720: B<homeserver($uname,$udom)>: find the server which has
                   8721: the user's directory and files (there must be only one), this caches
                   8722: the answer, and also caches if there is a borken connection.
1.191     harris41 8723: 
                   8724: =item *
1.394     bowersj2 8725: X<idget()>
                   8726: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8727: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8728: username, and only 1 username per ID in a specific domain) (returns
                   8729: hash: id=>name,id=>name)
1.191     harris41 8730: 
                   8731: =item *
1.394     bowersj2 8732: X<idrget()>
                   8733: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8734: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8735: 
                   8736: =item *
1.394     bowersj2 8737: X<idput()>
                   8738: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8739: 
                   8740: =item *
1.394     bowersj2 8741: X<rolesinit()>
                   8742: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8743: 
                   8744: =item *
1.551     albertel 8745: X<getsection()>
                   8746: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8747: course $cname, return section name/number or '' for "not in course"
                   8748: and '-1' for "no section"
                   8749: 
                   8750: =item *
1.394     bowersj2 8751: X<userenvironment()>
                   8752: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8753: passed in @what from the requested user's environment, returns a hash
                   8754: 
1.858     raeburn  8755: =item * 
                   8756: X<userlog_query()>
1.859     albertel 8757: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8758: activity.log file. %filters defines filters applied when parsing the
                   8759: log file. These can be start or end timestamps, or the type of action
                   8760: - log to look for Login or Logout events, check for Checkin or
                   8761: Checkout, role for role selection. The response is in the form
                   8762: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8763: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8764: 
1.243     albertel 8765: =back
                   8766: 
                   8767: =head2 User Roles
                   8768: 
                   8769: =over 4
                   8770: 
                   8771: =item *
                   8772: 
1.810     raeburn  8773: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8774:  F: full access
                   8775:  U,I,K: authentication modes (cxx only)
                   8776:  '': forbidden
                   8777:  1: user needs to choose course
                   8778:  2: browse allowed
1.766     albertel 8779:  A: passphrase authentication needed
1.243     albertel 8780: 
                   8781: =item *
                   8782: 
                   8783: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8784: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8785: and course level
                   8786: 
                   8787: =item *
                   8788: 
                   8789: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8790: explanation of a user role term
                   8791: 
1.832     raeburn  8792: =item *
                   8793: 
1.858     raeburn  8794: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8795: All arguments are optional. Returns a hash of a roles, either for
                   8796: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8797: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8798: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8799: and value is set to colon-separated start and end times for the role.
                   8800: If no username and domain are specified, will default to current
                   8801: user/domain. Types, roles, and roledoms are references to arrays,
                   8802: of role statuses (active, future or previous), roles 
                   8803: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8804: to restrict the list of roles reported. If no array ref is 
                   8805: provided for types, will default to return only active roles.
1.834     albertel 8806: 
1.243     albertel 8807: =back
                   8808: 
                   8809: =head2 User Modification
                   8810: 
                   8811: =over 4
                   8812: 
                   8813: =item *
                   8814: 
                   8815: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8816: user for the level given by URL.  Optional start and end dates (leave empty
                   8817: string or zero for "no date")
1.191     harris41 8818: 
                   8819: =item *
                   8820: 
1.243     albertel 8821: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8822: change a users, password, possible return values are: ok,
                   8823: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8824: refused
1.191     harris41 8825: 
                   8826: =item *
                   8827: 
1.243     albertel 8828: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8829: 
                   8830: =item *
                   8831: 
1.243     albertel 8832: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8833: modify user
1.191     harris41 8834: 
                   8835: =item *
                   8836: 
1.286     matthew  8837: modifystudent
                   8838: 
                   8839: modify a students enrollment and identification information.
                   8840: The course id is resolved based on the current users environment.  
                   8841: This means the envoking user must be a course coordinator or otherwise
                   8842: associated with a course.
                   8843: 
1.297     matthew  8844: This call is essentially a wrapper for lonnet::modifyuser and
                   8845: lonnet::modify_student_enrollment
1.286     matthew  8846: 
                   8847: Inputs: 
                   8848: 
                   8849: =over 4
                   8850: 
                   8851: =item B<$udom> Students loncapa domain
                   8852: 
                   8853: =item B<$uname> Students loncapa login name
                   8854: 
                   8855: =item B<$uid> Students id/student number
                   8856: 
                   8857: =item B<$umode> Students authentication mode
                   8858: 
                   8859: =item B<$upass> Students password
                   8860: 
                   8861: =item B<$first> Students first name
                   8862: 
                   8863: =item B<$middle> Students middle name
                   8864: 
                   8865: =item B<$last> Students last name
                   8866: 
                   8867: =item B<$gene> Students generation
                   8868: 
                   8869: =item B<$usec> Students section in course
                   8870: 
                   8871: =item B<$end> Unix time of the roles expiration
                   8872: 
                   8873: =item B<$start> Unix time of the roles start date
                   8874: 
                   8875: =item B<$forceid> If defined, allow $uid to be changed
                   8876: 
                   8877: =item B<$desiredhome> server to use as home server for student
                   8878: 
                   8879: =back
1.297     matthew  8880: 
                   8881: =item *
                   8882: 
                   8883: modify_student_enrollment
                   8884: 
                   8885: Change a students enrollment status in a class.  The environment variable
                   8886: 'role.request.course' must be defined for this function to proceed.
                   8887: 
                   8888: Inputs:
                   8889: 
                   8890: =over 4
                   8891: 
                   8892: =item $udom, students domain
                   8893: 
                   8894: =item $uname, students name
                   8895: 
                   8896: =item $uid, students user id
                   8897: 
                   8898: =item $first, students first name
                   8899: 
                   8900: =item $middle
                   8901: 
                   8902: =item $last
                   8903: 
                   8904: =item $gene
                   8905: 
                   8906: =item $usec
                   8907: 
                   8908: =item $end
                   8909: 
                   8910: =item $start
                   8911: 
                   8912: =back
                   8913: 
1.191     harris41 8914: 
                   8915: =item *
                   8916: 
1.243     albertel 8917: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8918: custom role; give a custom role to a user for the level given by URL.  Specify
                   8919: name and domain of role author, and role name
1.191     harris41 8920: 
                   8921: =item *
                   8922: 
1.243     albertel 8923: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8924: 
                   8925: =item *
                   8926: 
1.243     albertel 8927: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8928: 
                   8929: =back
                   8930: 
                   8931: =head2 Course Infomation
                   8932: 
                   8933: =over 4
1.191     harris41 8934: 
                   8935: =item *
                   8936: 
1.631     albertel 8937: coursedescription($courseid) : returns a hash of information about the
                   8938: specified course id, including all environment settings for the
                   8939: course, the description of the course will be in the hash under the
                   8940: key 'description'
1.191     harris41 8941: 
                   8942: =item *
                   8943: 
1.624     albertel 8944: resdata($name,$domain,$type,@which) : request for current parameter
                   8945: setting for a specific $type, where $type is either 'course' or 'user',
                   8946: @what should be a list of parameters to ask about. This routine caches
                   8947: answers for 5 minutes.
1.243     albertel 8948: 
1.877     foxr     8949: =item *
                   8950: 
                   8951: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8952: data base, returning a hash that is keyed by the resource name and has
                   8953: values that are the resource value.  I believe that the timestamps and
                   8954: versions are also returned.
                   8955: 
                   8956: 
1.243     albertel 8957: =back
                   8958: 
                   8959: =head2 Course Modification
                   8960: 
                   8961: =over 4
1.191     harris41 8962: 
                   8963: =item *
                   8964: 
1.243     albertel 8965: writecoursepref($courseid,%prefs) : write preferences (environment
                   8966: database) for a course
1.191     harris41 8967: 
                   8968: =item *
                   8969: 
1.243     albertel 8970: createcourse($udom,$description,$url) : make/modify course
                   8971: 
                   8972: =back
                   8973: 
                   8974: =head2 Resource Subroutines
                   8975: 
                   8976: =over 4
1.191     harris41 8977: 
                   8978: =item *
                   8979: 
1.243     albertel 8980: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8981: 
                   8982: =item *
                   8983: 
1.243     albertel 8984: repcopy($filename) : subscribes to the requested file, and attempts to
                   8985: replicate from the owning library server, Might return
1.607     raeburn  8986: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8987: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8988: resource. Expects the local filesystem pathname
                   8989: (/home/httpd/html/res/....)
                   8990: 
                   8991: =back
                   8992: 
                   8993: =head2 Resource Information
                   8994: 
                   8995: =over 4
1.191     harris41 8996: 
                   8997: =item *
                   8998: 
1.243     albertel 8999: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9000: a vairety of different possible values, $varname should be a request
                   9001: string, and the other parameters can be used to specify who and what
                   9002: one is asking about.
                   9003: 
                   9004: Possible values for $varname are environment.lastname (or other item
                   9005: from the envirnment hash), user.name (or someother aspect about the
                   9006: user), resource.0.maxtries (or some other part and parameter of a
                   9007: resource)
1.204     albertel 9008: 
                   9009: =item *
                   9010: 
1.243     albertel 9011: directcondval($number) : get current value of a condition; reads from a state
                   9012: string
1.204     albertel 9013: 
                   9014: =item *
                   9015: 
1.243     albertel 9016: condval($condidx) : value of condition index based on state
1.204     albertel 9017: 
                   9018: =item *
                   9019: 
1.243     albertel 9020: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9021: resource's metadata, $what should be either a specific key, or either
                   9022: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9023: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9024: 
                   9025: this function automatically caches all requests
1.191     harris41 9026: 
                   9027: =item *
                   9028: 
1.243     albertel 9029: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9030: network of library servers; returns file handle of where SQL and regex results
                   9031: will be stored for query
1.191     harris41 9032: 
                   9033: =item *
                   9034: 
1.243     albertel 9035: symbread($filename) : return symbolic list entry (filename argument optional);
                   9036: returns the data handle
1.191     harris41 9037: 
                   9038: =item *
                   9039: 
1.243     albertel 9040: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9041: a possible symb for the URL in $thisfn, and if is an encryypted
                   9042: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9043: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9044: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9045: 
1.191     harris41 9046: 
                   9047: =item *
                   9048: 
1.243     albertel 9049: symbclean($symb) : removes versions numbers from a symb, returns the
                   9050: cleaned symb
1.191     harris41 9051: 
                   9052: =item *
                   9053: 
1.243     albertel 9054: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9055: course map, user must be in a course for it to work.
1.191     harris41 9056: 
                   9057: =item *
                   9058: 
1.243     albertel 9059: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9060: 
                   9061: =item *
                   9062: 
1.243     albertel 9063: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9064: a random seed, all arguments are optional, if they aren't sent it uses the
                   9065: environment to derive them. Note: if symb isn't sent and it can't get one
                   9066: from &symbread it will use the current time as its return value
1.191     harris41 9067: 
                   9068: =item *
                   9069: 
1.243     albertel 9070: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9071: unfakeable, receipt
1.191     harris41 9072: 
                   9073: =item *
                   9074: 
1.620     albertel 9075: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9076: 
                   9077: =item *
                   9078: 
1.243     albertel 9079: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9080: 
                   9081: =item *
                   9082: 
1.243     albertel 9083: 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 9084: 
                   9085: =item *
                   9086: 
1.243     albertel 9087: 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 9088: 
                   9089: =item *
                   9090: 
1.243     albertel 9091: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9092: 
                   9093: =item *
                   9094: 
1.243     albertel 9095: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9096: forcing spreadsheet to reevaluate the resource scores next time.
                   9097: 
                   9098: =back
                   9099: 
                   9100: =head2 Storing/Retreiving Data
                   9101: 
                   9102: =over 4
1.191     harris41 9103: 
                   9104: =item *
                   9105: 
1.243     albertel 9106: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9107: for this url; hashref needs to be given and should be a \%hashname; the
                   9108: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9109: be derived from the env
1.191     harris41 9110: 
                   9111: =item *
                   9112: 
1.243     albertel 9113: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9114: uses critical subroutine
1.191     harris41 9115: 
                   9116: =item *
                   9117: 
1.243     albertel 9118: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9119: all args are optional
1.191     harris41 9120: 
                   9121: =item *
                   9122: 
1.717     albertel 9123: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9124: dumps the complete (or key matching regexp) namespace into a hash
                   9125: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9126: normally &store()ed into
                   9127: 
                   9128: $range should be either an integer '100' (give me the first 100
                   9129:                                            matching records)
                   9130:               or be  two integers sperated by a - with no spaces
                   9131:                  '30-50' (give me the 30th through the 50th matching
                   9132:                           records)
                   9133: 
                   9134: 
                   9135: =item *
                   9136: 
                   9137: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9138: replaces a &store() version of data with a replacement set of data
                   9139: for a particular resource in a namespace passed in the $storehash hash 
                   9140: reference
                   9141: 
                   9142: =item *
                   9143: 
1.243     albertel 9144: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9145: works very similar to store/cstore, but all data is stored in a
                   9146: temporary location and can be reset using tmpreset, $storehash should
                   9147: be a hash reference, returns nothing on success
1.191     harris41 9148: 
                   9149: =item *
                   9150: 
1.243     albertel 9151: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9152: similar to restore, but all data is stored in a temporary location and
                   9153: can be reset using tmpreset. Returns a hash of values on success,
                   9154: error string otherwise.
1.191     harris41 9155: 
                   9156: =item *
                   9157: 
1.243     albertel 9158: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9159: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9160: 
                   9161: =item *
                   9162: 
1.243     albertel 9163: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9164: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9165: 
                   9166: =item *
                   9167: 
1.243     albertel 9168: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9169: namesp ($udom and $uname are optional)
1.191     harris41 9170: 
                   9171: =item *
                   9172: 
1.702     albertel 9173: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9174: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9175: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9176: 
1.702     albertel 9177: $range should be either an integer '100' (give me the first 100
                   9178:                                            matching records)
                   9179:               or be  two integers sperated by a - with no spaces
                   9180:                  '30-50' (give me the 30th through the 50th matching
                   9181:                           records)
1.449     matthew  9182: =item *
                   9183: 
                   9184: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9185: $store can be a scalar, an array reference, or if the amount to be 
                   9186: incremented is > 1, a hash reference.
                   9187: 
                   9188: ($udom and $uname are optional)
1.191     harris41 9189: 
                   9190: =item *
                   9191: 
1.243     albertel 9192: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9193: ($udom and $uname are optional)
1.191     harris41 9194: 
                   9195: =item *
                   9196: 
1.243     albertel 9197: cput($namespace,$storehash,$udom,$uname) : critical put
                   9198: ($udom and $uname are optional)
1.191     harris41 9199: 
                   9200: =item *
                   9201: 
1.748     albertel 9202: newput($namespace,$storehash,$udom,$uname) :
                   9203: 
                   9204: Attempts to store the items in the $storehash, but only if they don't
                   9205: currently exist, if this succeeds you can be certain that you have 
                   9206: successfully created a new key value pair in the $namespace db.
                   9207: 
                   9208: 
                   9209: Args:
                   9210:  $namespace: name of database to store values to
                   9211:  $storehash: hashref to store to the db
                   9212:  $udom: (optional) domain of user containing the db
                   9213:  $uname: (optional) name of user caontaining the db
                   9214: 
                   9215: Returns:
                   9216:  'ok' -> succeeded in storing all keys of $storehash
                   9217:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9218:                         least <key> already existed in the db (other
                   9219:                         requested keys may also already exist)
                   9220:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9221:  'con_lost' -> unable to contact request server
                   9222:  'refused' -> action was not allowed by remote machine
                   9223: 
                   9224: 
                   9225: =item *
                   9226: 
1.243     albertel 9227: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9228: reference filled in from namesp (encrypts the return communication)
                   9229: ($udom and $uname are optional)
1.191     harris41 9230: 
                   9231: =item *
                   9232: 
1.243     albertel 9233: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9234: critical subroutine
                   9235: 
1.806     raeburn  9236: =item *
                   9237: 
1.860     raeburn  9238: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9239: array reference filled in from namespace found in domain level on either
                   9240: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9241: 
                   9242: =item *
                   9243: 
1.860     raeburn  9244: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9245: domain level either on specified domain server ($uhome) or primary domain 
                   9246: server ($udom and $uhome are optional)
1.806     raeburn  9247: 
1.243     albertel 9248: =back
                   9249: 
                   9250: =head2 Network Status Functions
                   9251: 
                   9252: =over 4
1.191     harris41 9253: 
                   9254: =item *
                   9255: 
                   9256: dirlist($uri) : return directory list based on URI
                   9257: 
                   9258: =item *
                   9259: 
1.243     albertel 9260: spareserver() : find server with least workload from spare.tab
                   9261: 
                   9262: =back
                   9263: 
                   9264: =head2 Apache Request
                   9265: 
                   9266: =over 4
1.191     harris41 9267: 
                   9268: =item *
                   9269: 
1.243     albertel 9270: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9271: localhost, posts hash
                   9272: 
                   9273: =back
                   9274: 
                   9275: =head2 Data to String to Data
                   9276: 
                   9277: =over 4
1.191     harris41 9278: 
                   9279: =item *
                   9280: 
1.243     albertel 9281: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9282: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9283: 
                   9284: =item *
                   9285: 
1.243     albertel 9286: hashref2str($hashref) : convert a hashref into a string complete with
                   9287: escaping and '=' and '&' separators, supports elements that are
                   9288: arrayrefs and hashrefs
1.191     harris41 9289: 
                   9290: =item *
                   9291: 
1.243     albertel 9292: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9293: with escaping and '&' separators, supports elements that are arrayrefs
                   9294: and hashrefs
1.191     harris41 9295: 
                   9296: =item *
                   9297: 
1.243     albertel 9298: str2hash($string) : convert string to hash using unescaping and
                   9299: splitting on '=' and '&', supports elements that are arrayrefs and
                   9300: hashrefs
1.191     harris41 9301: 
                   9302: =item *
                   9303: 
1.243     albertel 9304: str2array($string) : convert string to hash using unescaping and
                   9305: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9306: 
                   9307: =back
                   9308: 
                   9309: =head2 Logging Routines
                   9310: 
                   9311: =over 4
                   9312: 
                   9313: These routines allow one to make log messages in the lonnet.log and
                   9314: lonnet.perm logfiles.
1.191     harris41 9315: 
                   9316: =item *
                   9317: 
1.243     albertel 9318: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9319: 
                   9320: =item *
                   9321: 
1.243     albertel 9322: logthis() : append message to the normal lonnet.log file, it gets
                   9323: preiodically rolled over and deleted.
1.191     harris41 9324: 
                   9325: =item *
                   9326: 
1.243     albertel 9327: logperm() : append a permanent message to lonnet.perm.log, this log
                   9328: file never gets deleted by any automated portion of the system, only
                   9329: messages of critical importance should go in here.
                   9330: 
                   9331: =back
                   9332: 
                   9333: =head2 General File Helper Routines
                   9334: 
                   9335: =over 4
1.191     harris41 9336: 
                   9337: =item *
                   9338: 
1.481     raeburn  9339: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9340: (a) files in /uploaded
                   9341:   (i) If a local copy of the file exists - 
                   9342:       compares modification date of local copy with last-modified date for 
                   9343:       definitive version stored on home server for course. If local copy is 
                   9344:       stale, requests a new version from the home server and stores it. 
                   9345:       If the original has been removed from the home server, then local copy 
                   9346:       is unlinked.
                   9347:   (ii) If local copy does not exist -
                   9348:       requests the file from the home server and stores it. 
                   9349:   
                   9350:   If $caller is 'uploadrep':  
                   9351:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9352:     for request for files originally uploaded via DOCS. 
                   9353:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9354:   
                   9355:   Otherwise:
                   9356:      This indicates a call from the content generation phase of the request.
                   9357:      -  returns the entire contents of the file or -1.
                   9358:      
                   9359: (b) files in /res
                   9360:    - returns the entire contents of a file or -1; 
                   9361:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9362: 
1.712     albertel 9363: 
                   9364: =item *
                   9365: 
                   9366: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9367:                   reference
                   9368: 
                   9369: returns either a stat() list of data about the file or an empty list
                   9370: if the file doesn't exist or couldn't find out about it (connection
                   9371: problems or user unknown)
                   9372: 
1.191     harris41 9373: =item *
                   9374: 
1.243     albertel 9375: filelocation($dir,$file) : returns file system location of a file
                   9376: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9377: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9378: and a file of ../bob will become /a/bob)
1.191     harris41 9379: 
                   9380: =item *
                   9381: 
                   9382: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9383: filelocation except for hrefs
                   9384: 
                   9385: =item *
                   9386: 
                   9387: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9388: 
1.243     albertel 9389: =back
                   9390: 
1.608     albertel 9391: =head2 Usererfile file routines (/uploaded*)
                   9392: 
                   9393: =over 4
                   9394: 
                   9395: =item *
                   9396: 
                   9397: userfileupload(): main rotine for putting a file in a user or course's
                   9398:                   filespace, arguments are,
                   9399: 
1.620     albertel 9400:  formname - required - this is the name of the element in $env where the
1.608     albertel 9401:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9402:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9403:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9404:  coursedoc - if true, store the file in the course of the active role
                   9405:              of the current user
                   9406:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9407:          if undefined, it will be placed in "unknown"
                   9408: 
                   9409:  (This routine calls clean_filename() to remove any dangerous
                   9410:  characters from the filename, and then calls finuserfileupload() to
                   9411:  complete the transaction)
                   9412: 
                   9413:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9414:  and /adm/notfound.html if unsuccessful
                   9415: 
                   9416: =item *
                   9417: 
                   9418: clean_filename(): routine for cleaing a filename up for storage in
                   9419:                  userfile space, argument is:
                   9420: 
                   9421:  filename - proposed filename
                   9422: 
                   9423: returns: the new clean filename
                   9424: 
                   9425: =item *
                   9426: 
                   9427: finishuserfileupload(): routine that creaes and sends the file to
                   9428: userspace, probably shouldn't be called directly
                   9429: 
                   9430:   docuname: username or courseid of destination for the file
                   9431:   docudom: domain of user/course of destination for the file
                   9432:   formname: same as for userfileupload()
                   9433:   fname: filename (inculding subdirectories) for the file
                   9434: 
                   9435:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9436:  and /adm/notfound.html if unsuccessful
                   9437: 
                   9438: =item *
                   9439: 
                   9440: renameuserfile(): renames an existing userfile to a new name
                   9441: 
                   9442:   Args:
                   9443:    docuname: username or courseid of destination for the file
                   9444:    docudom: domain of user/course of destination for the file
                   9445:    old: current file name (including any subdirs under userfiles)
                   9446:    new: desired file name (including any subdirs under userfiles)
                   9447: 
                   9448: =item *
                   9449: 
                   9450: mkdiruserfile(): creates a directory is a userfiles dir
                   9451: 
                   9452:   Args:
                   9453:    docuname: username or courseid of destination for the file
                   9454:    docudom: domain of user/course of destination for the file
                   9455:    dir: dir to create (including any subdirs under userfiles)
                   9456: 
                   9457: =item *
                   9458: 
                   9459: removeuserfile(): removes a file that exists in userfiles
                   9460: 
                   9461:   Args:
                   9462:    docuname: username or courseid of destination for the file
                   9463:    docudom: domain of user/course of destination for the file
                   9464:    fname: filname to delete (including any subdirs under userfiles)
                   9465: 
                   9466: =item *
                   9467: 
                   9468: removeuploadedurl(): convience function for removeuserfile()
                   9469: 
                   9470:   Args:
                   9471:    url:  a full /uploaded/... url to delete
                   9472: 
1.747     albertel 9473: =item * 
                   9474: 
                   9475: get_portfile_permissions():
                   9476:   Args:
                   9477:     domain: domain of user or course contain the portfolio files
                   9478:     user: name of user or num of course contain the portfolio files
                   9479:   Returns:
                   9480:     hashref of a dump of the proper file_permissions.db
                   9481:    
                   9482: 
                   9483: =item * 
                   9484: 
                   9485: get_access_controls():
                   9486: 
                   9487: Args:
                   9488:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9489:   group: (optional) the group you want the files associated with
                   9490:   file: (optional) the file you want access info on
                   9491: 
                   9492: Returns:
1.749     raeburn  9493:     a hash (keys are file names) of hashes containing
                   9494:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9495:         values are XML containing access control settings (see below) 
1.747     albertel 9496: 
                   9497: Internal notes:
                   9498: 
1.749     raeburn  9499:  access controls are stored in file_permissions.db as key=value pairs.
                   9500:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9501:         where scope -> public,guest,course,group,domains or users.
                   9502:               end -> UNIX time for end of access (0 -> no end date)
                   9503:               start -> UNIX time for start of access
                   9504: 
                   9505:     value -> XML description of access control
                   9506:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9507:             <start></start>
                   9508:             <end></end>
                   9509: 
                   9510:             <password></password>  for scope type = guest
                   9511: 
                   9512:             <domain></domain>     for scope type = course or group
                   9513:             <number></number>
                   9514:             <roles id="">
                   9515:              <role></role>
                   9516:              <access></access>
                   9517:              <section></section>
                   9518:              <group></group>
                   9519:             </roles>
                   9520: 
                   9521:             <dom></dom>         for scope type = domains
                   9522: 
                   9523:             <users>             for scope type = users
                   9524:              <user>
                   9525:               <uname></uname>
                   9526:               <udom></udom>
                   9527:              </user>
                   9528:             </users>
                   9529:            </scope> 
                   9530:               
                   9531:  Access data is also aggregated for each file in an additional key=value pair:
                   9532:  key -> path to file/file_name\0accesscontrol 
                   9533:  value -> reference to hash
                   9534:           hash contains key = value pairs
                   9535:           where key = uniqueID:scope_end_start
                   9536:                 value = UNIX time record was last updated
                   9537: 
                   9538:           Used to improve speed of look-ups of access controls for each file.  
                   9539:  
                   9540:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9541: 
                   9542: modify_access_controls():
                   9543: 
                   9544: Modifies access controls for a portfolio file
                   9545: Args
                   9546: 1. file name
                   9547: 2. reference to hash of required changes,
                   9548: 3. domain
                   9549: 4. username
                   9550:   where domain,username are the domain of the portfolio owner 
                   9551:   (either a user or a course) 
                   9552: 
                   9553: Returns:
                   9554: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9555: 2. result of deletions ('ok' or 'error', with error message).
                   9556: 3. reference to hash of any new or updated access controls.
                   9557: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9558:    key = integer (inbound ID)
                   9559:    value = uniqueID  
1.747     albertel 9560: 
1.608     albertel 9561: =back
                   9562: 
1.243     albertel 9563: =head2 HTTP Helper Routines
                   9564: 
                   9565: =over 4
                   9566: 
1.191     harris41 9567: =item *
                   9568: 
                   9569: escape() : unpack non-word characters into CGI-compatible hex codes
                   9570: 
                   9571: =item *
                   9572: 
                   9573: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9574: 
1.243     albertel 9575: =back
                   9576: 
                   9577: =head1 PRIVATE SUBROUTINES
                   9578: 
                   9579: =head2 Underlying communication routines (Shouldn't call)
                   9580: 
                   9581: =over 4
                   9582: 
                   9583: =item *
                   9584: 
                   9585: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9586: 
                   9587: =item *
                   9588: 
                   9589: reply() : uses subreply to send a message to remote machine, logs all failures
                   9590: 
                   9591: =item *
                   9592: 
                   9593: critical() : passes a critical message to another server; if cannot
                   9594: get through then place message in connection buffer directory and
                   9595: returns con_delayed, if incapable of saving message, returns
                   9596: con_failed
                   9597: 
                   9598: =item *
                   9599: 
                   9600: reconlonc() : tries to reconnect lonc client processes.
                   9601: 
                   9602: =back
                   9603: 
                   9604: =head2 Resource Access Logging
                   9605: 
                   9606: =over 4
                   9607: 
                   9608: =item *
                   9609: 
                   9610: flushcourselogs() : flush (save) buffer logs and access logs
                   9611: 
                   9612: =item *
                   9613: 
                   9614: courselog($what) : save message for course in hash
                   9615: 
                   9616: =item *
                   9617: 
                   9618: courseacclog($what) : save message for course using &courselog().  Perform
                   9619: special processing for specific resource types (problems, exams, quizzes, etc).
                   9620: 
1.191     harris41 9621: =item *
                   9622: 
                   9623: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9624: as a PerlChildExitHandler
1.243     albertel 9625: 
                   9626: =back
                   9627: 
                   9628: =head2 Other
                   9629: 
                   9630: =over 4
                   9631: 
                   9632: =item *
                   9633: 
                   9634: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9635: 
                   9636: =back
                   9637: 
                   9638: =cut
1.877     foxr     9639: 

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